diff --git a/.idea/inspectionProfiles/idea_default.xml b/.idea/inspectionProfiles/idea_default.xml
index c26e94dd8ed7..4e177e76dd34 100644
--- a/.idea/inspectionProfiles/idea_default.xml
+++ b/.idea/inspectionProfiles/idea_default.xml
@@ -55,7 +55,6 @@
-
@@ -527,9 +526,6 @@
-
-
-
@@ -698,7 +694,6 @@
-
diff --git a/.idea/inspectionProfiles/idea_default_no_spellchecker.xml b/.idea/inspectionProfiles/idea_default_no_spellchecker.xml
index 12cb6f5f27ce..f0226c22640e 100644
--- a/.idea/inspectionProfiles/idea_default_no_spellchecker.xml
+++ b/.idea/inspectionProfiles/idea_default_no_spellchecker.xml
@@ -529,9 +529,6 @@
-
-
-
@@ -672,7 +669,6 @@
-
diff --git a/.idea/modules.xml b/.idea/modules.xml
index 41a0830f1d18..1c9aa2e4f46b 100644
--- a/.idea/modules.xml
+++ b/.idea/modules.xml
@@ -51,8 +51,8 @@
-
-
+
+
@@ -82,7 +82,7 @@
-
+
@@ -114,8 +114,8 @@
-
-
+
+
@@ -164,7 +164,7 @@
-
+
@@ -201,8 +201,8 @@
-
-
+
+
@@ -214,6 +214,7 @@
+
diff --git a/build/conf/ideaCE-launcher.properties b/build/conf/ideaCE-launcher.properties
index 447e5e48859a..bb8259af9757 100644
--- a/build/conf/ideaCE-launcher.properties
+++ b/build/conf/ideaCE-launcher.properties
@@ -5,4 +5,4 @@ IDC_WINLAUNCHER=__IDE-NAME___LAUNCHER
IDS_PROPS_ENV_VAR=__IDE-NAME___PROPERTIES
IDS_VM_OPTIONS_ENV_VAR=__IDE-NAME___VM_OPTIONS
IDS_ERROR_LAUNCHING_APP=Error launching __IDE-NAME__
-IDS_VM_OPTIONS=-Didea.paths.selector=__PRODUCT_PATHS_SELECTOR__
+IDS_VM_OPTIONS=-Didea.paths.selector=__PRODUCT_PATHS_SELECTOR__ -Didea.jre.check=true
diff --git a/build/conf/ideaCE64-launcher.properties b/build/conf/ideaCE64-launcher.properties
index 03fe514c2f16..ba9686fa0fbf 100644
--- a/build/conf/ideaCE64-launcher.properties
+++ b/build/conf/ideaCE64-launcher.properties
@@ -6,4 +6,4 @@ IDC_WINLAUNCHER=__IDE-NAME___LAUNCHER
IDS_PROPS_ENV_VAR=__IDE-NAME___PROPERTIES
IDS_VM_OPTIONS_ENV_VAR=__IDE-NAME__64_VM_OPTIONS
IDS_ERROR_LAUNCHING_APP=Error launching __IDE-NAME__
-IDS_VM_OPTIONS=-Didea.paths.selector=__PRODUCT_PATHS_SELECTOR__
+IDS_VM_OPTIONS=-Didea.paths.selector=__PRODUCT_PATHS_SELECTOR__ -Didea.jre.check=true
diff --git a/build/conf/mac/Contents/Info.plist b/build/conf/mac/Contents/Info.plist
index f9cec6b77584..1354f7cf8e50 100644
--- a/build/conf/mac/Contents/Info.plist
+++ b/build/conf/mac/Contents/Info.plist
@@ -71,7 +71,7 @@
@@class_path@@
JVMVersion
- 1.6*,1.7+
+ 1.8*,1.8+
MainClass
com.intellij.idea.Main
diff --git a/build/conf/nsis/customInstallActions.nsi b/build/conf/nsis/customInstallActions.nsi
new file mode 100644
index 000000000000..a208f5c07b82
--- /dev/null
+++ b/build/conf/nsis/customInstallActions.nsi
@@ -0,0 +1,38 @@
+!define INSTALL_OPTION_ELEMENTS 4
+
+
+Function customInstallActions
+ DetailPrint "There are no custom install actions."
+FunctionEnd
+
+
+Function ConfirmDesktopShortcut
+ !insertmacro MUI_HEADER_TEXT "$(installation_options)" "$(installation_options_prompt)"
+ !insertmacro INSTALLOPTIONS_WRITE "Desktop.ini" "Field 1" "Text" "$(create_desktop_shortcut)"
+ call winVersion
+ ${If} $0 == "1"
+ !insertmacro INSTALLOPTIONS_WRITE "Desktop.ini" "Field 2" "Type" "Label"
+ !insertmacro INSTALLOPTIONS_WRITE "Desktop.ini" "Field 2" "Text" ""
+ ${Else}
+ !insertmacro INSTALLOPTIONS_WRITE "Desktop.ini" "Field 2" "Text" "$(create_quick_launch_shortcut)"
+ ${EndIf}
+ StrCmp "${ASSOCIATION}" "NoAssociation" skip_association
+ StrCpy $R0 3
+ push "${ASSOCIATION}"
+loop:
+ call SplitStr
+ Pop $0
+ StrCmp $0 "" done
+ IntOp $R0 $R0 + 1
+ !insertmacro INSTALLOPTIONS_WRITE "Desktop.ini" "Field $R0" "Text" "$0"
+ goto loop
+skip_association:
+ StrCpy $R0 2
+ call winVersion
+ ${If} $0 == "1"
+ IntOp $R0 $R0 - 1
+ ${EndIf}
+done:
+ !insertmacro INSTALLOPTIONS_WRITE "Desktop.ini" "Settings" "NumFields" "$R0"
+ !insertmacro INSTALLOPTIONS_DISPLAY "Desktop.ini"
+FunctionEnd
diff --git a/build/conf/nsis/idea.nsi b/build/conf/nsis/idea.nsi
index 16cc8904799b..04e2f16f7088 100644
--- a/build/conf/nsis/idea.nsi
+++ b/build/conf/nsis/idea.nsi
@@ -12,7 +12,6 @@
; thus ${PRODUCT_WITH_VER} is used for uninstall registry information
!define PRODUCT_REG_VER "${MUI_PRODUCT}\${VER_BUILD}"
-!define INSTALL_OPTION_ELEMENTS 4
Name "${MUI_PRODUCT}"
SetCompressor lzma
; http://nsis.sourceforge.net/Shortcuts_removal_fails_on_Windows_Vista
@@ -28,6 +27,8 @@ RequestExecutionLevel user
!include StrFunc.nsh
!include LogicLib.nsh
+!include "customInstallActions.nsi"
+
${UnStrStr}
${UnStrLoc}
${UnStrRep}
@@ -686,9 +687,9 @@ FunctionEnd
Function ProductRegistration
StrCmp "${PRODUCT_WITH_VER}" "${MUI_PRODUCT} ${VER_BUILD}" eapInfo releaseInfo
-eapInfo:
+eapInfo:
StrCpy $3 "${PRODUCT_WITH_VER}(EAP)"
- goto createRegistration
+ goto createRegistration
releaseInfo:
StrCpy $3 "${PRODUCT_WITH_VER}"
createRegistration:
@@ -742,31 +743,34 @@ Section "IDEA Files" CopyIdeaFiles
skip_desktop_shortcut:
; OS is not win7
Call winVersion
- ${If} $0 == "0"
+ ${If} $0 == "0"
!insertmacro INSTALLOPTIONS_READ $R2 "Desktop.ini" "Field 2" "State"
StrCmp $R2 1 "" skip_quicklaunch_shortcut
CreateShortCut "$QUICKLAUNCH\${PRODUCT_FULL_NAME_WITH_VER}.lnk" \
"$INSTDIR\bin\${PRODUCT_EXE_FILE}" "" "" "" SW_SHOWNORMAL
- ${EndIf}
+ ${EndIf}
skip_quicklaunch_shortcut:
!insertmacro INSTALLOPTIONS_READ $R1 "Desktop.ini" "Settings" "NumFields"
IntCmp $R1 ${INSTALL_OPTION_ELEMENTS} do_association done do_association
do_association:
- StrCpy $R2 ${INSTALL_OPTION_ELEMENTS}
+ StrCpy $R2 ${INSTALL_OPTION_ELEMENTS}
get_user_choice:
!insertmacro INSTALLOPTIONS_READ $R3 "Desktop.ini" "Field $R2" "State"
StrCmp $R3 1 "" next_association
!insertmacro INSTALLOPTIONS_READ $R4 "Desktop.ini" "Field $R2" "Text"
call ProductAssociation
-next_association:
+next_association:
IntOp $R2 $R2 + 1
IntCmp $R1 $R2 get_user_choice done get_user_choice
done:
+
+ Call customInstallActions
+
;registration application to be presented in Open With list
call ProductRegistration
;reset icon cache
- System::Call 'shell32.dll::SHChangeNotify(i, i, i, i) v (0x08000000, 0, 0, 0)'
+ System::Call 'shell32.dll::SHChangeNotify(i, i, i, i) v (0x08000000, 0, 0, 0)'
!insertmacro MUI_STARTMENU_WRITE_BEGIN Application
; $STARTMENU_FOLDER stores name of IDEA folder in Start Menu,
; save it name in the "MenuFolder" RegValue
@@ -864,47 +868,6 @@ skip_properties:
${EndIf}
SectionEnd
-;------------------------------------------------------------------------------
-; Descriptions of sections
-;------------------------------------------------------------------------------
-; LangString DESC_CopyRuntime ${LANG_ENGLISH} "${MUI_PRODUCT} files"
-
-;------------------------------------------------------------------------------
-; custom install pages
-;------------------------------------------------------------------------------
-
-Function ConfirmDesktopShortcut
- !insertmacro MUI_HEADER_TEXT "$(installation_options)" "$(installation_options_prompt)"
- !insertmacro INSTALLOPTIONS_WRITE "Desktop.ini" "Field 1" "Text" "$(create_desktop_shortcut)"
- call winVersion
- ${If} $0 == "1"
- !insertmacro INSTALLOPTIONS_WRITE "Desktop.ini" "Field 2" "Type" "Label"
- !insertmacro INSTALLOPTIONS_WRITE "Desktop.ini" "Field 2" "Text" ""
- ${Else}
- !insertmacro INSTALLOPTIONS_WRITE "Desktop.ini" "Field 2" "Text" "$(create_quick_launch_shortcut)"
- ${EndIf}
- StrCmp "${ASSOCIATION}" "NoAssociation" skip_association
- StrCpy $R0 3
- push "${ASSOCIATION}"
-loop:
- call SplitStr
- Pop $0
- StrCmp $0 "" done
- IntOp $R0 $R0 + 1
- !insertmacro INSTALLOPTIONS_WRITE "Desktop.ini" "Field $R0" "Text" "$0"
- goto loop
-skip_association:
- StrCpy $R0 2
- call winVersion
- ${If} $0 == "1"
- IntOp $R0 $R0 - 1
- ${EndIf}
-done:
- !insertmacro INSTALLOPTIONS_WRITE "Desktop.ini" "Settings" "NumFields" "$R0"
- !insertmacro INSTALLOPTIONS_DISPLAY "Desktop.ini"
-FunctionEnd
-
-
;------------------------------------------------------------------------------
; custom uninstall functions
;------------------------------------------------------------------------------
diff --git a/build/scripts/dist.gant b/build/scripts/dist.gant
index a9fe51f5f5ee..574b8ef8dd96 100644
--- a/build/scripts/dist.gant
+++ b/build/scripts/dist.gant
@@ -70,6 +70,9 @@ def loadProductProperties(String home, String buildNumber) {
throw new BuildException("No product specific properties file found at: " + productPropertiesPath)
}
setProperty("productProperties", includeFile(productPropertiesPath).getProperties(home, buildNumber))
+ productProperties.ideJvmArgs = productProperties.ideJvmArgs != null ?
+ productProperties.ideJvmArgs + " -Didea.jre.check=true" :
+ "-Didea.jre.check=true"
}
target(compile: "Compile project") {
@@ -204,9 +207,11 @@ def layoutAll(Map args, String home, String out, Paths _paths = null, buildJps =
buildMacZip(macAppRoot, macZip, [paths.distAll], paths.distMac, productProperties.extraMacBins)
buildTarGz(linuxAppRoot, "$paths.artifacts/${archiveName}-no-jdk.tar", [paths.distAll, paths.distUnix], productProperties.extraLinuxBins)
+ requireProperty("jdk.linux", "false")
if (p("jdk.linux") != "false") {
buildTarGz(linuxAppRoot, "$paths.artifacts/${archiveName}.tar", [paths.distAll, paths.distUnix, "${paths.sandbox}/jdk.linux"], ["jre/jre/bin/*"] + productProperties.extraLinuxBins)
}
+ requireProperty("jdk.custom.linux", "false")
if (p("jdk.custom.linux") != "false") {
buildTarGz(linuxAppRoot, "$paths.artifacts/${archiveName}-custom-jdk-linux.tar", [paths.distAll, paths.distUnix, "${paths.sandbox}/jdk.custom.linux"], ["jre/jre/bin/*"] + productProperties.extraLinuxBins)
}
@@ -263,6 +268,7 @@ private layoutMac(Map _args, String home, Paths paths) {
"""
args."idea.properties.path" = "${paths.distAll}/bin/idea.properties"
+ args."idea.properties" = ["idea.jre.check": true];
args.urlSchemes = ["idea"]
args.mac_no_yjp = true
args.executable = prefix
diff --git a/build/scripts/download_kotlin.gant b/build/scripts/download_kotlin.gant
index 622ff8d0c852..7a613afae520 100644
--- a/build/scripts/download_kotlin.gant
+++ b/build/scripts/download_kotlin.gant
@@ -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.
@@ -18,7 +18,7 @@ import com.intellij.util.text.VersionComparatorUtil
import static org.jetbrains.jps.idea.IdeaProjectLoader.guessHome
includeTargets << new File("${guessHome(this)}/build/scripts/utils.gant")
-String kotlinBuildConfigurationOnPublicTeamCity = "Kotlin_Beta4_Idea142branch150versionNoTests"
+String kotlinBuildConfigurationOnPublicTeamCity = "Kotlin_Rc_Idea142branch150versionNoTests"
target('default': 'Ensures that build/kotlinc directory contains JARs from Kotlin plugin compatible with current IDEA sources. These JARs are used by build scripts.') {
def communityHome = guessHome(this)
diff --git a/build/scripts/layouts.gant b/build/scripts/layouts.gant
index 06f698053971..7ad0282482ac 100644
--- a/build/scripts/layouts.gant
+++ b/build/scripts/layouts.gant
@@ -454,6 +454,7 @@ public def layoutCommunityPlugins(String home, boolean maySkipAndroidPlugin = fa
}
jar("remote-servers-git.jar") {
moduleOptional("remote-servers-git")
+ moduleOptional("remote-servers-git-java")
}
fileset(dir: "$home/plugins/git4idea/lib") {
include(name: "trilead-ssh2.jar")
diff --git a/build/scripts/nsis_installer.gant b/build/scripts/nsis_installer.gant
index cba236ad6625..1d714667a92b 100644
--- a/build/scripts/nsis_installer.gant
+++ b/build/scripts/nsis_installer.gant
@@ -22,12 +22,9 @@ def nsis_installer(pathsToInclude, stringsFile, pathsFile, outNamePrefix, includ
ant.mkdir(dir: "$box/nsiconf")
if (!hasBundledJRE) {
- ant.mkdir(dir: "$box/jre")
- ant.unzip(dest: "$box/jre", src: winJDK)
-
ant.copy(todir: "$box/bin") {
- fileset(dir: "$box/jre/jre/bin") {
- include(name: "msvcr71.dll")
+ fileset(dir: "${box}/jdk.win/jre") {
+ include(name: "**/msvcr71.dll")
}
}
}
@@ -60,12 +57,7 @@ def nsis_installer(pathsToInclude, stringsFile, pathsFile, outNamePrefix, includ
}
fileset(dir: box, includes: "bin/msvcr71.dll")
if (!hasBundledJRE) {
- fileset(dir: box, includes: "jre/**/*")
- if (includeToolsJar) {
- fileset(dir: box) {
- include(name: "jre/lib/tools.jar")
- }
- }
+ fileset(dir: "${box}/jdk.win", includes: "jre/**/*")
}
}
diff --git a/build/scripts/utils.gant b/build/scripts/utils.gant
index 9020c76bb204..4ecce8209c91 100644
--- a/build/scripts/utils.gant
+++ b/build/scripts/utils.gant
@@ -495,7 +495,7 @@ binding.setVariable("layoutMacApp", { String path, String ch, Map args ->
String archs = """
LSArchitecturePriority
"""
- (args.archs != null ? args.archs : ["x86_64", "i386"]).each {
+ (args.archs != null ? args.archs : ["x86_64"]).each {
archs += "${it}"
}
archs +="\n"
@@ -873,34 +873,39 @@ binding.setVariable("signExecutableFiles", { String binDir ->
})
binding.setVariable("bundledJDKs"){
+ bundledJDK(false)
+}
+
+binding.setVariable("bundledJDK64s"){
+ bundledJDK(true)
+}
+
+private bundledJDK(boolean win64) {
requireProperty("artifact.linux.no.jdk", "true")
requireProperty("artifact.mac.no.jdk", "true")
- requireProperty("jdk.win", "1.8")
- requireProperty("jdk.mac", "1.8")
+ requireProperty("jdk.win", "jdk1.8")
+ requireProperty("jdk.mac", "openjdk.1.8")
requireProperty("jdk.linux", "1.8")
- requireProperty("jdk.custom.linux", "1.8")
+ requireProperty("jdk.custom.linux", "openjdk.1.8")
if (new File("${home}/build/jdk").exists()) {
if (p("jdk.win") != "false") {
- setProperty("winJDK", getPathToBundledJDK(new File("${home}/build/jdk/win"), "jdk" + p("jdk.win"), "x32.zip"))
+ setProperty("winJDK", getPathToBundledJDK(new File("${home}/build/jdk/win"), p("jdk.win"), (win64 ? "x64.zip": "x32.zip") ))
extractRedistJre(winJDK, "${paths.sandbox}/jdk.win/jre")
}
if (p("jdk.linux") != "false") {
setProperty("linuxJDK", getPathToBundledJDK(new File("${home}/build/jdk/linux"), "jdk" + p("jdk.linux"), ".tar"))
extractRedistJre(linuxJDK, "${paths.sandbox}/jdk.linux/jre")
}
- def customJdkDir = new File("${home}/build/jdk/custom")
+ def customJdkDir = new File("${home}/build/jdk/mac/custom")
if (p("jdk.mac") != "false" && (customJdkDir.exists() && customJdkDir.isDirectory())) {
- setProperty("macCustomJDK", getPathToBundledJDK(customJdkDir, "openjdk.1.8", ".tar.gz"))
+ setProperty("macCustomJDK", getPathToBundledJDK(customJdkDir, p("jdk.mac"), ".tar.gz"))
}
- customJdkDir = new File("${home}/build/jdk/custom/linux")
+ customJdkDir = new File("${home}/build/jdk/linux/custom")
if (p("jdk.custom.linux") != "false" && (customJdkDir.exists() && customJdkDir.isDirectory())) {
- setProperty("linuxCustomJDK", getPathToBundledJDK(customJdkDir, "openjdk.1.8", ".tar.gz"))
+ setProperty("linuxCustomJDK", getPathToBundledJDK(customJdkDir, p("jdk.custom.linux"), ".tar.gz"))
extractRedistJre(linuxCustomJDK, "${paths.sandbox}/jdk.custom.linux")
}
-/* if (p("jdk.bundled.mac") != "false") {
- setProperty("macJDK", getPathToBundledJDK(new File("${home}/build/jdk/mac"), "jdk" + p("jdk.bundled.mac"), ".tar"))
- } */
}
}
@@ -1187,9 +1192,12 @@ binding.setVariable("collectUsedJars", { List modules, List approvedJars, List f
return usedJars
})
+final def javaRT = "java-runtime" // that is used by build system in "buildSearchableOptions"
+
binding.setVariable("buildModulesAndCollectUsedJars", { List modules, List approvedJars, List forbiddenJars ->
def modulesToBuild = []
- def usedJars = collectUsedJars(modules, approvedJars, forbiddenJars, modulesToBuild)
+ def modulesNames = modules.contains(javaRT) ? modules : [*modules, javaRT]
+ def usedJars = collectUsedJars(modulesNames, approvedJars, forbiddenJars, modulesToBuild)
clearBuildCaches()
projectBuilder.cleanOutput()
projectBuilder.buildModules(modulesToBuild)
@@ -1199,7 +1207,8 @@ binding.setVariable("buildModulesAndCollectUsedJars", { List modules, List appro
binding.setVariable("buildSearchableOptions", { String target, List licenses, Closure cp, String jvmArgs = null,
def paths = getProperty("paths") ->
- projectBuilder.stage("Building searchable options")
+ def pathToJRT = "${projectBuilder.moduleOutput(findModule(javaRT))}"
+ projectBuilder.stage("Building searchable options JRT:" + pathToJRT)
String targetFile = "${target}/searchableOptions.xml"
ant.delete(file: targetFile)
@@ -1228,7 +1237,7 @@ binding.setVariable("buildSearchableOptions", { String target, List licenses, Cl
arg(value: "${target}/searchableOptions.xml")
classpath() {
- pathelement(location: "${projectBuilder.moduleOutput(findModule("java-runtime"))}")
+ pathelement(location: "${pathToJRT}")
}
}
diff --git a/community-main.iml b/community-main.iml
index ea35d365deee..6dcf144cc226 100644
--- a/community-main.iml
+++ b/community-main.iml
@@ -117,9 +117,10 @@
-
+
+
\ No newline at end of file
diff --git a/community-tests/src/tests/testGroups.properties b/community-tests/src/tests/testGroups.properties
index d58a632068cf..943213f21675 100644
--- a/community-tests/src/tests/testGroups.properties
+++ b/community-tests/src/tests/testGroups.properties
@@ -80,6 +80,7 @@ com.android.tools.idea.editors.theme.ThemeEditorStyleTest
com.android.tools.idea.editors.theme.ThemeEditorUtilsTest
com.android.tools.idea.editors.theme.qualifiers.QualifierUtilsTest
com.android.tools.idea.gradle.IdeaAndroidProjectTest
+com.android.tools.idea.gradle.project.AndroidGradleProjectImportingTest
com.android.tools.idea.gradle.project.GradleProjectSyncDataTest
com.android.tools.idea.npw.ConfigureAndroidModuleStepTest
com.android.tools.idea.npw.ConfigureAndroidModuleStepDynamicTest
diff --git a/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java b/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java
index 05c27526775a..95f6a84510d8 100644
--- a/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java
+++ b/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java
@@ -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.
@@ -46,6 +46,7 @@ import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.FileUtil;
+import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
@@ -74,7 +75,7 @@ import java.util.*;
name = "CompilerConfiguration",
storages = {
@Storage(file = StoragePathMacros.PROJECT_FILE),
- @Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/compiler.xml", scheme = StorageScheme.DIRECTORY_BASED)
+ @Storage(file = "compiler.xml", scheme = StorageScheme.DIRECTORY_BASED)
}
)
public class CompilerConfigurationImpl extends CompilerConfiguration implements PersistentStateComponent, ProjectComponent {
@@ -82,6 +83,9 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements
public static final String TESTS_EXTERNAL_COMPILER_HOME_PROPERTY_NAME = "tests.external.compiler.home";
public static final int DEFAULT_BUILD_PROCESS_HEAP_SIZE = 700;
+ private static final List DEFAULT_WILDCARD_PATTERNS =
+ Arrays.asList("!?*.java", "!?*.form", "!?*.class", "!?*.groovy", "!?*.scala", "!?*.flex", "!?*.kt", "!?*.clj", "!?*.aj");
+
private BackendCompiler myDefaultJavaCompiler;
private State myState = new State();
@@ -142,11 +146,13 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements
@Override
public Element getState() {
+ final boolean savingStateInNewFormatAllowed = Registry.is("saving.state.in.new.format.is.allowed", false);
+
Element state = new Element("state");
XmlSerializer.serializeInto(myState, state, new SkipDefaultValuesSerializationFilters() {
@Override
public boolean accepts(@NotNull Accessor accessor, @NotNull Object bean) {
- if (myState.compilerWasSpecified && "DEFAULT_COMPILER".equals(accessor.getName())) {
+ if (!savingStateInNewFormatAllowed && myState.compilerWasSpecified && "DEFAULT_COMPILER".equals(accessor.getName())) {
return true;
}
return super.accepts(accessor, bean);
@@ -162,24 +168,43 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements
myExcludesConfiguration.getDelegate().writeExternal(addChild(state, JpsJavaCompilerConfigurationSerializer.EXCLUDE_FROM_COMPILE));
}
- final Element newChild = addChild(state, JpsJavaCompilerConfigurationSerializer.RESOURCE_EXTENSIONS);
- for (final String pattern : getRegexpPatterns()) {
- addChild(newChild, JpsJavaCompilerConfigurationSerializer.ENTRY).setAttribute(JpsJavaCompilerConfigurationSerializer.NAME, pattern);
+ Element resourceExtensions = new Element(JpsJavaCompilerConfigurationSerializer.RESOURCE_EXTENSIONS);
+ for (String pattern : getRegexpPatterns()) {
+ addChild(resourceExtensions, JpsJavaCompilerConfigurationSerializer.ENTRY).setAttribute(JpsJavaCompilerConfigurationSerializer.NAME, pattern);
+ }
+ if (!savingStateInNewFormatAllowed || !JDOMUtil.isEmpty(resourceExtensions)) {
+ state.addContent(resourceExtensions);
}
- if (myWildcardPatternsInitialized || !myWildcardPatterns.isEmpty()) {
+ if ((myWildcardPatternsInitialized || !myWildcardPatterns.isEmpty()) &&
+ (!savingStateInNewFormatAllowed || !DEFAULT_WILDCARD_PATTERNS.equals(myWildcardPatterns))) {
final Element wildcardPatterns = addChild(state, JpsJavaCompilerConfigurationSerializer.WILDCARD_RESOURCE_PATTERNS);
for (final String wildcardPattern : myWildcardPatterns) {
- addChild(wildcardPatterns, JpsJavaCompilerConfigurationSerializer.ENTRY).setAttribute(JpsJavaCompilerConfigurationSerializer.NAME, wildcardPattern);
+ addChild(wildcardPatterns, JpsJavaCompilerConfigurationSerializer.ENTRY)
+ .setAttribute(JpsJavaCompilerConfigurationSerializer.NAME, wildcardPattern);
}
}
- final Element annotationProcessingSettings = addChild(state, JpsJavaCompilerConfigurationSerializer.ANNOTATION_PROCESSING);
- final Element defaultProfileElem = addChild(annotationProcessingSettings, "profile").setAttribute("default", "true");
- AnnotationProcessorProfileSerializer.writeExternal(myDefaultProcessorsProfile, defaultProfileElem);
+ Element annotationProcessingSettings = new Element(JpsJavaCompilerConfigurationSerializer.ANNOTATION_PROCESSING);
+
+ Element profileElement = new Element("profile");
+ profileElement.setAttribute("default", "true");
+ AnnotationProcessorProfileSerializer.writeExternal(myDefaultProcessorsProfile, profileElement);
+ if (!savingStateInNewFormatAllowed || !JDOMUtil.isEmpty(profileElement, 2)) {
+ annotationProcessingSettings.addContent(profileElement);
+ }
+
for (ProcessorConfigProfile profile : myModuleProcessorProfiles) {
- final Element profileElem = addChild(annotationProcessingSettings, "profile").setAttribute("default", "false");
- AnnotationProcessorProfileSerializer.writeExternal(profile, profileElem);
+ Element element = new Element("profile");
+ if (!savingStateInNewFormatAllowed) {
+ element.setAttribute("default", "false");
+ }
+ AnnotationProcessorProfileSerializer.writeExternal(profile, element);
+ annotationProcessingSettings.addContent(element);
+ }
+
+ if (!savingStateInNewFormatAllowed || !JDOMUtil.isEmpty(annotationProcessingSettings)) {
+ state.addContent(annotationProcessingSettings);
}
if (!StringUtil.isEmpty(myBytecodeTargetLevel) || !myModuleBytecodeTarget.isEmpty()) {
@@ -206,6 +231,7 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements
readExternal(state);
}
+ @Override
public int getBuildProcessHeapSize(final int javacPreferredHeapSize) {
final int heapSize = myState.BUILD_PROCESS_HEAP_SIZE;
if (heapSize != DEFAULT_BUILD_PROCESS_HEAP_SIZE) {
@@ -215,14 +241,17 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements
return Math.max(heapSize, javacPreferredHeapSize);
}
+ @Override
public void setBuildProcessHeapSize(int size) {
myState.BUILD_PROCESS_HEAP_SIZE = size > 0? size : DEFAULT_BUILD_PROCESS_HEAP_SIZE;
}
+ @Override
public String getBuildProcessVMOptions() {
return myState.BUILD_PROCESS_ADDITIONAL_VM_OPTIONS;
}
+ @Override
public void setBuildProcessVMOptions(String options) {
myState.BUILD_PROCESS_ADDITIONAL_VM_OPTIONS = options == null? "" : options.trim();
}
@@ -287,15 +316,9 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements
removeWildcardPatterns();
}
try {
- addWildcardResourcePattern("!?*.java");
- addWildcardResourcePattern("!?*.form");
- addWildcardResourcePattern("!?*.class");
- addWildcardResourcePattern("!?*.groovy");
- addWildcardResourcePattern("!?*.scala");
- addWildcardResourcePattern("!?*.flex");
- addWildcardResourcePattern("!?*.kt");
- addWildcardResourcePattern("!?*.clj");
- addWildcardResourcePattern("!?*.aj");
+ for (String pattern : DEFAULT_WILDCARD_PATTERNS) {
+ addWildcardResourcePattern(pattern);
+ }
}
catch (MalformedPatternException e) {
LOG.error(e);
@@ -719,8 +742,7 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements
node = parentNode.getChild(JpsJavaCompilerConfigurationSerializer.WILDCARD_RESOURCE_PATTERNS);
if (node != null) {
myWildcardPatternsInitialized = true;
- for (final Object o : node.getChildren(JpsJavaCompilerConfigurationSerializer.ENTRY)) {
- final Element element = (Element)o;
+ for (Element element : node.getChildren(JpsJavaCompilerConfigurationSerializer.ENTRY)) {
String pattern = element.getAttributeValue(JpsJavaCompilerConfigurationSerializer.NAME);
if (!StringUtil.isEmpty(pattern)) {
addWildcardResourcePattern(pattern);
diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/CompileContextImpl.java b/java/compiler/impl/src/com/intellij/compiler/impl/CompileContextImpl.java
index 154c7008f0b3..00d0513a483b 100644
--- a/java/compiler/impl/src/com/intellij/compiler/impl/CompileContextImpl.java
+++ b/java/compiler/impl/src/com/intellij/compiler/impl/CompileContextImpl.java
@@ -22,7 +22,6 @@
package com.intellij.compiler.impl;
import com.intellij.compiler.CompilerConfiguration;
-import com.intellij.compiler.CompilerMessageImpl;
import com.intellij.compiler.CompilerWorkspaceConfiguration;
import com.intellij.compiler.ProblemsView;
import com.intellij.compiler.progress.CompilerTask;
@@ -37,25 +36,21 @@ import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
-import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.UserDataHolderBase;
-import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
-import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.pom.Navigatable;
-import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import java.util.*;
+import java.util.UUID;
public class CompileContextImpl extends UserDataHolderBase implements CompileContextEx {
private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.CompileContextImpl");
private final Project myProject;
private final CompilerTask myBuildSession;
- private final Map> myMessages = new EnumMap>(CompilerMessageCategory.class);
+ private final MessagesContainer myMessages;
private final boolean myShouldUpdateProblemsView;
private CompileScope myCompileScope;
private final boolean myMake;
@@ -63,9 +58,6 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon
private final boolean myIsAnnotationProcessorsEnabled;
private boolean myRebuildRequested;
private String myRebuildReason;
- private final Map myRootToModuleMap = new HashMap();
- private final Map> myModuleToRootsMap = new HashMap>();
- private final Set myGeneratedTestRoots = new HashSet();
private final ProjectFileIndex myProjectFileIndex; // cached for performance reasons
private final ProjectCompileScope myProjectCompileScope;
private final long myStartCompilationStamp;
@@ -76,6 +68,7 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon
@NotNull CompileScope compileScope,
boolean isMake, boolean isRebuild) {
myProject = project;
+ myMessages = new MessagesContainer(project);
myBuildSession = compilerSession;
myCompileScope = compileScope;
myMake = isMake;
@@ -117,37 +110,17 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon
@Override
public CompilerMessage[] getMessages(CompilerMessageCategory category) {
- Collection collection = myMessages.get(category);
- if (collection == null) {
- return CompilerMessage.EMPTY_ARRAY;
- }
- return collection.toArray(new CompilerMessage[collection.size()]);
+ return myMessages.getMessages(category).toArray(CompilerMessage.EMPTY_ARRAY);
}
@Override
public void addMessage(CompilerMessageCategory category, String message, String url, int lineNum, int columnNum) {
- final CompilerMessageImpl msg = new CompilerMessageImpl(myProject, category, message, findFileByUrl(url), lineNum, columnNum, null);
- addMessage(msg);
+ addMessage(category, message, url, lineNum, columnNum, null);
}
@Override
- public void addMessage(CompilerMessageCategory category, String message, String url, int lineNum, int columnNum,
- Navigatable navigatable) {
- final CompilerMessageImpl msg = new CompilerMessageImpl(myProject, category, message, findFileByUrl(url), lineNum, columnNum, navigatable);
- addMessage(msg);
- }
-
- @Nullable
- private static VirtualFile findFileByUrl(@Nullable String url) {
- if (url == null) {
- return null;
- }
- VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(url);
- if (file == null) {
- // groovy stubs may be placed in completely random directories which aren't refreshed automatically
- return VirtualFileManager.getInstance().refreshAndFindFileByUrl(url);
- }
- return file;
+ public void addMessage(CompilerMessageCategory category, String message, String url, int lineNum, int columnNum, Navigatable navigatable) {
+ myMessages.addMessage(category, message, url, lineNum, columnNum, navigatable);
}
@Override
@@ -155,13 +128,7 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon
if (ApplicationManager.getApplication().isUnitTestMode()) {
LOG.info("addMessage: " + msg + " this=" + this);
}
-
- Collection messages = myMessages.get(msg.getCategory());
- if (messages == null) {
- messages = new LinkedHashSet();
- myMessages.put(msg.getCategory(), messages);
- }
- if (messages.add(msg)) {
+ if (myMessages.addMessage(msg)) {
myBuildSession.addMessage(msg);
}
if (myShouldUpdateProblemsView && msg.getCategory() == CompilerMessageCategory.ERROR) {
@@ -171,17 +138,7 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon
@Override
public int getMessageCount(CompilerMessageCategory category) {
- if (category != null) {
- Collection collection = myMessages.get(category);
- return collection != null ? collection.size() : 0;
- }
- int count = 0;
- for (Collection collection : myMessages.values()) {
- if (collection != null) {
- count += collection.size();
- }
- }
- return count;
+ return myMessages.getMessageCount(category);
}
@Override
@@ -226,59 +183,9 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon
LOG.assertTrue(!module.isDisposed());
return module;
}
- for (final VirtualFile root : myRootToModuleMap.keySet()) {
- if (VfsUtilCore.isAncestor(root, file, false)) {
- final Module mod = myRootToModuleMap.get(root);
- if (mod != null) {
- LOG.assertTrue(!mod.isDisposed());
- }
- return mod;
- }
- }
return null;
}
-
- private final Map myModuleToRootsCache = new HashMap();
-
- @Override
- public VirtualFile[] getSourceRoots(Module module) {
- VirtualFile[] cachedRoots = myModuleToRootsCache.get(module);
- if (cachedRoots != null) {
- if (areFilesValid(cachedRoots)) {
- return cachedRoots;
- }
- else {
- myModuleToRootsCache.remove(module); // clear cache for this module and rebuild list of roots
- }
- }
-
- Set additionalRoots = myModuleToRootsMap.get(module);
- VirtualFile[] moduleRoots = ModuleRootManager.getInstance(module).getSourceRoots();
- if (additionalRoots == null || additionalRoots.isEmpty()) {
- myModuleToRootsCache.put(module, moduleRoots);
- return moduleRoots;
- }
-
- final VirtualFile[] allRoots = new VirtualFile[additionalRoots.size() + moduleRoots.length];
- System.arraycopy(moduleRoots, 0, allRoots, 0, moduleRoots.length);
- int index = moduleRoots.length;
- for (final VirtualFile additionalRoot : additionalRoots) {
- allRoots[index++] = additionalRoot;
- }
- myModuleToRootsCache.put(module, allRoots);
- return allRoots;
- }
-
- private static boolean areFilesValid(VirtualFile[] files) {
- for (VirtualFile file : files) {
- if (!file.isValid()) {
- return false;
- }
- }
- return true;
- }
-
@Override
public VirtualFile getModuleOutputDirectory(Module module) {
return CompilerPaths.getModuleOutputDirectory(module, false);
@@ -294,6 +201,11 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon
return myMake;
}
+ @Override
+ public boolean isAutomake() {
+ return false;
+ }
+
@Override
public boolean isRebuild() {
return myIsRebuild;
@@ -309,22 +221,6 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon
myCompileScope = new CompositeScope(myCompileScope, additionalScope);
}
- @Override
- public boolean isInTestSourceContent(@NotNull final VirtualFile fileOrDir) {
- if (myProjectFileIndex.isInTestSourceContent(fileOrDir)) {
- return true;
- }
- return VfsUtilCore.isUnder(fileOrDir, myGeneratedTestRoots);
- }
-
- @Override
- public boolean isInSourceContent(@NotNull final VirtualFile fileOrDir) {
- if (myProjectFileIndex.isInSourceContent(fileOrDir)) {
- return true;
- }
- return VfsUtilCore.isUnder(fileOrDir, myRootToModuleMap.keySet());
- }
-
public UUID getSessionId() {
return mySessionId;
}
diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java
index 0b351b150220..95c190743443 100644
--- a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java
+++ b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java
@@ -22,7 +22,10 @@
package com.intellij.compiler.impl;
import com.intellij.CommonBundle;
-import com.intellij.compiler.*;
+import com.intellij.compiler.CompilerWorkspaceConfiguration;
+import com.intellij.compiler.ModuleCompilerUtil;
+import com.intellij.compiler.ModuleSourceSet;
+import com.intellij.compiler.ProblemsView;
import com.intellij.compiler.progress.CompilerTask;
import com.intellij.compiler.server.BuildManager;
import com.intellij.compiler.server.DefaultMessageHandler;
@@ -489,27 +492,10 @@ public class CompileDriver {
if (!outputs.isEmpty()) {
final ProgressIndicator indicator = compileContext.getProgressIndicator();
indicator.setText("Synchronizing output directories...");
- CompilerUtil.refreshOutputDirectories(outputs, _status == ExitStatus.CANCELLED);
+ CompilerUtil.refreshOutputDirectories(outputs, false);
indicator.setText("");
}
}
-
- if (compileContext.isAnnotationProcessorsEnabled() && !myProject.isDisposed()) {
- final Set genSourceRoots = new THashSet(FileUtil.FILE_HASHING_STRATEGY);
- final CompilerConfiguration config = CompilerConfiguration.getInstance(myProject);
- for (Module module : affectedModules) {
- if (!module.isDisposed() && config.getAnnotationProcessingConfiguration(module).isEnabled()) {
- final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module);
- if (path != null) {
- genSourceRoots.add(new File(path));
- }
- }
- }
- if (!genSourceRoots.isEmpty()) {
- // refresh generates source roots asynchronously; needed for error highlighting update
- LocalFileSystem.getInstance().refreshIoFiles(genSourceRoots, true, true, null);
- }
- }
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/MessagesContainer.java b/java/compiler/impl/src/com/intellij/compiler/impl/MessagesContainer.java
new file mode 100644
index 000000000000..e953fff920db
--- /dev/null
+++ b/java/compiler/impl/src/com/intellij/compiler/impl/MessagesContainer.java
@@ -0,0 +1,94 @@
+/*
+ * 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.compiler.impl;
+
+import com.intellij.compiler.CompilerMessageImpl;
+import com.intellij.openapi.compiler.CompilerMessage;
+import com.intellij.openapi.compiler.CompilerMessageCategory;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.openapi.vfs.VirtualFileManager;
+import com.intellij.pom.Navigatable;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.*;
+
+/**
+ * @author Eugene Zhuravlev
+ * Date: 27-Jan-16
+ */
+public class MessagesContainer {
+ private final Project myProject;
+ private final Map> myMessages = new EnumMap>(CompilerMessageCategory.class);
+
+ public MessagesContainer(Project project) {
+ myProject = project;
+ }
+
+ @NotNull
+ public Collection getMessages(CompilerMessageCategory category) {
+ final Collection collection = myMessages.get(category);
+ if (collection == null) {
+ return Collections.emptyList();
+ }
+ return Collections.unmodifiableCollection(collection);
+ }
+
+ public CompilerMessage addMessage(CompilerMessageCategory category, String message, String url, int lineNum, int columnNum, Navigatable navigatable) {
+ final CompilerMessageImpl msg =
+ new CompilerMessageImpl(myProject, category, message, findFileByUrl(url), lineNum, columnNum, navigatable);
+ addMessage(msg);
+ return msg;
+ }
+
+ public boolean addMessage(CompilerMessage msg) {
+ Collection messages = myMessages.get(msg.getCategory());
+ if (messages == null) {
+ messages = new LinkedHashSet();
+ myMessages.put(msg.getCategory(), messages);
+ }
+ return messages.add(msg);
+ }
+
+ @Nullable
+ private static VirtualFile findFileByUrl(@Nullable String url) {
+ if (url == null) {
+ return null;
+ }
+ VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(url);
+ if (file == null) {
+ // groovy stubs may be placed in completely random directories which aren't refreshed automatically
+ return VirtualFileManager.getInstance().refreshAndFindFileByUrl(url);
+ }
+ return file;
+ }
+
+ public int getMessageCount(CompilerMessageCategory category) {
+ if (category != null) {
+ Collection collection = myMessages.get(category);
+ return collection != null ? collection.size() : 0;
+ }
+ int count = 0;
+ for (Collection collection : myMessages.values()) {
+ if (collection != null) {
+ count += collection.size();
+ }
+ }
+ return count;
+ }
+
+}
diff --git a/java/compiler/impl/src/com/intellij/compiler/server/AutoMakeMessageHandler.java b/java/compiler/impl/src/com/intellij/compiler/server/AutoMakeMessageHandler.java
index cbdcc3a43475..9f2a284dc88a 100644
--- a/java/compiler/impl/src/com/intellij/compiler/server/AutoMakeMessageHandler.java
+++ b/java/compiler/impl/src/com/intellij/compiler/server/AutoMakeMessageHandler.java
@@ -18,21 +18,21 @@ package com.intellij.compiler.server;
import com.intellij.compiler.CompilerMessageImpl;
import com.intellij.compiler.ProblemsView;
import com.intellij.notification.Notification;
-import com.intellij.openapi.compiler.CompilationStatusListener;
-import com.intellij.openapi.compiler.CompilerManager;
-import com.intellij.openapi.compiler.CompilerMessageCategory;
-import com.intellij.openapi.compiler.CompilerTopics;
+import com.intellij.openapi.compiler.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.problems.Problem;
import com.intellij.problems.WolfTheProblemSolver;
+import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.api.CmdlineRemoteProto;
import org.jetbrains.jps.api.GlobalOptions;
+import javax.swing.*;
import java.util.Collections;
import java.util.UUID;
@@ -46,12 +46,14 @@ class AutoMakeMessageHandler extends DefaultMessageHandler {
private final Project myProject;
private final WolfTheProblemSolver myWolf;
private volatile boolean myUnprocessedFSChangesDetected = false;
+ private final AutomakeCompileContext myContext;
public AutoMakeMessageHandler(Project project) {
super(project);
myProject = project;
myBuildStatus = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.SUCCESS;
myWolf = WolfTheProblemSolver.getInstance(project);
+ myContext = new AutomakeCompileContext(project);
}
public boolean unprocessedFSChangesDetected() {
@@ -69,9 +71,27 @@ class AutoMakeMessageHandler extends DefaultMessageHandler {
}
switch (event.getEventType()) {
case BUILD_COMPLETED:
+ myContext.getProgressIndicator().stop();
if (event.hasCompletionStatus()) {
- myBuildStatus = event.getCompletionStatus();
+ final CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status status = event.getCompletionStatus();
+ myBuildStatus = status;
+ if (status == CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.CANCELED) {
+ myContext.getProgressIndicator().cancel();
+ }
}
+ final int errors = myContext.getMessageCount(CompilerMessageCategory.ERROR);
+ final int warnings = myContext.getMessageCount(CompilerMessageCategory.WARNING);
+ //noinspection SSBasedInspection
+ SwingUtilities.invokeLater(new Runnable() {
+ @Override
+ public void run() {
+ if (myProject.isDisposed()) {
+ return;
+ }
+ final CompilationStatusListener publisher = myProject.getMessageBus().syncPublisher(CompilerTopics.COMPILATION_STATUS);
+ publisher.automakeCompilationFinished(errors, warnings, myContext);
+ }
+ });
return;
case FILES_GENERATED:
@@ -112,14 +132,29 @@ class AutoMakeMessageHandler extends DefaultMessageHandler {
view.setProgress(message.getText());
}
}
- else if (kind == CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind.ERROR) {
- informWolf(myProject, message);
+ else {
+ final CompilerMessageCategory category = convertToCategory(kind);
+ if (category != null) { // only process supported kinds of messages
+ final String sourceFilePath = message.hasSourceFilePath() ? message.getSourceFilePath() : null;
+ final String url = sourceFilePath != null ? VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, FileUtil.toSystemIndependentName(sourceFilePath)) : null;
+ final long line = message.hasLine() ? message.getLine() : -1;
+ final long column = message.hasColumn() ? message.getColumn() : -1;
+ final CompilerMessage msg = myContext.createAndAddMessage(category, message.getText(), url, (int)line, (int)column, null);
+ if (kind == CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind.ERROR) {
+ informWolf(myProject, message);
+ ProblemsView.SERVICE.getInstance(myProject).addMessage(msg, sessionId);
+ }
+ }
+ }
+ }
- final String sourceFilePath = message.hasSourceFilePath() ? message.getSourceFilePath() : null;
- final VirtualFile vFile = sourceFilePath != null? LocalFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(sourceFilePath)) : null;
- final long line = message.hasLine() ? message.getLine() : -1;
- final long column = message.hasColumn() ? message.getColumn() : -1;
- ProblemsView.SERVICE.getInstance(myProject).addMessage(new CompilerMessageImpl(myProject, CompilerMessageCategory.ERROR, message.getText(), vFile, (int)line, (int)column, null), sessionId);
+ @Nullable
+ private static CompilerMessageCategory convertToCategory(CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind kind) {
+ switch(kind) {
+ case ERROR: return CompilerMessageCategory.ERROR;
+ case INFO: return CompilerMessageCategory.INFORMATION;
+ case WARNING: return CompilerMessageCategory.WARNING;
+ default: return null;
}
}
diff --git a/java/compiler/impl/src/com/intellij/compiler/server/AutomakeCompileContext.java b/java/compiler/impl/src/com/intellij/compiler/server/AutomakeCompileContext.java
new file mode 100644
index 000000000000..1ed51434ae5b
--- /dev/null
+++ b/java/compiler/impl/src/com/intellij/compiler/server/AutomakeCompileContext.java
@@ -0,0 +1,143 @@
+/*
+ * 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.compiler.server;
+
+import com.intellij.compiler.CompilerConfiguration;
+import com.intellij.compiler.impl.MessagesContainer;
+import com.intellij.compiler.impl.ProjectCompileScope;
+import com.intellij.openapi.compiler.*;
+import com.intellij.openapi.module.Module;
+import com.intellij.openapi.progress.EmptyProgressIndicator;
+import com.intellij.openapi.progress.ProgressIndicator;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.roots.ProjectRootManager;
+import com.intellij.openapi.util.UserDataHolderBase;
+import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.pom.Navigatable;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * @author Eugene Zhuravlev
+ * Date: 27-Jan-16
+ */
+final class AutomakeCompileContext extends UserDataHolderBase implements CompileContext {
+ private final Project myProject;
+ private final ProjectCompileScope myScope;
+ private final MessagesContainer myMessages;
+ private final EmptyProgressIndicator myIndicator;
+ private final boolean myAnnotationProcessingEnabled;
+
+ public AutomakeCompileContext(Project project) {
+ myProject = project;
+ myScope = new ProjectCompileScope(project);
+ myMessages = new MessagesContainer(project);
+ myIndicator = new EmptyProgressIndicator();
+ myAnnotationProcessingEnabled = CompilerConfiguration.getInstance(project).isAnnotationProcessorsEnabled();
+ }
+
+ @Override
+ public Project getProject() {
+ return myProject;
+ }
+
+ @Override
+ public CompileScope getCompileScope() {
+ return getProjectCompileScope();
+ }
+
+ @Override
+ public CompileScope getProjectCompileScope() {
+ return myScope;
+ }
+
+ @Override
+ public boolean isMake() {
+ return true;
+ }
+
+ @Override
+ public boolean isAutomake() {
+ return true;
+ }
+
+ public void addMessage(CompilerMessageCategory category, String message, @Nullable String url, int lineNum, int columnNum) {
+ addMessage(category, message, url, lineNum, columnNum, null);
+ }
+
+ @Override
+ public void addMessage(CompilerMessageCategory category, String message, @Nullable String url, int lineNum, int columnNum, Navigatable navigatable) {
+ createAndAddMessage(category, message, url, lineNum, columnNum, navigatable);
+ }
+
+ @Override
+ public CompilerMessage[] getMessages(CompilerMessageCategory category) {
+ return myMessages.getMessages(category).toArray(CompilerMessage.EMPTY_ARRAY);
+ }
+
+ public CompilerMessage createAndAddMessage(CompilerMessageCategory category, String message, @Nullable String url, int lineNum, int columnNum, Navigatable navigatable) {
+ return myMessages.addMessage(category, message, url, lineNum, columnNum, navigatable);
+ }
+
+ @Override
+ public int getMessageCount(CompilerMessageCategory category) {
+ return myMessages.getMessageCount(category);
+ }
+
+ @NotNull
+ @Override
+ public ProgressIndicator getProgressIndicator() {
+ return myIndicator;
+ }
+
+ @Override
+ public void requestRebuildNextTime(String message) {
+ }
+
+ @Override
+ public boolean isRebuildRequested() {
+ return false;
+ }
+
+ @Nullable
+ @Override
+ public String getRebuildReason() {
+ return null;
+ }
+
+ @Override
+ public Module getModuleByFile(VirtualFile file) {
+ return ProjectRootManager.getInstance(myProject).getFileIndex().getModuleForFile(file);
+ }
+
+ public VirtualFile getModuleOutputDirectory(final Module module) {
+ return CompilerPaths.getModuleOutputDirectory(module, false);
+ }
+
+ public VirtualFile getModuleOutputDirectoryForTests(final Module module) {
+ return CompilerPaths.getModuleOutputDirectory(module, true);
+ }
+
+ @Override
+ public boolean isRebuild() {
+ return false;
+ }
+
+ @Override
+ public boolean isAnnotationProcessorsEnabled() {
+ return myAnnotationProcessingEnabled;
+ }
+}
diff --git a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java
index da41b0850d93..05ad77baf475 100644
--- a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java
+++ b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java
@@ -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.
@@ -42,6 +42,7 @@ import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.compiler.CompilationStatusListener;
import com.intellij.openapi.compiler.CompileContext;
+import com.intellij.openapi.compiler.CompilerPaths;
import com.intellij.openapi.compiler.CompilerTopics;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.EditorFactory;
@@ -342,7 +343,7 @@ public class BuildManager implements Disposable {
}
});
- JobScheduler.getScheduler().scheduleAtFixedRate(new Runnable() {
+ JobScheduler.getScheduler().scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
runCommand(myGCTask);
@@ -1504,22 +1505,50 @@ public class BuildManager implements Disposable {
});
conn.subscribe(CompilerTopics.COMPILATION_STATUS, new CompilationStatusListener() {
private final Set myRootsToRefresh = new THashSet(FileUtil.PATH_HASHING_STRATEGY);
+
+ @Override
+ public void automakeCompilationFinished(int errors, int warnings, CompileContext compileContext) {
+ if (!compileContext.getProgressIndicator().isCanceled()) {
+ refreshSources(compileContext);
+ }
+ }
+
@Override
public void compilationFinished(boolean aborted, int errors, int warnings, CompileContext compileContext) {
- final String[] roots;
+ refreshSources(compileContext);
+ }
+
+ private void refreshSources(CompileContext compileContext) {
+ if (project.isDisposed()) {
+ return;
+ }
+ final Set candidates = new THashSet(FileUtil.PATH_HASHING_STRATEGY);
synchronized (myRootsToRefresh) {
- roots = ArrayUtil.toStringArray(myRootsToRefresh);
+ candidates.addAll(myRootsToRefresh);
myRootsToRefresh.clear();
}
- if (roots.length != 0) {
+ if (compileContext.isAnnotationProcessorsEnabled()) {
+ // annotation processors may have re-generated code
+ final CompilerConfiguration config = CompilerConfiguration.getInstance(project);
+ for (Module module : compileContext.getCompileScope().getAffectedModules()) {
+ if (config.getAnnotationProcessingConfiguration(module).isEnabled()) {
+ final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module);
+ if (path != null) {
+ candidates.add(path);
+ }
+ }
+ }
+ }
+
+ if (!candidates.isEmpty()) {
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
@Override
public void run() {
if (project.isDisposed()) {
return;
}
- final List rootFiles = new ArrayList(roots.length);
- for (String root : roots) {
+ final List rootFiles = new ArrayList(candidates.size());
+ for (String root : candidates) {
rootFiles.add(new File(root));
}
// this will ensure that we'll be able to obtain VirtualFile for existing roots
diff --git a/java/compiler/impl/src/com/intellij/openapi/compiler/ex/CompileContextEx.java b/java/compiler/impl/src/com/intellij/openapi/compiler/ex/CompileContextEx.java
index 6251b56c5b21..a50e4f4801d1 100644
--- a/java/compiler/impl/src/com/intellij/openapi/compiler/ex/CompileContextEx.java
+++ b/java/compiler/impl/src/com/intellij/openapi/compiler/ex/CompileContextEx.java
@@ -18,20 +18,11 @@ package com.intellij.openapi.compiler.ex;
import com.intellij.openapi.compiler.CompileContext;
import com.intellij.openapi.compiler.CompileScope;
import com.intellij.openapi.compiler.CompilerMessage;
-import com.intellij.openapi.vfs.VirtualFile;
-import org.jetbrains.annotations.NotNull;
public interface CompileContextEx extends CompileContext {
void addMessage(CompilerMessage message);
- /**
- * the same as FileIndex.isInTestSourceContent(), but takes into account generated output dirs
- */
- boolean isInTestSourceContent(@NotNull VirtualFile fileOrDir);
-
- boolean isInSourceContent(@NotNull VirtualFile fileOrDir);
-
void addScope(CompileScope additionalScope);
}
diff --git a/java/compiler/openapi/compiler-openapi.iml b/java/compiler/openapi/compiler-openapi.iml
index 9fb5c9321534..e0570144de08 100644
--- a/java/compiler/openapi/compiler-openapi.iml
+++ b/java/compiler/openapi/compiler-openapi.iml
@@ -1,6 +1,6 @@
-
+
@@ -161,5 +161,4 @@
-
-
+
\ No newline at end of file
diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilationStatusAdapter.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilationStatusAdapter.java
index 263919458292..018bf3dae323 100644
--- a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilationStatusAdapter.java
+++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilationStatusAdapter.java
@@ -16,6 +16,9 @@
package com.intellij.openapi.compiler;
public class CompilationStatusAdapter implements CompilationStatusListener {
+ public void automakeCompilationFinished(int errors, int warnings, CompileContext compileContext) {
+ }
+
public void compilationFinished(boolean aborted, int errors, int warnings, final CompileContext compileContext) {
}
diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilationStatusListener.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilationStatusListener.java
index 11fbe73d9ed0..05f9241fec83 100644
--- a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilationStatusListener.java
+++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilationStatusListener.java
@@ -31,7 +31,12 @@ public interface CompilationStatusListener extends EventListener {
* @param warnings warning count
* @param compileContext context for the finished compilation
*/
- void compilationFinished(boolean aborted, int errors, int warnings, final CompileContext compileContext);
+ default void compilationFinished(boolean aborted, int errors, int warnings, final CompileContext compileContext){
+ }
- void fileGenerated(String outputRoot, String relativePath);
+ default void automakeCompilationFinished(int errors, int warnings, final CompileContext compileContext) {
+ }
+
+ default void fileGenerated(String outputRoot, String relativePath) {
+ }
}
diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompileContext.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompileContext.java
index 6046c2835194..7817e6522797 100644
--- a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompileContext.java
+++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompileContext.java
@@ -114,13 +114,6 @@ public interface CompileContext extends UserDataHolder {
*/
Module getModuleByFile(VirtualFile file);
- /**
- * Returns the source roots for the specified module.
- *
- * @return module's source roots as well as source roots for generated sources that are attributed to the module
- */
- VirtualFile[] getSourceRoots(Module module);
-
/**
* Returns the output directory for the specified module.
*
@@ -147,6 +140,8 @@ public interface CompileContext extends UserDataHolder {
*/
boolean isMake();
+ boolean isAutomake();
+
boolean isRebuild();
Project getProject();
diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerPaths.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerPaths.java
index fd749d136449..6ffe84dfdbd7 100644
--- a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerPaths.java
+++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerPaths.java
@@ -112,6 +112,9 @@ public class CompilerPaths {
@Nullable
public static VirtualFile getModuleOutputDirectory(final Module module, boolean forTestClasses) {
final CompilerModuleExtension compilerModuleExtension = CompilerModuleExtension.getInstance(module);
+ if (compilerModuleExtension == null) {
+ return null;
+ }
VirtualFile outPath;
if (forTestClasses) {
final VirtualFile path = compilerModuleExtension.getCompilerOutputPathForTests();
@@ -144,6 +147,9 @@ public class CompilerPaths {
final String outPathUrl;
final Application application = ApplicationManager.getApplication();
final CompilerModuleExtension extension = CompilerModuleExtension.getInstance(module);
+ if (extension == null) {
+ return null;
+ }
if (forTestClasses) {
if (application.isDispatchThread()) {
final String url = extension.getCompilerOutputUrlForTests();
diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/DummyCompileContext.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/DummyCompileContext.java
index f308bd980aa5..9cffddabb503 100644
--- a/java/compiler/openapi/src/com/intellij/openapi/compiler/DummyCompileContext.java
+++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/DummyCompileContext.java
@@ -94,10 +94,6 @@ public class DummyCompileContext implements CompileContext {
return false;
}
- public VirtualFile[] getSourceRoots(Module module) {
- return VirtualFile.EMPTY_ARRAY;
- }
-
public VirtualFile getModuleOutputDirectory(final Module module) {
return ApplicationManager.getApplication().runReadAction(new Computable() {
public VirtualFile compute() {
@@ -121,6 +117,11 @@ public class DummyCompileContext implements CompileContext {
return false; // stub implementation
}
+ @Override
+ public boolean isAutomake() {
+ return false;
+ }
+
public boolean isRebuild() {
return false;
}
diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/JavaMarkObjectActionHandler.java b/java/debugger/impl/src/com/intellij/debugger/actions/JavaMarkObjectActionHandler.java
index a4ecca3e709b..56597fe99a15 100644
--- a/java/debugger/impl/src/com/intellij/debugger/actions/JavaMarkObjectActionHandler.java
+++ b/java/debugger/impl/src/com/intellij/debugger/actions/JavaMarkObjectActionHandler.java
@@ -15,7 +15,7 @@
*/
package com.intellij.debugger.actions;
-import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
+import com.intellij.codeInsight.daemon.impl.JavaHighlightInfoTypes;
import com.intellij.debugger.engine.DebugProcess;
import com.intellij.debugger.engine.DebugProcessImpl;
import com.intellij.debugger.engine.DebuggerUtils;
@@ -269,7 +269,7 @@ public class JavaMarkObjectActionHandler extends MarkObjectActionHandler {
public static Color getAutoMarkupColor() {
final EditorColorsManager manager = EditorColorsManager.getInstance();
- final TextAttributes textAttributes = manager.getGlobalScheme().getAttributes(HighlightInfoType.STATIC_FIELD.getAttributesKey());
+ final TextAttributes textAttributes = manager.getGlobalScheme().getAttributes(JavaHighlightInfoTypes.STATIC_FIELD.getAttributesKey());
return textAttributes.getForegroundColor();
}
}
diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/PopFrameAction.java b/java/debugger/impl/src/com/intellij/debugger/actions/PopFrameAction.java
index 8e1dc5075727..797273f6e578 100644
--- a/java/debugger/impl/src/com/intellij/debugger/actions/PopFrameAction.java
+++ b/java/debugger/impl/src/com/intellij/debugger/actions/PopFrameAction.java
@@ -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.
@@ -313,7 +313,7 @@ public class PopFrameAction extends DebuggerAction {
boolean enable = false;
StackFrameProxyImpl proxy = getStackFrameProxy(e);
- if (proxy != null && !proxy.isBottom() && isAtBreakpoint(e)) {
+ if (proxy != null && !proxy.isBottom() /*&& isAtBreakpoint(e)*/) {
enable = proxy.getVirtualMachine().canPopFrames();
}
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/ClassInstanceMethodFilter.java b/java/debugger/impl/src/com/intellij/debugger/engine/ClassInstanceMethodFilter.java
index 85a655c920a9..9f760da9e0c8 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/ClassInstanceMethodFilter.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/ClassInstanceMethodFilter.java
@@ -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.
@@ -49,7 +49,7 @@ public class ClassInstanceMethodFilter extends ConstructorStepMethodFilter imple
try {
ObjectReference reference = proxy.thisObject();
if (reference != null) {
- DebugProcessImpl debugProcess = context.getDebugProcessNoAssert();
+ DebugProcessImpl debugProcess = context.getDebugProcess();
BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(debugProcess.getProject()).getBreakpointManager();
StepIntoBreakpoint breakpoint = breakpointManager.addStepIntoBreakpoint(myMethodFilter);
if (breakpoint != null) {
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessEvents.java b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessEvents.java
index e88601093fbb..1a96a9cc51f2 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessEvents.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessEvents.java
@@ -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.
@@ -181,11 +181,12 @@ public class DebugProcessEvents extends DebugProcessImpl {
return;
}
+ LocatableEvent locatableEvent = getLocatableEvent(eventSet);
if (eventSet.suspendPolicy() == EventRequest.SUSPEND_ALL) {
// check if there is already one request with policy SUSPEND_ALL
for (SuspendContextImpl context : getSuspendManager().getEventContexts()) {
if (context.getSuspendPolicy() == EventRequest.SUSPEND_ALL) {
- if (Registry.is("debugger.step.resumes.one.thread") && getStepEvent(eventSet) != null) {
+ if (Registry.is("debugger.step.resumes.one.thread") && locatableEvent != null) {
// if step event is present - switch context
getSuspendManager().resume(context);
//((SuspendManagerImpl)getSuspendManager()).popContext(context);
@@ -201,10 +202,9 @@ public class DebugProcessEvents extends DebugProcessImpl {
SuspendContextImpl suspendContext = null;
- StepEvent stepEvent = getStepEvent(eventSet);
- if (Registry.is("debugger.step.resumes.one.thread") && stepEvent != null) {
+ if (Registry.is("debugger.step.resumes.one.thread") && locatableEvent != null) {
for (SuspendContextImpl context : getSuspendManager().getEventContexts()) {
- ThreadReferenceProxyImpl threadProxy = getVirtualMachineProxy().getThreadReferenceProxy(stepEvent.thread());
+ ThreadReferenceProxyImpl threadProxy = getVirtualMachineProxy().getThreadReferenceProxy(locatableEvent.thread());
if (context.getSuspendPolicy() == EventRequest.SUSPEND_ALL &&
context.isExplicitlyResumed(threadProxy)) {
context.myResumedThreads.remove(threadProxy);
@@ -526,10 +526,10 @@ public class DebugProcessEvents extends DebugProcessImpl {
}
@Nullable
- private static StepEvent getStepEvent(EventSet eventSet) {
+ private static LocatableEvent getLocatableEvent(EventSet eventSet) {
for (Event event : eventSet) {
- if (event instanceof StepEvent) {
- return (StepEvent)event;
+ if (event instanceof LocatableEvent) {
+ return (LocatableEvent)event;
}
}
return null;
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java
index e03008466d2e..98dcbaf5c76d 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java
@@ -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.
@@ -921,8 +921,10 @@ public abstract class DebugProcessImpl extends UserDataHolderBase implements Deb
}
private static int getInvokePolicy(SuspendContext suspendContext) {
- //return ThreadReference.INVOKE_SINGLE_THREADED;
- return suspendContext.getSuspendPolicy() == EventRequest.SUSPEND_EVENT_THREAD ? ObjectReference.INVOKE_SINGLE_THREADED : 0;
+ if (suspendContext.getSuspendPolicy() == EventRequest.SUSPEND_EVENT_THREAD || Registry.is("debugger.step.resumes.one.thread")) {
+ return ObjectReference.INVOKE_SINGLE_THREADED;
+ }
+ return 0;
}
@Override
@@ -995,6 +997,10 @@ public abstract class DebugProcessImpl extends UserDataHolderBase implements Deb
throw EvaluateExceptionUtil.NESTED_EVALUATION_ERROR;
}
+ if (!suspendContext.suspends(invokeThread)) {
+ throw EvaluateExceptionUtil.THREAD_WAS_RESUMED;
+ }
+
Set suspendingContexts = SuspendManagerUtil.getSuspendingContexts(getSuspendManager(), invokeThread);
final ThreadReference invokeThreadRef = invokeThread.getThreadReference();
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/DefaultSyntheticProvider.java b/java/debugger/impl/src/com/intellij/debugger/engine/DefaultSyntheticProvider.java
index 772e997da668..fd162f12a07c 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/DefaultSyntheticProvider.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/DefaultSyntheticProvider.java
@@ -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.
@@ -15,7 +15,7 @@
*/
package com.intellij.debugger.engine;
-import com.sun.jdi.ReferenceType;
+import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.sun.jdi.TypeComponent;
import com.sun.jdi.VirtualMachine;
@@ -30,8 +30,7 @@ public class DefaultSyntheticProvider implements SyntheticTypeComponentProvider
return false;
}
else {
- ReferenceType type = typeComponent.declaringType();
- if (type.name().contains("$$Lambda$")) {
+ if (DebuggerUtilsEx.isLambdaClassName(typeComponent.declaringType().name())) {
return true;
}
}
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/JavaDebugProcess.java b/java/debugger/impl/src/com/intellij/debugger/engine/JavaDebugProcess.java
index 7d1636ec0cb9..c9413a44dc6e 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/JavaDebugProcess.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/JavaDebugProcess.java
@@ -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.
@@ -59,8 +59,8 @@ import com.intellij.xdebugger.frame.XValueMarkerProvider;
import com.intellij.xdebugger.impl.XDebugSessionImpl;
import com.intellij.xdebugger.impl.XDebuggerUtilImpl;
import com.intellij.xdebugger.ui.XDebugTabLayouter;
-import com.sun.jdi.event.BreakpointEvent;
import com.sun.jdi.event.Event;
+import com.sun.jdi.event.LocatableEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.java.debugger.JavaDebuggerEditorsProvider;
@@ -123,8 +123,8 @@ public class JavaDebugProcess extends XDebugProcess {
if (item != null) {
XBreakpoint xBreakpoint = item.getFirst().getXBreakpoint();
Event second = item.getSecond();
- if (xBreakpoint != null && second instanceof BreakpointEvent &&
- threadProxy != null && ((BreakpointEvent)second).thread() == threadProxy.getThreadReference()) {
+ if (xBreakpoint != null && second instanceof LocatableEvent &&
+ threadProxy != null && ((LocatableEvent)second).thread() == threadProxy.getThreadReference()) {
((XDebugSessionImpl)getSession()).breakpointReachedNoProcessing(xBreakpoint, newSuspendContext);
unsetPausedIfNeeded(newContext);
return;
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/JavaDebuggerEvaluator.java b/java/debugger/impl/src/com/intellij/debugger/engine/JavaDebuggerEvaluator.java
index 1a15a5bc2335..4610d4b85104 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/JavaDebuggerEvaluator.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/JavaDebuggerEvaluator.java
@@ -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,7 +87,7 @@ public class JavaDebuggerEvaluator extends XDebuggerEvaluator {
TextWithImports text = TextWithImportsImpl.fromXExpression(expression);
NodeManagerImpl nodeManager = process.getNodeManager();
WatchItemDescriptor descriptor = nodeManager.getWatchItemDescriptor(null, text, null);
- EvaluationContextImpl evalContext = myStackFrame.getFrameDebuggerContext().createEvaluationContext();
+ EvaluationContextImpl evalContext = myStackFrame.getFrameDebuggerContext(getDebuggerContext()).createEvaluationContext();
if (evalContext == null) {
callback.errorOccurred("Context is not available");
return;
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/JavaStackFrame.java b/java/debugger/impl/src/com/intellij/debugger/engine/JavaStackFrame.java
index fb6078e54e4d..08647077a0b6 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/JavaStackFrame.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/JavaStackFrame.java
@@ -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.
@@ -139,18 +139,20 @@ public class JavaStackFrame extends XStackFrame {
public void threadAction() {
if (node.isObsolete()) return;
XValueChildrenList children = new XValueChildrenList();
- buildVariablesThreadAction(getFrameDebuggerContext(), children, node);
+ buildVariablesThreadAction(getFrameDebuggerContext(getDebuggerContext()), children, node);
node.addChildren(children, true);
}
});
}
- DebuggerContextImpl getFrameDebuggerContext() {
+ DebuggerContextImpl getFrameDebuggerContext(@Nullable DebuggerContextImpl context) {
DebuggerManagerThreadImpl.assertIsManagerThread();
- DebuggerContextImpl context = myDebugProcess.getDebuggerContext();
+ if (context == null) {
+ context = myDebugProcess.getDebuggerContext();
+ }
if (context.getFrameProxy() != getStackFrameProxy()) {
- SuspendContextImpl threadSuspendContext = SuspendManagerUtil.getSuspendContextForThread(context.getSuspendContext(),
- getStackFrameProxy().threadProxy());
+ SuspendContextImpl threadSuspendContext =
+ SuspendManagerUtil.findContextByThread(myDebugProcess.getSuspendManager(), getStackFrameProxy().threadProxy());
context = DebuggerContextImpl.createDebuggerContext(
myDebugProcess.mySession,
threadSuspendContext,
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/JavaValue.java b/java/debugger/impl/src/com/intellij/debugger/engine/JavaValue.java
index 80a37df68768..9ace154fe5f6 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/JavaValue.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/JavaValue.java
@@ -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.
@@ -401,9 +401,15 @@ public class JavaValue extends XNamedValue implements NodeDescriptorProvider, XV
protected static boolean scheduleCommand(EvaluationContextImpl evaluationContext,
@NotNull final XCompositeNode node,
final SuspendContextCommandImpl command) {
+ if (node.isObsolete()) {
+ return false;
+ }
evaluationContext.getManagerThread().schedule(new SuspendContextCommandImpl(command.getSuspendContext()) {
@Override
public void contextAction() throws Exception {
+ if (node.isObsolete()) {
+ return;
+ }
command.contextAction();
}
@@ -596,7 +602,7 @@ public class JavaValue extends XNamedValue implements NodeDescriptorProvider, XV
}
}
}
- EvaluationContextImpl evaluationContext = ((JavaStackFrame)frame).getFrameDebuggerContext().createEvaluationContext();
+ EvaluationContextImpl evaluationContext = ((JavaStackFrame)frame).getFrameDebuggerContext(null).createEvaluationContext();
if (evaluationContext != null) {
callback.evaluated(create(inspectDescriptor, evaluationContext, myNodeManager));
}
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java
index 3c0ed6780f10..1042389c5318 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java
@@ -41,6 +41,7 @@ import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.DocumentUtil;
import com.intellij.util.Function;
+import com.intellij.util.PairProcessor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.EmptyIterable;
import com.sun.jdi.AbsentInformationException;
@@ -432,7 +433,15 @@ public class PositionManagerImpl implements PositionManager, MultiRequestPositio
}
}
else {
- LOG.error("Local or anonymous class has no non-local parent");
+ final StringBuilder sb = new StringBuilder();
+ PsiTreeUtil.treeWalkUp(psiClass, null, new PairProcessor() {
+ @Override
+ public boolean process(PsiElement element, PsiElement element2) {
+ sb.append('\n').append(element);
+ return true;
+ }
+ });
+ LOG.info("Local or anonymous class " + psiClass + " has no non-local parent, parents:" + sb);
}
}
else {
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextImpl.java
index 15716907e6b1..75fef939d742 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextImpl.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextImpl.java
@@ -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.
@@ -126,11 +126,6 @@ public abstract class SuspendContextImpl extends XSuspendContext implements Susp
@Override
@NotNull
public DebugProcessImpl getDebugProcess() {
- assertNotResumed();
- return myDebugProcess;
- }
-
- public DebugProcessImpl getDebugProcessNoAssert() {
return myDebugProcess;
}
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendManagerImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendManagerImpl.java
index 0fe1e45cc5dc..0bab04a4987d 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendManagerImpl.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendManagerImpl.java
@@ -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.
@@ -185,10 +185,9 @@ public class SuspendManagerImpl implements SuspendManager {
SuspendManagerUtil.prepareForResume(context);
myDebugProcess.logThreads();
- final int suspendPolicy = context.getSuspendPolicy();
popContext(context);
context.resume();
- myDebugProcess.clearCashes(suspendPolicy);
+ myDebugProcess.clearCashes(context.getSuspendPolicy());
}
@Override
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendManagerUtil.java b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendManagerUtil.java
index a4b13089384f..4de93ccd6ee5 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendManagerUtil.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendManagerUtil.java
@@ -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.
@@ -126,14 +126,6 @@ public class SuspendManagerUtil {
return resumeData;
}
- public static SuspendContextImpl getSuspendContextForThread(SuspendContextImpl suspendContext, ThreadReferenceProxyImpl thread) {
- if (suspendContext == null) {
- return null;
- }
- SuspendContextImpl context = findContextByThread(suspendContext.getDebugProcess().getSuspendManager(), thread);
- return context != null && !context.myInProgress ? context : suspendContext;
- }
-
public static SuspendContextImpl getEvaluatingContext(SuspendManager suspendManager, ThreadReferenceProxyImpl thread) {
for (SuspendContextImpl suspendContext : suspendManager.getEventContexts()) {
if (!suspendContext.isResumed() && suspendContext.isEvaluating() && suspendContext.getThread() == thread) {
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/CodeFragmentFactoryContextWrapper.java b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/CodeFragmentFactoryContextWrapper.java
index 26e01417bd58..c9f035b446a5 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/CodeFragmentFactoryContextWrapper.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/CodeFragmentFactoryContextWrapper.java
@@ -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.
@@ -34,6 +34,7 @@ import com.intellij.xdebugger.impl.ui.tree.ValueMarkup;
import com.sun.jdi.ObjectCollectedException;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.Value;
+import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
@@ -64,6 +65,7 @@ public class CodeFragmentFactoryContextWrapper extends CodeFragmentFactory {
return myDelegate.isContextAccepted(contextElement);
}
+ @NotNull
public LanguageFileType getFileType() {
return myDelegate.getFileType();
}
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/DefaultCodeFragmentFactory.java b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/DefaultCodeFragmentFactory.java
index 1166f6f56c03..24d6006184a2 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/DefaultCodeFragmentFactory.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/DefaultCodeFragmentFactory.java
@@ -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,6 +33,7 @@ import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.util.PairFunction;
import com.intellij.util.concurrency.Semaphore;
+import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.atomic.AtomicReference;
@@ -119,6 +120,7 @@ public class DefaultCodeFragmentFactory extends CodeFragmentFactory {
return true; // default factory works everywhere debugger can stop
}
+ @NotNull
public LanguageFileType getFileType() {
return StdFileTypes.JAVA;
}
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/EvaluationContextImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/EvaluationContextImpl.java
index 252aca73cdc0..a89cad15303d 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/EvaluationContextImpl.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/EvaluationContextImpl.java
@@ -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.
@@ -62,7 +62,7 @@ public final class EvaluationContextImpl implements EvaluationContext{
}
public DebuggerManagerThreadImpl getManagerThread() {
- return getSuspendContext().getDebugProcessNoAssert().getManagerThread();
+ return getDebugProcess().getManagerThread();
}
@Override
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/events/DebuggerContextCommandImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/events/DebuggerContextCommandImpl.java
index 767811b4d274..b92395c887e0 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/events/DebuggerContextCommandImpl.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/events/DebuggerContextCommandImpl.java
@@ -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.
@@ -66,12 +66,6 @@ public abstract class DebuggerContextCommandImpl extends SuspendContextCommandIm
@Override
public final void contextAction() throws Exception {
- // with custom thread we have the right context already
- if (myCustomThread != null) {
- threadAction();
- return;
- }
-
SuspendManager suspendManager = myDebuggerContext.getDebugProcess().getSuspendManager();
boolean isSuspendedByContext;
try {
@@ -89,8 +83,9 @@ public abstract class DebuggerContextCommandImpl extends SuspendContextCommandIm
threadAction();
}
else {
- // there are no suspend context currently registered
- SuspendContextImpl suspendContextForThread = SuspendManagerUtil.findContextByThread(suspendManager, getThread());
+ // no suspend context currently available
+ SuspendContextImpl suspendContextForThread = myCustomThread != null ? getSuspendContext() :
+ SuspendManagerUtil.findContextByThread(suspendManager, getThread());
if (suspendContextForThread != null) {
suspendContextForThread.postponeCommand(this);
}
diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerContextUtil.java b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerContextUtil.java
index 564c1a75fea9..9376636e3367 100644
--- a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerContextUtil.java
+++ b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerContextUtil.java
@@ -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.
@@ -27,7 +27,6 @@ import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl;
-import com.intellij.openapi.util.Couple;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
@@ -37,9 +36,7 @@ import com.intellij.xdebugger.XDebugSession;
import com.intellij.xdebugger.XSourcePosition;
import org.jetbrains.annotations.NotNull;
-import java.util.ArrayList;
import java.util.Collection;
-import java.util.List;
public class DebuggerContextUtil {
public static void setStackFrame(final DebuggerStateManager manager, final StackFrameProxyImpl stackFrame) {
@@ -56,8 +53,10 @@ public class DebuggerContextUtil {
@Override
protected void action() throws Exception {
- SuspendContextImpl threadSuspendContext = SuspendManagerUtil.getSuspendContextForThread(context.getSuspendContext(), stackFrame.threadProxy());
- final DebuggerContextImpl newContext = DebuggerContextImpl.createDebuggerContext(session, threadSuspendContext, stackFrame.threadProxy(), stackFrame);
+ SuspendContextImpl threadSuspendContext =
+ SuspendManagerUtil.findContextByThread(session.getProcess().getSuspendManager(), stackFrame.threadProxy());
+ final DebuggerContextImpl newContext =
+ DebuggerContextImpl.createDebuggerContext(session, threadSuspendContext, stackFrame.threadProxy(), stackFrame);
DebuggerInvocationUtil.swingInvokeLater(session.getProject(), new Runnable() {
@Override
public void run() {
@@ -98,11 +97,8 @@ public class DebuggerContextUtil {
//final Editor editor = fileEditor instanceof TextEditorImpl ? ((TextEditorImpl)fileEditor).getEditor() : null;
if (editor != null && position != null && file.getVirtualFile().equals(position.getFile())) {
PsiMethod method = PsiTreeUtil.getParentOfType(PositionUtil.getContextElement(context), PsiMethod.class, false);
- final Couple> usages =
- IdentifierHighlighterPass.getHighlightUsages(psi, method != null ? method : file, false);
- final List ranges = new ArrayList();
- ranges.addAll(usages.first);
- ranges.addAll(usages.second);
+ final Collection ranges =
+ IdentifierHighlighterPass.getUsages(psi, method != null ? method : file, false);
final int breakPointLine = position.getLine();
int bestLine = -1;
int bestOffset = -1;
diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerUtilsEx.java b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerUtilsEx.java
index 68c949e0bb2e..0f062bf231cf 100644
--- a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerUtilsEx.java
+++ b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerUtilsEx.java
@@ -100,7 +100,6 @@ public abstract class DebuggerUtilsEx extends DebuggerUtils {
return suitableFactories;
}
-
public static PsiMethod findPsiMethod(PsiFile file, int offset) {
PsiElement element = null;
@@ -461,22 +460,30 @@ public abstract class DebuggerUtilsEx extends DebuggerUtils {
public abstract EvaluatorBuilder getEvaluatorBuilder();
+ public static CodeFragmentFactory getCodeFragmentFactory(@Nullable PsiElement context, @Nullable FileType fileType) {
+ DefaultCodeFragmentFactory defaultFactory = DefaultCodeFragmentFactory.getInstance();
+ if (fileType == null) {
+ if (context == null) {
+ return defaultFactory;
+ }
+ else {
+ fileType = context.getContainingFile().getFileType();
+ }
+ }
+ for (CodeFragmentFactory factory : ApplicationManager.getApplication().getExtensions(CodeFragmentFactory.EXTENSION_POINT_NAME)) {
+ if (factory != defaultFactory && factory.getFileType().equals(fileType) && factory.isContextAccepted(context)) {
+ return factory;
+ }
+ }
+ return defaultFactory;
+ }
+
@NotNull
public static CodeFragmentFactory findAppropriateCodeFragmentFactory(final TextWithImports text, final PsiElement context) {
CodeFragmentFactory factory = ApplicationManager.getApplication().runReadAction(new Computable() {
@Override
public CodeFragmentFactory compute() {
- final FileType fileType = text.getFileType();
- final List factories = getCodeFragmentFactories(context);
- if (fileType == null) {
- return factories.get(0);
- }
- for (CodeFragmentFactory factory : factories) {
- if (factory.getFileType().equals(fileType)) {
- return factory;
- }
- }
- return DefaultCodeFragmentFactory.getInstance();
+ return getCodeFragmentFactory(context, text.getFileType());
}
});
return new CodeFragmentFactoryContextWrapper(factory);
@@ -801,6 +808,15 @@ public abstract class DebuggerUtilsEx extends DebuggerUtils {
return null;
}
+ public static boolean isLambdaClassName(String typeName) {
+ return getLambdaBaseClassName(typeName) != null;
+ }
+
+ @Nullable
+ public static String getLambdaBaseClassName(String typeName) {
+ return StringUtil.substringBefore(typeName, "$$Lambda$");
+ }
+
public static List collectLambdas(@NotNull SourcePosition position, final boolean onlyOnTheLine) {
ApplicationManager.getApplication().assertReadAccessAllowed();
PsiFile file = position.getFile();
diff --git a/java/debugger/impl/src/com/intellij/debugger/settings/DebuggerSettings.java b/java/debugger/impl/src/com/intellij/debugger/settings/DebuggerSettings.java
index 5b80d27cd3d3..9edbb0440d71 100644
--- a/java/debugger/impl/src/com/intellij/debugger/settings/DebuggerSettings.java
+++ b/java/debugger/impl/src/com/intellij/debugger/settings/DebuggerSettings.java
@@ -16,7 +16,10 @@
package com.intellij.debugger.settings;
import com.intellij.debugger.impl.DebuggerUtilsEx;
-import com.intellij.openapi.components.*;
+import com.intellij.openapi.components.PersistentStateComponent;
+import com.intellij.openapi.components.ServiceManager;
+import com.intellij.openapi.components.State;
+import com.intellij.openapi.components.Storage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
@@ -36,7 +39,10 @@ import java.util.Map;
@State(
name = "DebuggerSettings",
defaultStateAsResource = true,
- storages = @Storage(file = StoragePathMacros.APP_CONFIG + "/other.xml")
+ storages = {
+ @Storage(file = "debugger.xml"),
+ @Storage(file = "other.xml", deprecated = true)
+ }
)
public class DebuggerSettings implements Cloneable, PersistentStateComponent {
private static final Logger LOG = Logger.getInstance(DebuggerSettings.class);
diff --git a/java/debugger/impl/src/com/intellij/debugger/settings/NodeRendererSettings.java b/java/debugger/impl/src/com/intellij/debugger/settings/NodeRendererSettings.java
index 5facfe560008..441fb5448970 100644
--- a/java/debugger/impl/src/com/intellij/debugger/settings/NodeRendererSettings.java
+++ b/java/debugger/impl/src/com/intellij/debugger/settings/NodeRendererSettings.java
@@ -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.
@@ -67,7 +67,6 @@ public class NodeRendererSettings implements PersistentStateComponent {
@NonNls private static final String RENDERER_ID = "ID";
private final EventDispatcher myDispatcher = EventDispatcher.create(NodeRendererSettingsListener.class);
- private final List myPluginRenderers = new ArrayList();
private RendererConfiguration myCustomRenderers = new RendererConfiguration(this);
// base renderers
@@ -110,20 +109,6 @@ public class NodeRendererSettings implements PersistentStateComponent {
return ServiceManager.getService(NodeRendererSettings.class);
}
- /**
- * use {@link NodeRenderer} extension
- * @param renderer
- */
- @Deprecated
- public void addPluginRenderer(NodeRenderer renderer) {
- myPluginRenderers.add(renderer);
- }
-
- @Deprecated
- public void removePluginRenderer(NodeRenderer renderer) {
- myPluginRenderers.remove(renderer);
- }
-
public void setAlternateCollectionViewsEnabled(boolean enabled) {
for (NodeRenderer myAlternateCollectionRenderer : myAlternateCollectionRenderers) {
myAlternateCollectionRenderer.setEnabled(enabled);
@@ -227,10 +212,6 @@ public class NodeRendererSettings implements PersistentStateComponent {
}
}
- public List getPluginRenderers() {
- return new ArrayList(myPluginRenderers);
- }
-
public PrimitiveRenderer getPrimitiveRenderer() {
return myPrimitiveRenderer;
}
@@ -272,7 +253,6 @@ public class NodeRendererSettings implements PersistentStateComponent {
});
// plugins registered renderers come after that
- allRenderers.addAll(myPluginRenderers);
Collections.addAll(allRenderers, NodeRenderer.EP_NAME.getExtensions());
// now all predefined stuff
diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/DebuggerEditorImpl.java b/java/debugger/impl/src/com/intellij/debugger/ui/DebuggerEditorImpl.java
index 6fb6cf8bf371..4dc1e315913f 100644
--- a/java/debugger/impl/src/com/intellij/debugger/ui/DebuggerEditorImpl.java
+++ b/java/debugger/impl/src/com/intellij/debugger/ui/DebuggerEditorImpl.java
@@ -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,10 @@
package com.intellij.debugger.ui;
import com.intellij.debugger.DebuggerManagerEx;
-import com.intellij.debugger.engine.evaluation.*;
+import com.intellij.debugger.engine.evaluation.CodeFragmentFactory;
+import com.intellij.debugger.engine.evaluation.CodeFragmentFactoryContextWrapper;
+import com.intellij.debugger.engine.evaluation.TextWithImports;
+import com.intellij.debugger.engine.evaluation.TextWithImportsImpl;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.impl.PositionUtil;
import com.intellij.ide.DataManager;
@@ -287,22 +290,12 @@ public abstract class DebuggerEditorImpl extends CompletionEditor {
}
}
- @NotNull
- private static CodeFragmentFactory findAppropriateFactory(@NotNull TextWithImports text, @Nullable PsiElement context) {
- for (CodeFragmentFactory factory : DebuggerUtilsEx.getCodeFragmentFactories(context)) {
- if (factory.getFileType().equals(text.getFileType())) {
- return factory;
- }
- }
- return DefaultCodeFragmentFactory.getInstance();
- }
-
protected void restoreFactory(TextWithImports text) {
FileType fileType = text.getFileType();
if (fileType == null) return;
if (myContext == null) return;
- setFactory(findAppropriateFactory(text, myContext));
+ setFactory(DebuggerUtilsEx.getCodeFragmentFactory(myContext, text.getFileType()));
}
private void setFactory(@NotNull CodeFragmentFactory factory) {
diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/JavaLineBreakpointType.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/JavaLineBreakpointType.java
index 50ac2b9474f3..08af8387cf5a 100644
--- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/JavaLineBreakpointType.java
+++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/JavaLineBreakpointType.java
@@ -78,7 +78,7 @@ public class JavaLineBreakpointType extends JavaLineBreakpointTypeBase 0) {
return typeName.substring(dotIndex + 1);
diff --git a/java/debugger/openapi/src/com/intellij/debugger/engine/evaluation/CodeFragmentFactory.java b/java/debugger/openapi/src/com/intellij/debugger/engine/evaluation/CodeFragmentFactory.java
index f7ceafc23355..1beb594ad23e 100644
--- a/java/debugger/openapi/src/com/intellij/debugger/engine/evaluation/CodeFragmentFactory.java
+++ b/java/debugger/openapi/src/com/intellij/debugger/engine/evaluation/CodeFragmentFactory.java
@@ -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.
@@ -21,6 +21,7 @@ import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.project.Project;
import com.intellij.psi.JavaCodeFragment;
import com.intellij.psi.PsiElement;
+import org.jetbrains.annotations.NotNull;
public abstract class CodeFragmentFactory {
public static final ExtensionPointName EXTENSION_POINT_NAME = ExtensionPointName.create("com.intellij.debugger.codeFragmentFactory");
@@ -31,6 +32,7 @@ public abstract class CodeFragmentFactory {
public abstract boolean isContextAccepted(PsiElement contextElement);
+ @NotNull
public abstract LanguageFileType getFileType();
/**
diff --git a/java/execution/impl/src/com/intellij/execution/junit/JUnitUtil.java b/java/execution/impl/src/com/intellij/execution/junit/JUnitUtil.java
index 9e088f81785b..74bf67d2c428 100644
--- a/java/execution/impl/src/com/intellij/execution/junit/JUnitUtil.java
+++ b/java/execution/impl/src/com/intellij/execution/junit/JUnitUtil.java
@@ -55,8 +55,8 @@ public class JUnitUtil {
public static final String BEFORE_ANNOTATION_NAME = "org.junit.Before";
public static final String AFTER_ANNOTATION_NAME = "org.junit.After";
public static final String PARAMETRIZED_PARAMETERS_ANNOTATION_NAME = "org.junit.runners.Parameterized.Parameters";
- private static final String AFTER_CLASS_ANNOTATION_NAME = "org.junit.AfterClass";
- private static final String BEFORE_CLASS_ANNOTATION_NAME = "org.junit.BeforeClass";
+ public static final String AFTER_CLASS_ANNOTATION_NAME = "org.junit.AfterClass";
+ public static final String BEFORE_CLASS_ANNOTATION_NAME = "org.junit.BeforeClass";
private static final Collection CONFIGURATIONS_ANNOTATION_NAME = Collections.unmodifiableList(
Arrays.asList(DATA_POINT, AFTER_ANNOTATION_NAME, BEFORE_ANNOTATION_NAME, AFTER_CLASS_ANNOTATION_NAME, BEFORE_CLASS_ANNOTATION_NAME));
diff --git a/java/execution/impl/src/com/intellij/execution/testframework/JavaTestLocator.java b/java/execution/impl/src/com/intellij/execution/testframework/JavaTestLocator.java
index ac4c581f15e9..a02ef2a4d8fd 100644
--- a/java/execution/impl/src/com/intellij/execution/testframework/JavaTestLocator.java
+++ b/java/execution/impl/src/com/intellij/execution/testframework/JavaTestLocator.java
@@ -67,7 +67,7 @@ public class JavaTestLocator implements SMTestLocator {
PsiClass aClass = ClassUtil.findPsiClass(PsiManager.getInstance(project), className, null, true, scope);
if (aClass != null) {
results = ContainerUtil.newSmartList();
- PsiMethod[] methods = aClass.findMethodsByName(methodName, true);
+ PsiMethod[] methods = aClass.findMethodsByName(methodName.trim(), true);
if (methods.length > 0) {
for (PsiMethod method : methods) {
results.add(paramName != null ? new PsiMemberParameterizedLocation(project, method, aClass, paramName)
diff --git a/java/execution/impl/src/com/intellij/testIntegration/RecentTestRunner.java b/java/execution/impl/src/com/intellij/testIntegration/RecentTestRunner.java
index 629a7e623618..47556660b43f 100644
--- a/java/execution/impl/src/com/intellij/testIntegration/RecentTestRunner.java
+++ b/java/execution/impl/src/com/intellij/testIntegration/RecentTestRunner.java
@@ -45,7 +45,7 @@ class RecentTestRunnerImpl implements RecentTestRunner {
private static AnAction RUN = ActionManager.getInstance().getAction("RunClass");
private static AnAction DEBUG = ActionManager.getInstance().getAction("DebugClass");
- protected AnAction myCurrentAction = DEBUG;
+ protected AnAction myCurrentAction = RUN;
private final Project myProject;
public RecentTestRunnerImpl(Project project) {
diff --git a/java/execution/impl/src/com/intellij/testIntegration/RecentTestsData.java b/java/execution/impl/src/com/intellij/testIntegration/RecentTestsData.java
new file mode 100644
index 000000000000..191a7644eb8e
--- /dev/null
+++ b/java/execution/impl/src/com/intellij/testIntegration/RecentTestsData.java
@@ -0,0 +1,258 @@
+/*
+ * 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.testIntegration;
+
+import com.intellij.execution.testframework.sm.runner.states.TestStateInfo;
+import com.intellij.openapi.util.Condition;
+import com.intellij.openapi.vfs.VirtualFileManager;
+import com.intellij.util.containers.ContainerUtil;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.*;
+
+import static com.intellij.execution.testframework.sm.runner.states.TestStateInfo.Magnitude.*;
+import static com.intellij.testIntegration.TestInfo.select;
+import static com.intellij.testIntegration.TestInfo.selectNot;
+
+public class RecentTestsData {
+ private static Comparator TEST_BY_PATH_COMPARATOR = new Comparator() {
+ @Override
+ public int compare(TestInfo o1, TestInfo o2) {
+ String path1 = VirtualFileManager.extractPath(o1.getUrl());
+ String path2 = VirtualFileManager.extractPath(o2.getUrl());
+ return path1.compareTo(path2);
+ }
+ };
+
+ private static Comparator SUITE_BY_RECENT_COMPARATOR = new Comparator() {
+ @Override
+ public int compare(SuiteInfo o1, SuiteInfo o2) {
+ return -o1.getMostRecentRunDate().compareTo(o2.getMostRecentRunDate());
+ }
+ };
+
+ private static Comparator TEST_BY_RECENT_COMPARATOR = new Comparator() {
+ @Override
+ public int compare(TestInfo o1, TestInfo o2) {
+ return -o1.getRunDate().compareTo(o2.getRunDate());
+ }
+ };
+
+ private final RecentTestRunner myRunner;
+ private final Map mySuites = ContainerUtil.newHashMap();
+
+ private List myTestsWithoutSuites = ContainerUtil.newArrayList();
+
+ public RecentTestsData(RecentTestRunner runner) {
+ myRunner = runner;
+ }
+
+ public void addTest(String url, TestStateInfo.Magnitude magnitude, Date runDate) {
+ if (myRunner.isSuite(url)) {
+ mySuites.put(url, new SuiteInfo(url, magnitude, runDate));
+ return;
+ }
+
+ TestInfo testInfo = new TestInfo(url, magnitude, runDate);
+
+ SuiteInfo suite = getSuite(url);
+ if (suite != null) {
+ suite.addTest(testInfo);
+ return;
+ }
+
+ myTestsWithoutSuites.add(testInfo);
+ }
+
+ @Nullable
+ private SuiteInfo getSuite(String url) {
+ String testName = VirtualFileManager.extractPath(url);
+
+ for (SuiteInfo info : mySuites.values()) {
+ String suiteName = info.getSuiteName();
+ if (testName.startsWith(suiteName)) {
+ return info;
+ }
+ }
+
+ return null;
+ }
+
+ public List calculateTestList() {
+ distributeUnmatchedTests();
+
+ List suites = ContainerUtil.newArrayList(mySuites.values());
+ Collections.sort(suites, TEST_BY_PATH_COMPARATOR);
+ Collections.sort(myTestsWithoutSuites, TEST_BY_PATH_COMPARATOR);
+
+ Collections.sort(suites, SUITE_BY_RECENT_COMPARATOR);
+ Collections.sort(myTestsWithoutSuites, TEST_BY_RECENT_COMPARATOR);
+
+ List result = ContainerUtil.newArrayList();
+
+ fillWithSuites(result, select(suites, ERROR_INDEX));
+ fillWithTests(result, select(myTestsWithoutSuites, ERROR_INDEX));
+
+ fillWithSuites(result, selectNot(suites, ERROR_INDEX, COMPLETE_INDEX, PASSED_INDEX));
+ fillWithTests(result, selectNot(myTestsWithoutSuites, COMPLETE_INDEX, PASSED_INDEX));
+
+ fillWithSuites(result, select(suites, COMPLETE_INDEX, PASSED_INDEX));
+ fillWithTests(result, select(myTestsWithoutSuites, COMPLETE_INDEX, PASSED_INDEX));
+
+ return result;
+ }
+
+ private static void fillWithTests(List result, List tests) {
+ for (TestInfo info : tests) {
+ result.add(info.getUrl());
+ }
+ }
+
+ private static void fillWithSuites(List result, List suites) {
+ for (SuiteInfo suite : suites) {
+ result.addAll(suiteToTestList(suite));
+ }
+ }
+
+ private static List suiteToTestList(SuiteInfo suite) {
+ List result = ContainerUtil.newArrayList();
+
+ TestStateInfo.Magnitude suiteMagnitude = suite.getMagnitude();
+ Set allTests = suite.getTests();
+
+ List sameMagnitudeTests = suite.getTests(suiteMagnitude);
+ if (sameMagnitudeTests.size() == allTests.size()) {
+ result.add(suite.getUrl());
+ }
+ else {
+ result.add(suite.getUrl());
+ Collections.sort(sameMagnitudeTests, TEST_BY_RECENT_COMPARATOR);
+ for (TestInfo test : sameMagnitudeTests) {
+ result.add(test.getUrl());
+ }
+ }
+
+ return result;
+ }
+
+
+ private void distributeUnmatchedTests() {
+ List noSuites = ContainerUtil.newSmartList();
+
+ for (TestInfo test : myTestsWithoutSuites) {
+ String url = test.getUrl();
+ SuiteInfo suite = getSuite(url);
+ if (suite != null) {
+ suite.addTest(test);
+ }
+ else {
+ noSuites.add(test);
+ }
+ }
+
+ myTestsWithoutSuites = noSuites;
+ }
+}
+
+
+class SuiteInfo extends TestInfo {
+ private final String mySuiteName;
+ private Set tests = ContainerUtil.newHashSet();
+
+ public SuiteInfo(String url, TestStateInfo.Magnitude magnitude, Date runDate) {
+ super(url, magnitude, runDate);
+ mySuiteName = VirtualFileManager.extractPath(url);
+ }
+
+ public Date getMostRecentRunDate() {
+ Date mostRecent = getRunDate();
+ for (TestInfo test : tests) {
+ Date testDate = test.getRunDate();
+ if (testDate.compareTo(mostRecent) > 0) {
+ mostRecent = testDate;
+ }
+ }
+ return mostRecent;
+ }
+
+ public String getSuiteName() {
+ return mySuiteName;
+ }
+
+ public void addTest(TestInfo info) {
+ tests.add(info);
+ }
+
+ public Set getTests() {
+ return tests;
+ }
+
+ public List getTests(TestStateInfo.Magnitude magnitude) {
+ return select(tests, magnitude);
+ }
+}
+
+class TestInfo {
+ private final Date runDate;
+ private final String url;
+ private final TestStateInfo.Magnitude magnitude;
+
+ public TestInfo(String url, TestStateInfo.Magnitude magnitude, Date runDate) {
+ this.url = url;
+ this.magnitude = magnitude;
+ this.runDate = runDate;
+ }
+
+ public Date getRunDate() {
+ return runDate;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public TestStateInfo.Magnitude getMagnitude() {
+ return magnitude;
+ }
+
+ public static List select(Collection infos, final TestStateInfo.Magnitude... magnitudes) {
+ return ContainerUtil.filter(infos, new Condition() {
+ @Override
+ public boolean value(T t) {
+ for (TestStateInfo.Magnitude magnitude : magnitudes) {
+ if (t.getMagnitude() == magnitude) {
+ return true;
+ }
+ }
+ return false;
+ }
+ });
+ }
+
+ public static List selectNot(Collection infos, final TestStateInfo.Magnitude... magnitudes) {
+ return ContainerUtil.filter(infos, new Condition() {
+ @Override
+ public boolean value(T t) {
+ for (TestStateInfo.Magnitude magnitude : magnitudes) {
+ if (t.getMagnitude() == magnitude) {
+ return false;
+ }
+ }
+ return true;
+ }
+ });
+ }
+}
diff --git a/java/execution/impl/src/com/intellij/testIntegration/SelectTestStep.java b/java/execution/impl/src/com/intellij/testIntegration/SelectTestStep.java
index 0709edab77da..0f0d458249f1 100644
--- a/java/execution/impl/src/com/intellij/testIntegration/SelectTestStep.java
+++ b/java/execution/impl/src/com/intellij/testIntegration/SelectTestStep.java
@@ -22,22 +22,14 @@ import com.intellij.execution.testframework.sm.runner.states.TestStateInfo;
import com.intellij.openapi.ui.popup.PopupStep;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.vfs.VirtualFileManager;
-import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
-import java.util.*;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
public class SelectTestStep extends BaseListPopupStep {
- private static Comparator TEST_BY_PATH_COMPARATOR = new Comparator() {
- @Override
- public int compare(String o1, String o2) {
- String path1 = VirtualFileManager.extractPath(o1);
- String path2 = VirtualFileManager.extractPath(o2);
- return path1.compareTo(path2);
- }
- };
-
private final Map myRecords;
private final RecentTestRunner myRunner;
@@ -48,50 +40,15 @@ public class SelectTestStep extends BaseListPopupStep {
}
private static List getUrls(Map records, RecentTestRunner runner) {
- TestGroup groups = toTestGroups(records, runner);
-
- List failed = ContainerUtil.newArrayList(groups.failedTests);
- Collections.sort(failed, TEST_BY_PATH_COMPARATOR);
- List other = ContainerUtil.newArrayList(groups.otherTests);
- Collections.sort(other, TEST_BY_PATH_COMPARATOR);
- List passed = ContainerUtil.newArrayList(groups.passedTests);
- Collections.sort(passed, TEST_BY_PATH_COMPARATOR);
-
- failed.addAll(other);
- failed.addAll(passed);
- return failed;
- }
+ RecentTestsData data = new RecentTestsData(runner);
- private static TestGroup toTestGroups(Map records, RecentTestRunner runner) {
- Set failedTests = ContainerUtil.newHashSet();
- Set passedSuites = ContainerUtil.newHashSet();
- Set otherSuites = ContainerUtil.newHashSet();
-
- for (Map.Entry item : records.entrySet()) {
- String url = item.getKey();
- TestStateInfo.Magnitude magnitude = getMagnitude(item.getValue().magnitude);
- if (magnitude == null) continue;
- switch (magnitude) {
- case COMPLETE_INDEX:
- if (runner.isSuite(url)) {
- passedSuites.add(url);
- }
- break;
- case PASSED_INDEX:
- if (runner.isSuite(url)) {
- passedSuites.add(url);
- }
- break;
- case ERROR_INDEX:
- failedTests.add(url);
- break;
- default:
- otherSuites.add(url);
- break;
- }
+ for (Map.Entry entry : records.entrySet()) {
+ String url = entry.getKey();
+ TestStateStorage.Record record = entry.getValue();
+ data.addTest(url, getMagnitude(record.magnitude), record.date);
}
-
- return new TestGroup(failedTests, passedSuites, otherSuites);
+
+ return data.calculateTestList();
}
private static TestStateInfo.Magnitude getMagnitude(int magnitude) {
diff --git a/java/execution/impl/src/com/intellij/testIntegration/ShowRecentTests.java b/java/execution/impl/src/com/intellij/testIntegration/ShowRecentTests.java
index 4834b82214bb..5647a6bc3918 100644
--- a/java/execution/impl/src/com/intellij/testIntegration/ShowRecentTests.java
+++ b/java/execution/impl/src/com/intellij/testIntegration/ShowRecentTests.java
@@ -19,12 +19,14 @@ import com.intellij.execution.Location;
import com.intellij.execution.TestStateStorage;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
-import com.intellij.openapi.actionSystem.CommonDataKeys;
+import com.intellij.openapi.keymap.MacKeymapUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.ListPopupStep;
+import com.intellij.openapi.util.SystemInfo;
import com.intellij.ui.popup.list.ListPopupImpl;
import com.intellij.util.PsiNavigateUtil;
import com.intellij.util.Time;
+import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.event.ActionEvent;
@@ -39,9 +41,14 @@ public class ShowRecentTests extends AnAction {
return new Date(System.currentTimeMillis() - Time.DAY);
}
+ @Override
+ public void update(@NotNull AnActionEvent e) {
+ e.getPresentation().setEnabled(e.getProject() != null);
+ }
+
@Override
public void actionPerformed(AnActionEvent e) {
- final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext());
+ final Project project = e.getProject();
if (project == null) return;
Map records = TestStateStorage.getInstance(project).getRecentTests(TEST_LIMIT, getSinceDate());
@@ -61,6 +68,9 @@ class RecentTestsListPopup extends ListPopupImpl {
myTestRunner = testRunner;
shiftReleased();
registerActions(this);
+
+ String shift = SystemInfo.isMac ? MacKeymapUtil.SHIFT : "Shift";
+ setAdText("Debug with " + shift + ", navigate with F4");
}
private void registerActions(ListPopupImpl popup) {
@@ -98,13 +108,13 @@ class RecentTestsListPopup extends ListPopupImpl {
}
private void shiftPressed() {
- setCaption("Run Recent Tests");
- myTestRunner.setMode(RecentTestRunner.Mode.RUN);
+ setCaption("Debug Recent Tests");
+ myTestRunner.setMode(RecentTestRunner.Mode.DEBUG);
}
private void shiftReleased() {
- setCaption("Debug Recent Tests");
- myTestRunner.setMode(RecentTestRunner.Mode.DEBUG);
+ setCaption("Run Recent Tests");
+ myTestRunner.setMode(RecentTestRunner.Mode.RUN);
}
}
diff --git a/java/idea-ui/src/com/intellij/facet/impl/ui/FacetEditorImpl.java b/java/idea-ui/src/com/intellij/facet/impl/ui/FacetEditorImpl.java
index 41868ba87529..d7a7baab0f51 100644
--- a/java/idea-ui/src/com/intellij/facet/impl/ui/FacetEditorImpl.java
+++ b/java/idea-ui/src/com/intellij/facet/impl/ui/FacetEditorImpl.java
@@ -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.
@@ -27,6 +27,7 @@ import com.intellij.openapi.options.UnnamedConfigurable;
import com.intellij.openapi.options.UnnamedConfigurableGroup;
import com.intellij.openapi.util.Disposer;
import com.intellij.ui.TabbedPaneWrapper;
+import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -96,14 +97,14 @@ public class FacetEditorImpl extends UnnamedConfigurableGroup implements Unnamed
}
else if (myEditorTabs.length == 1) {
editorComponent = myEditorTabs[0].createComponent();
- UIUtil.addInsets(editorComponent, new Insets(0, 5, 0, 0));
+ UIUtil.addInsets(editorComponent, JBUI.insets(0, 5, 0, 0));
}
else {
editorComponent = new JPanel();
}
final JComponent errorComponent = myErrorPanel.getComponent();
- UIUtil.addInsets(errorComponent, new Insets(0, 5, 5, 0));
+ UIUtil.addInsets(errorComponent, JBUI.insets(0, 5, 5, 0));
final JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, editorComponent);
diff --git a/java/idea-ui/src/com/intellij/ide/actions/ShowStructureSettingsAction.java b/java/idea-ui/src/com/intellij/ide/actions/ShowStructureSettingsAction.java
index e6ce665906c9..025608265e1e 100644
--- a/java/idea-ui/src/com/intellij/ide/actions/ShowStructureSettingsAction.java
+++ b/java/idea-ui/src/com/intellij/ide/actions/ShowStructureSettingsAction.java
@@ -18,14 +18,12 @@ package com.intellij.ide.actions;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
-import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.options.ex.SingleConfigurableEditor;
import com.intellij.openapi.options.newEditor.SettingsDialog;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.roots.ui.configuration.ProjectStructureConfigurable;
-import com.intellij.openapi.util.registry.Registry;
import org.jetbrains.annotations.NotNull;
public class ShowStructureSettingsAction extends AnAction implements DumbAware {
@@ -39,18 +37,12 @@ public class ShowStructureSettingsAction extends AnAction implements DumbAware {
}
static void showDialog(Project project) {
- if (Registry.is("ide.new.project.settings")) {
- new SingleConfigurableEditor(project, ProjectStructureConfigurable.getInstance(project), SettingsDialog.DIMENSION_KEY) {
- @NotNull
- @Override
- protected DialogStyle getStyle() {
- return DialogStyle.COMPACT;
- }
- }.show();
- }
- else {
- ShowSettingsUtil
- .getInstance().editConfigurable(project, SettingsDialog.DIMENSION_KEY, ProjectStructureConfigurable.getInstance(project));
- }
+ new SingleConfigurableEditor(project, ProjectStructureConfigurable.getInstance(project), SettingsDialog.DIMENSION_KEY) {
+ @NotNull
+ @Override
+ protected DialogStyle getStyle() {
+ return DialogStyle.COMPACT;
+ }
+ }.show();
}
}
\ No newline at end of file
diff --git a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java
index 1fdce85e8883..462a8e49f44c 100644
--- a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java
+++ b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java
@@ -604,40 +604,40 @@ public class ProjectTypeStep extends ModuleWizardStep implements SettingsStep, D
}
void loadRemoteTemplates(final ChooseTemplateStep chooseTemplateStep) {
+ myTemplatesList.setPaintBusy(true);
+ chooseTemplateStep.getTemplateList().setPaintBusy(true);
ProgressManager.getInstance().run(new Task.Backgroundable(myContext.getProject(), "Loading Templates") {
@Override
public void run(@NotNull ProgressIndicator indicator) {
- try {
- myTemplatesList.setPaintBusy(true);
- chooseTemplateStep.getTemplateList().setPaintBusy(true);
- RemoteTemplatesFactory factory = new RemoteTemplatesFactory();
- for (String group : factory.getGroups()) {
- ProjectTemplate[] templates = factory.createTemplates(group, myContext);
- for (ProjectTemplate template : templates) {
- String id = ((ArchivedProjectTemplate)template).getCategory();
- for (TemplatesGroup templatesGroup : myTemplatesMap.keySet()) {
- if (Comparing.equal(id, templatesGroup.getId()) || Comparing.equal(group, templatesGroup.getName())) {
- myTemplatesMap.putValue(templatesGroup, template);
- }
+ RemoteTemplatesFactory factory = new RemoteTemplatesFactory();
+ for (String group : factory.getGroups()) {
+ ProjectTemplate[] templates = factory.createTemplates(group, myContext);
+ for (ProjectTemplate template : templates) {
+ String id = ((ArchivedProjectTemplate)template).getCategory();
+ for (TemplatesGroup templatesGroup : myTemplatesMap.keySet()) {
+ if (Comparing.equal(id, templatesGroup.getId()) || Comparing.equal(group, templatesGroup.getName())) {
+ myTemplatesMap.putValue(templatesGroup, template);
}
}
}
- //noinspection SSBasedInspection
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- TemplatesGroup group = getSelectedGroup();
- if (group == null) return;
- Collection templates = myTemplatesMap.get(group);
- setTemplatesList(group, templates, true);
- chooseTemplateStep.updateStep();
- }
- });
- }
- finally {
- myTemplatesList.setPaintBusy(false);
- chooseTemplateStep.getTemplateList().setPaintBusy(false);
}
}
+
+ @Override
+ public void onSuccess() {
+ super.onSuccess();
+ TemplatesGroup group = getSelectedGroup();
+ if (group == null) return;
+ Collection templates = myTemplatesMap.get(group);
+ setTemplatesList(group, templates, true);
+ chooseTemplateStep.updateStep();
+ }
+
+ @Override
+ public void onFinished() {
+ myTemplatesList.setPaintBusy(false);
+ chooseTemplateStep.getTemplateList().setPaintBusy(false);
+ }
});
}
diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddSupportForFrameworksPanel.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddSupportForFrameworksPanel.java
index ea88dcd3698e..b3d3d05a1fbc 100644
--- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddSupportForFrameworksPanel.java
+++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddSupportForFrameworksPanel.java
@@ -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.
@@ -34,7 +34,6 @@ import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.DumbModePermission;
import com.intellij.openapi.project.DumbService;
-import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.roots.IdeaModifiableModelsProvider;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.roots.libraries.Library;
@@ -176,7 +175,7 @@ public class AddSupportForFrameworksPanel implements Disposable {
private static void addAssociatedFrameworkComponent(JPanel component, JPanel panel) {
panel.add(component, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 2, 1, 1.0, 0, GridBagConstraints.NORTHWEST,
- GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
+ GridBagConstraints.HORIZONTAL, JBUI.emptyInsets(), 0, 0));
}
protected void onFrameworkStateChanged() {}
diff --git a/java/idea-ui/src/com/intellij/ide/util/projectWizard/NamePathComponent.java b/java/idea-ui/src/com/intellij/ide/util/projectWizard/NamePathComponent.java
index 4541ba7b8693..a7d433a5fc87 100644
--- a/java/idea-ui/src/com/intellij/ide/util/projectWizard/NamePathComponent.java
+++ b/java/idea-ui/src/com/intellij/ide/util/projectWizard/NamePathComponent.java
@@ -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.
@@ -28,6 +28,7 @@ import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.FieldPanel;
+import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
@@ -91,11 +92,11 @@ public class NamePathComponent extends JPanel{
myNameLabel = new JLabel(nameLabelText);
if (bold) myNameLabel.setFont(UIUtil.getLabelFont().deriveFont(Font.BOLD));
myNameLabel.setLabelFor(myTfName);
- Insets insets = new Insets(0, 0, 5, 4);
+ Insets insets = JBUI.insets(0, 0, 5, 4);
this.add(myNameLabel, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
insets, 0, 0));
- insets = new Insets(0, 0, 5, 0);
+ insets = JBUI.insets(0, 0, 5, 0);
this.add(myTfName, new GridBagConstraints(1, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
insets, 0, 0));
// todo: review texts
@@ -111,10 +112,10 @@ public class NamePathComponent extends JPanel{
myPathLabel = new JLabel(pathLabelText);
myPathLabel.setLabelFor(myTfPath);
if (bold) myPathLabel.setFont(UIUtil.getLabelFont().deriveFont(Font.BOLD));
- insets = new Insets(0, 0, 5, 4);
+ insets = JBUI.insets(0, 0, 5, 4);
this.add(myPathLabel, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
insets, 0, 0));
- insets = new Insets(0, 0, 5, 0);
+ insets = JBUI.insets(0, 0, 5, 0);
this.add(myPathPanel, new GridBagConstraints(1, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
insets, 0, 0));
}
diff --git a/java/idea-ui/src/com/intellij/ide/util/projectWizard/ProjectNameStep.java b/java/idea-ui/src/com/intellij/ide/util/projectWizard/ProjectNameStep.java
index 398515f72b62..fea2114fc386 100644
--- a/java/idea-ui/src/com/intellij/ide/util/projectWizard/ProjectNameStep.java
+++ b/java/idea-ui/src/com/intellij/ide/util/projectWizard/ProjectNameStep.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,12 +19,12 @@ import com.intellij.ide.IdeBundle;
import com.intellij.ide.highlighter.ModuleFileType;
import com.intellij.ide.highlighter.ProjectFileType;
import com.intellij.openapi.application.ApplicationInfo;
-import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NonNls;
import javax.swing.*;
@@ -55,9 +55,9 @@ public class ProjectNameStep extends ModuleWizardStep {
ApplicationInfo info = ApplicationInfo.getInstance();
String appName = info.getVersionName();
myPanel.add(new JLabel(IdeBundle.message("label.please.enter.project.name", appName, wizardContext.getPresentationName())),
- new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(8, 10, 8, 10), 0, 0));
+ new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, JBUI.insets(8, 10), 0, 0));
- myPanel.add(myNamePathComponent, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(8, 10, 8, 10), 0, 0));
+ myPanel.add(myNamePathComponent, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, JBUI.insets(8, 10), 0, 0));
}
public JComponent getPreferredFocusedComponent() {
diff --git a/java/idea-ui/src/com/intellij/openapi/projectRoots/ui/SdkEditor.java b/java/idea-ui/src/com/intellij/openapi/projectRoots/ui/SdkEditor.java
index 17a52d249a70..978afd0fa1ac 100644
--- a/java/idea-ui/src/com/intellij/openapi/projectRoots/ui/SdkEditor.java
+++ b/java/idea-ui/src/com/intellij/openapi/projectRoots/ui/SdkEditor.java
@@ -32,7 +32,6 @@ import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.io.FileUtil;
-import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.TabbedPaneWrapper;
import com.intellij.ui.navigation.History;
@@ -152,8 +151,8 @@ public class SdkEditor implements Configurable, Place.Navigator {
myHomeComponent.getTextField().setEditable(false);
myHomeFieldLabel = new JLabel(getHomeFieldLabelValue());
- final int leftInset = Registry.is("ide.new.project.settings") ? 10 : 0;
- final int rightInset = Registry.is("ide.new.project.settings") ? 10 : 0;
+ final int leftInset = 10;
+ final int rightInset = 10;
myMainPanel.add(myHomeFieldLabel, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, leftInset, 2, 2), 0, 0));
myMainPanel.add(myHomeComponent, new GridBagConstraints(1, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, rightInset), 0, 0));
diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ClasspathEditor.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ClasspathEditor.java
index 44ddcce6ff65..9337892a9ba9 100644
--- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ClasspathEditor.java
+++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ClasspathEditor.java
@@ -30,6 +30,7 @@ import com.intellij.openapi.roots.impl.storage.ClasspathStorageProvider;
import com.intellij.openapi.roots.ui.configuration.classpath.ClasspathPanelImpl;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.util.Disposer;
+import com.intellij.util.ui.JBUI;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
@@ -163,7 +164,7 @@ public class ClasspathEditor extends ModuleElementsEditor implements ModuleRootL
super(new GridBagLayout());
add(new JLabel(ProjectBundle.message("project.roots.classpath.format.label")),
- new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(10, 6, 6, 0), 0, 0));
+ new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, JBUI.insets(10, 6, 6, 0), 0, 0));
formatIdToDescription.put(ClassPathStorageUtil.DEFAULT_STORAGE, ProjectBundle.message("project.roots.classpath.format.default.descr"));
for (ClasspathStorageProvider provider : providers) {
@@ -173,7 +174,7 @@ public class ClasspathEditor extends ModuleElementsEditor implements ModuleRootL
comboBoxClasspathFormat = new ComboBox(formatIdToDescription.values().toArray());
updateClasspathFormat();
add(comboBoxClasspathFormat,
- new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(6, 6, 6, 0), 0, 0));
+ new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, JBUI.insets(6, 6, 6, 0), 0, 0));
}
private void updateClasspathFormat() {
diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaContentEntriesEditor.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaContentEntriesEditor.java
index 1bb0d8d6911d..feaed160e646 100644
--- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaContentEntriesEditor.java
+++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaContentEntriesEditor.java
@@ -17,7 +17,6 @@ package com.intellij.openapi.roots.ui.configuration;
import com.intellij.ide.util.projectWizard.importSources.JavaModuleSourceRoot;
import com.intellij.ide.util.projectWizard.importSources.JavaSourceRootDetectionUtil;
-import com.intellij.openapi.module.Module;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.util.ProgressWindow;
@@ -26,7 +25,6 @@ import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.roots.ContentEntry;
import com.intellij.openapi.roots.ModifiableRootModel;
-import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
@@ -35,8 +33,6 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.java.JavaResourceRootType;
import org.jetbrains.jps.model.java.JavaSourceRootType;
-import javax.swing.*;
-import java.awt.*;
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
@@ -139,12 +135,4 @@ public class JavaContentEntriesEditor extends CommonContentEntriesEditor {
}
}.start();
}
-
- @Override
- protected JPanel createBottomControl(Module module) {
- if (Registry.is("ide.new.project.settings")) return null;
- final JPanel innerPanel = new JPanel(new GridBagLayout());
- innerPanel.setBorder(BorderFactory.createEmptyBorder(6, 0, 0, 6));
- return innerPanel;
- }
}
diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModuleEditor.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModuleEditor.java
index 6afc617e4120..0c6bdaefcd68 100644
--- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModuleEditor.java
+++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModuleEditor.java
@@ -39,7 +39,6 @@ import com.intellij.openapi.roots.impl.libraries.LibraryEx;
import com.intellij.openapi.roots.impl.libraries.LibraryTableBase;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
-import com.intellij.openapi.util.registry.Registry;
import com.intellij.ui.navigation.History;
import com.intellij.ui.navigation.Place;
import com.intellij.util.EventDispatcher;
@@ -261,11 +260,6 @@ public abstract class ModuleEditor implements Place.Navigator, Disposable {
createEditors(getModule());
- if (!Registry.is("ide.new.project.settings")) {
- JPanel northPanel = new JPanel(new GridBagLayout());
- myGenericSettingsPanel.add(northPanel, BorderLayout.NORTH);
- }
-
final JComponent component = createCenterPanel();
myGenericSettingsPanel.add(component, BorderLayout.CENTER);
myEditorsInitialized = true;
diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/OutputEditor.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/OutputEditor.java
index fe3ce1a82f7c..44d3fed6eb78 100644
--- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/OutputEditor.java
+++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/OutputEditor.java
@@ -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.
@@ -24,6 +24,7 @@ package com.intellij.openapi.roots.ui.configuration;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.ui.IdeBorderFactory;
+import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
@@ -49,7 +50,7 @@ public class OutputEditor extends ModuleElementsEditor {
final JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(new EmptyBorder(UIUtil.PANEL_SMALL_INSETS));
final GridBagConstraints gc =
- new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0);
+ new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, JBUI.emptyInsets(), 0, 0);
panel.add(myCompilerOutputEditor.createComponentImpl(), gc);
final JPanel javadocPanel = (JPanel)myJavadocEditor.createComponentImpl();
javadocPanel.setBorder(IdeBorderFactory.createTitledBorder(myJavadocEditor.getDisplayName(), false));
diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectConfigurable.java
index 3fe44c619516..3db5bf61e449 100644
--- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectConfigurable.java
+++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectConfigurable.java
@@ -44,7 +44,6 @@ import com.intellij.openapi.ui.DetailsComponent;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.EmptyRunnable;
import com.intellij.openapi.util.io.FileUtil;
-import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.pom.java.LanguageLevel;
@@ -118,7 +117,7 @@ public class ProjectConfigurable extends ProjectStructureElementConfigurable popupItems = new ArrayList();
for (AttachRootButtonDescriptor descriptor : myDescriptor.createAttachButtons()) {
Icon icon = descriptor.getToolbarIcon();
diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseStructureConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseStructureConfigurable.java
index 5bd87aaf27aa..723515e31591 100644
--- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseStructureConfigurable.java
+++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseStructureConfigurable.java
@@ -34,7 +34,6 @@ import com.intellij.openapi.ui.NamedConfigurable;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
-import com.intellij.openapi.util.registry.Registry;
import com.intellij.ui.TreeSpeedSearch;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.navigation.Place;
@@ -295,7 +294,7 @@ public abstract class BaseStructureConfigurable extends MasterDetailsComponent i
result.addAll(copyActions);
result.add(Separator.getInstance());
- if (fromPopup || !Registry.is("ide.new.project.settings")) {
+ if (fromPopup) {
result.add(new MyFindUsagesAction(myTree));
}
diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/FacetStructureConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/FacetStructureConfigurable.java
index a3539f7abfc0..b952f5a658c6 100644
--- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/FacetStructureConfigurable.java
+++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/FacetStructureConfigurable.java
@@ -35,7 +35,6 @@ import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.FacetProje
import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.ProjectStructureElement;
import com.intellij.openapi.ui.DetailsComponent;
import com.intellij.openapi.ui.NamedConfigurable;
-import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.treeStructure.filtered.FilteringTreeBuilder;
import com.intellij.util.ui.tree.TreeUtil;
@@ -276,7 +275,7 @@ public class FacetStructureConfigurable extends BaseStructureConfigurable {
actions.add(new MyNavigateAction());
}
actions.add(new MyRemoveAction());
- if (fromPopup || !(Registry.is("ide.new.project.settings"))) {
+ if (fromPopup) {
actions.add(Separator.getInstance());
addCollapseExpandActions(actions);
}
diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/ModuleStructureConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/ModuleStructureConfigurable.java
index 5418abf19f8c..2456fa472ef3 100644
--- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/ModuleStructureConfigurable.java
+++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/ModuleStructureConfigurable.java
@@ -52,7 +52,6 @@ import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.NullableComputable;
import com.intellij.openapi.util.io.FileUtil;
-import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
@@ -153,7 +152,7 @@ public class ModuleStructureConfigurable extends BaseStructureConfigurable imple
@NotNull
protected ArrayList createActions(final boolean fromPopup) {
final ArrayList result = super.createActions(fromPopup);
- if (fromPopup || !Registry.is("ide.new.project.settings")) {
+ if (fromPopup) {
result.add(Separator.getInstance());
result.add(new MyGroupAction());
addCollapseExpandActions(result);
diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/LibraryProjectStructureElement.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/LibraryProjectStructureElement.java
index 7af12e978190..6c65e099b582 100644
--- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/LibraryProjectStructureElement.java
+++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/LibraryProjectStructureElement.java
@@ -34,7 +34,6 @@ import com.intellij.openapi.roots.ui.configuration.projectRoot.LibraryConfigurab
import com.intellij.openapi.roots.ui.configuration.projectRoot.StructureConfigurableContext;
import com.intellij.openapi.ui.NamedConfigurable;
import com.intellij.openapi.util.ActionCallback;
-import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.PathUtil;
import com.intellij.xml.util.XmlStringUtil;
@@ -98,11 +97,7 @@ public class LibraryProjectStructureElement extends ProjectStructureElement {
StringBuilder buffer = new StringBuilder();
final String name = StringUtil.escapeXml(libraryName);
buffer.append("Library ");
- if (Registry.is("ide.new.project.settings")) {
- buffer.append("").append(name).append("");
- } else {
- buffer.append("'").append(name).append("'");
- }
+ buffer.append("").append(name).append("");
buffer.append(" has broken " + rootName + " " + StringUtil.pluralize("path", invalidClasses.size()) + ":");
for (String url : invalidClasses) {
buffer.append("
");
@@ -159,8 +154,7 @@ public class LibraryProjectStructureElement extends ProjectStructureElement {
public ProjectStructureProblemDescription createUnusedElementWarning() {
final List fixes = Arrays.asList(new AddLibraryToDependenciesFix(), new RemoveLibraryFix(), new RemoveAllUnusedLibrariesFix());
final String name = StringUtil.escapeXml(myLibrary.getName());
- String libraryName = Registry.is("ide.new.project.settings") ? "" + name + ""
- : "'" + name + "'";
+ String libraryName = "" + name + "";
return new ProjectStructureProblemDescription("Library " + libraryName + " is not used", null, createPlace(),
ProjectStructureProblemType.unused("unused-library"), ProjectStructureProblemDescription.ProblemLevel.PROJECT,
fixes, false);
diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/JavaHighlightInfoTypes.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/JavaHighlightInfoTypes.java
index 2558ccf43feb..a622e43c27e7 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/JavaHighlightInfoTypes.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/JavaHighlightInfoTypes.java
@@ -20,14 +20,57 @@ import com.intellij.codeInspection.unusedImport.UnusedImportLocalInspection;
import com.intellij.ide.highlighter.JavaHighlightingColors;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.editor.colors.CodeInsightColors;
+import com.intellij.openapi.editor.colors.TextAttributesKey;
+import org.jetbrains.annotations.NotNull;
-/**
- * @author anna
- * Date: 01-Feb-2008
- */
-public interface JavaHighlightInfoTypes {
- HighlightInfoType UNUSED_IMPORT = new HighlightInfoType.HighlightInfoTypeSeverityByKey(
+public final class JavaHighlightInfoTypes {
+ private JavaHighlightInfoTypes() {
+ }
+
+ public final static HighlightInfoType UNUSED_IMPORT = new HighlightInfoType.HighlightInfoTypeSeverityByKey(
HighlightDisplayKey.findOrRegister(UnusedImportLocalInspection.SHORT_NAME, UnusedImportLocalInspection.DISPLAY_NAME), CodeInsightColors.NOT_USED_ELEMENT_ATTRIBUTES);
- HighlightInfoType JAVA_KEYWORD = new HighlightInfoType.HighlightInfoTypeImpl(HighlightSeverity.INFORMATION, JavaHighlightingColors.KEYWORD);
+ public final static HighlightInfoType JAVA_KEYWORD = new HighlightInfoType.HighlightInfoTypeImpl(HighlightSeverity.INFORMATION, JavaHighlightingColors.KEYWORD);
+
+ public final static HighlightInfoType CLASS_NAME = createSymbolTypeInfo(JavaHighlightingColors.CLASS_NAME_ATTRIBUTES);
+ public final static HighlightInfoType LOCAL_VARIABLE = createSymbolTypeInfo(JavaHighlightingColors.LOCAL_VARIABLE_ATTRIBUTES);
+ public final static HighlightInfoType INSTANCE_FIELD = createSymbolTypeInfo(JavaHighlightingColors.INSTANCE_FIELD_ATTRIBUTES);
+ public final static HighlightInfoType INSTANCE_FINAL_FIELD = createSymbolTypeInfo(JavaHighlightingColors.INSTANCE_FINAL_FIELD_ATTRIBUTES);
+ public final static HighlightInfoType STATIC_FIELD = createSymbolTypeInfo(JavaHighlightingColors.STATIC_FIELD_ATTRIBUTES);
+ public final static HighlightInfoType STATIC_FINAL_FIELD = createSymbolTypeInfo(JavaHighlightingColors.STATIC_FINAL_FIELD_ATTRIBUTES);
+ public final static HighlightInfoType PARAMETER = createSymbolTypeInfo(JavaHighlightingColors.PARAMETER_ATTRIBUTES);
+ public final static HighlightInfoType METHOD_CALL = createSymbolTypeInfo(JavaHighlightingColors.METHOD_CALL_ATTRIBUTES);
+ public final static HighlightInfoType METHOD_DECLARATION = createSymbolTypeInfo(JavaHighlightingColors.METHOD_DECLARATION_ATTRIBUTES);
+ public final static HighlightInfoType CONSTRUCTOR_CALL = createSymbolTypeInfo(JavaHighlightingColors.CONSTRUCTOR_CALL_ATTRIBUTES);
+ public final static HighlightInfoType CONSTRUCTOR_DECLARATION = createSymbolTypeInfo(JavaHighlightingColors.CONSTRUCTOR_DECLARATION_ATTRIBUTES);
+ public final static HighlightInfoType STATIC_METHOD = createSymbolTypeInfo(JavaHighlightingColors.STATIC_METHOD_ATTRIBUTES);
+ public final static HighlightInfoType ABSTRACT_METHOD = createSymbolTypeInfo(JavaHighlightingColors.ABSTRACT_METHOD_ATTRIBUTES);
+ public final static HighlightInfoType INHERITED_METHOD = createSymbolTypeInfo(JavaHighlightingColors.INHERITED_METHOD_ATTRIBUTES);
+ public final static HighlightInfoType ANONYMOUS_CLASS_NAME = createSymbolTypeInfo(JavaHighlightingColors.ANONYMOUS_CLASS_NAME_ATTRIBUTES);
+ public final static HighlightInfoType INTERFACE_NAME = createSymbolTypeInfo(JavaHighlightingColors.INTERFACE_NAME_ATTRIBUTES);
+ public final static HighlightInfoType ENUM_NAME = createSymbolTypeInfo(JavaHighlightingColors.ENUM_NAME_ATTRIBUTES);
+ public final static HighlightInfoType TYPE_PARAMETER_NAME
+ = new HighlightInfoType.HighlightInfoTypeImpl(HighlightInfoType.SYMBOL_TYPE_SEVERITY,
+ JavaHighlightingColors.TYPE_PARAMETER_NAME_ATTRIBUTES);
+ public final static HighlightInfoType ABSTRACT_CLASS_NAME = createSymbolTypeInfo(JavaHighlightingColors.ABSTRACT_CLASS_NAME_ATTRIBUTES);
+ public final static HighlightInfoType ANNOTATION_NAME
+ = new HighlightInfoType.HighlightInfoTypeImpl(HighlightInfoType.SYMBOL_TYPE_SEVERITY,
+ JavaHighlightingColors.ANNOTATION_NAME_ATTRIBUTES);
+ public final static HighlightInfoType ANNOTATION_ATTRIBUTE_NAME
+ = new HighlightInfoType.HighlightInfoTypeImpl(HighlightInfoType.SYMBOL_TYPE_SEVERITY,
+ JavaHighlightingColors.ANNOTATION_ATTRIBUTE_NAME_ATTRIBUTES);
+ public final static HighlightInfoType REASSIGNED_LOCAL_VARIABLE
+ = new HighlightInfoType.HighlightInfoTypeImpl(HighlightInfoType.SYMBOL_TYPE_SEVERITY,
+ JavaHighlightingColors.REASSIGNED_LOCAL_VARIABLE_ATTRIBUTES);
+ public final static HighlightInfoType REASSIGNED_PARAMETER
+ = new HighlightInfoType.HighlightInfoTypeImpl(HighlightInfoType.SYMBOL_TYPE_SEVERITY,
+ JavaHighlightingColors.REASSIGNED_PARAMETER_ATTRIBUTES);
+ public final static HighlightInfoType IMPLICIT_ANONYMOUS_CLASS_PARAMETER
+ = new HighlightInfoType.HighlightInfoTypeImpl(HighlightInfoType.SYMBOL_TYPE_SEVERITY,
+ JavaHighlightingColors.IMPLICIT_ANONYMOUS_CLASS_PARAMETER_ATTRIBUTES);
+
+ private static HighlightInfoType createSymbolTypeInfo(@NotNull TextAttributesKey attributesKey) {
+ return new HighlightInfoType.HighlightInfoTypeImpl(HighlightInfoType.SYMBOL_TYPE_SEVERITY, attributesKey, false);
+ }
+
}
diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java
index c36dcd195ac9..bcd2424fb754 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java
@@ -168,10 +168,12 @@ public class HighlightMethodUtil {
@NotNull TextRange range,
@NotNull LanguageLevel languageLevel) {
if (superReturnType == null) return null;
- if ("clone".equals(method.getName())) {
+ final PsiClass superContainingClass = superMethod.getContainingClass();
+ if (superContainingClass != null &&
+ CommonClassNames.JAVA_LANG_OBJECT.equals(superContainingClass.getQualifiedName()) &&
+ !superMethod.hasModifierProperty(PsiModifier.PUBLIC)) {
final PsiClass containingClass = method.getContainingClass();
- final PsiClass superContainingClass = superMethod.getContainingClass();
- if (containingClass != null && superContainingClass != null && containingClass.isInterface() && !superContainingClass.isInterface()) {
+ if (containingClass != null && containingClass.isInterface() && !superContainingClass.isInterface()) {
return null;
}
}
@@ -805,7 +807,7 @@ public class HighlightMethodUtil {
@Language("HTML")
@NonNls String parensizedName = methodName + (parameters.length == 0 ? "( ) " : "");
- final String errorMessage = info != null ? info.getInferenceErrorMessage() : null;
+ String errorMessage = info != null ? info.getParentInferenceErrorMessage(list) : null;
return JavaErrorMessages.message(
"argument.mismatch.html.tooltip",
Integer.valueOf(cols - parameters.length + 1), parensizedName,
@@ -917,7 +919,7 @@ public class HighlightMethodUtil {
}
s+= "";
- final String errorMessage = info != null ? info.getInferenceErrorMessage() : null;
+ final String errorMessage = info != null ? info.getParentInferenceErrorMessage(list) : null;
if (errorMessage != null) {
s+= "reason: ";
s += XmlStringUtil.escapeString(errorMessage).replaceAll("\n", "
");
diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightNamesUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightNamesUtil.java
index eb085f3649eb..7d8fc50db7a1 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightNamesUtil.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightNamesUtil.java
@@ -22,6 +22,7 @@ package com.intellij.codeInsight.daemon.impl.analysis;
import com.intellij.application.options.colors.ScopeAttributesUtil;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
+import com.intellij.codeInsight.daemon.impl.JavaHighlightInfoTypes;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.TextAttributesKey;
@@ -171,32 +172,32 @@ public class HighlightNamesUtil {
private static HighlightInfoType getMethodNameHighlightType(@NotNull PsiMethod method, boolean isDeclaration, boolean isInheritedMethod) {
if (method.isConstructor()) {
- return isDeclaration ? HighlightInfoType.CONSTRUCTOR_DECLARATION : HighlightInfoType.CONSTRUCTOR_CALL;
+ return isDeclaration ? JavaHighlightInfoTypes.CONSTRUCTOR_DECLARATION : JavaHighlightInfoTypes.CONSTRUCTOR_CALL;
}
- if (isDeclaration) return HighlightInfoType.METHOD_DECLARATION;
+ if (isDeclaration) return JavaHighlightInfoTypes.METHOD_DECLARATION;
if (method.hasModifierProperty(PsiModifier.STATIC)) {
- return HighlightInfoType.STATIC_METHOD;
+ return JavaHighlightInfoTypes.STATIC_METHOD;
}
- if (isInheritedMethod) return HighlightInfoType.INHERITED_METHOD;
+ if (isInheritedMethod) return JavaHighlightInfoTypes.INHERITED_METHOD;
if(method.hasModifierProperty(PsiModifier.ABSTRACT)) {
- return HighlightInfoType.ABSTRACT_METHOD;
+ return JavaHighlightInfoTypes.ABSTRACT_METHOD;
}
- return HighlightInfoType.METHOD_CALL;
+ return JavaHighlightInfoTypes.METHOD_CALL;
}
@Nullable
private static HighlightInfoType getVariableNameHighlightType(PsiVariable var) {
if (var instanceof PsiLocalVariable
|| var instanceof PsiParameter && ((PsiParameter)var).getDeclarationScope() instanceof PsiForeachStatement) {
- return HighlightInfoType.LOCAL_VARIABLE;
+ return JavaHighlightInfoTypes.LOCAL_VARIABLE;
}
if (var instanceof PsiField) {
return var.hasModifierProperty(PsiModifier.STATIC)
- ? var.hasModifierProperty(PsiModifier.FINAL) ? HighlightInfoType.STATIC_FINAL_FIELD : HighlightInfoType.STATIC_FIELD
- : var.hasModifierProperty(PsiModifier.FINAL) ? HighlightInfoType.INSTANCE_FINAL_FIELD : HighlightInfoType.INSTANCE_FIELD;
+ ? var.hasModifierProperty(PsiModifier.FINAL) ? JavaHighlightInfoTypes.STATIC_FINAL_FIELD : JavaHighlightInfoTypes.STATIC_FIELD
+ : var.hasModifierProperty(PsiModifier.FINAL) ? JavaHighlightInfoTypes.INSTANCE_FINAL_FIELD : JavaHighlightInfoTypes.INSTANCE_FIELD;
}
if (var instanceof PsiParameter) {
- return HighlightInfoType.PARAMETER;
+ return JavaHighlightInfoTypes.PARAMETER;
}
return null;
}
@@ -204,27 +205,27 @@ public class HighlightNamesUtil {
@NotNull
private static HighlightInfoType getClassNameHighlightType(@Nullable PsiClass aClass, @Nullable PsiElement element) {
if (element instanceof PsiJavaCodeReferenceElement && element.getParent() instanceof PsiAnonymousClass) {
- return HighlightInfoType.ANONYMOUS_CLASS_NAME;
+ return JavaHighlightInfoTypes.ANONYMOUS_CLASS_NAME;
}
if (aClass != null) {
- if (aClass.isAnnotationType()) return HighlightInfoType.ANNOTATION_NAME;
- if (aClass.isInterface()) return HighlightInfoType.INTERFACE_NAME;
- if (aClass.isEnum()) return HighlightInfoType.ENUM_NAME;
- if (aClass instanceof PsiTypeParameter) return HighlightInfoType.TYPE_PARAMETER_NAME;
+ if (aClass.isAnnotationType()) return JavaHighlightInfoTypes.ANNOTATION_NAME;
+ if (aClass.isInterface()) return JavaHighlightInfoTypes.INTERFACE_NAME;
+ if (aClass.isEnum()) return JavaHighlightInfoTypes.ENUM_NAME;
+ if (aClass instanceof PsiTypeParameter) return JavaHighlightInfoTypes.TYPE_PARAMETER_NAME;
final PsiModifierList modList = aClass.getModifierList();
- if (modList != null && modList.hasModifierProperty(PsiModifier.ABSTRACT)) return HighlightInfoType.ABSTRACT_CLASS_NAME;
+ if (modList != null && modList.hasModifierProperty(PsiModifier.ABSTRACT)) return JavaHighlightInfoTypes.ABSTRACT_CLASS_NAME;
}
// use class by default
- return HighlightInfoType.CLASS_NAME;
+ return JavaHighlightInfoTypes.CLASS_NAME;
}
@Nullable
static HighlightInfo highlightReassignedVariable(PsiVariable variable, PsiElement elementToHighlight) {
if (variable instanceof PsiLocalVariable) {
- return HighlightInfo.newHighlightInfo(HighlightInfoType.REASSIGNED_LOCAL_VARIABLE).range(elementToHighlight).create();
+ return HighlightInfo.newHighlightInfo(JavaHighlightInfoTypes.REASSIGNED_LOCAL_VARIABLE).range(elementToHighlight).create();
}
if (variable instanceof PsiParameter) {
- return HighlightInfo.newHighlightInfo(HighlightInfoType.REASSIGNED_PARAMETER).range(elementToHighlight).create();
+ return HighlightInfo.newHighlightInfo(JavaHighlightInfoTypes.REASSIGNED_PARAMETER).range(elementToHighlight).create();
}
return null;
}
diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java
index fb3b83379666..fdcd49003c0b 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java
@@ -60,7 +60,10 @@ import com.intellij.util.ui.UIUtil;
import com.intellij.xml.util.XmlStringUtil;
import gnu.trove.THashMap;
import org.intellij.lang.annotations.Language;
-import org.jetbrains.annotations.*;
+import org.jetbrains.annotations.NonNls;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.annotations.PropertyKey;
import java.util.*;
import java.util.regex.Matcher;
@@ -1548,12 +1551,25 @@ public class HighlightUtil extends HighlightUtilBase {
//or if there exists some other direct superclass or direct superinterface of T, J, such that J is a subtype of I.
final PsiClass classT = PsiTreeUtil.getParentOfType(expr, PsiClass.class);
if (classT != null) {
+ final PsiElement parent = expr.getParent();
+ final PsiElement resolved = parent instanceof PsiReferenceExpression ? ((PsiReferenceExpression)parent).resolve() : null;
+
for (PsiClass superClass : classT.getSupers()) {
- if (superClass.isInterface() && //check spec-javac relations
- superClass.isInheritor(aClass, true)) {
- return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
- .range(qualifier)
- .descriptionAndTooltip(JavaErrorMessages.message("bad.qualifier.in.super.method.reference", format(aClass), formatClass(superClass))).create();
+ if (superClass.isInheritor(aClass, true)) {
+ String cause = null;
+ if (superClass.isInterface()) {
+ cause = "redundant interface " + format(aClass) + " is extended by ";
+ }
+ else if (resolved instanceof PsiMethod &&
+ MethodSignatureUtil.findMethodBySuperMethod(superClass, (PsiMethod)resolved, true) != resolved) {
+ cause = "method " + ((PsiMethod)resolved).getName() + " is overridden in ";
+ }
+
+ if (cause != null) {
+ return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
+ .range(qualifier)
+ .descriptionAndTooltip(JavaErrorMessages.message("bad.qualifier.in.super.method.reference", cause + formatClass(superClass))).create();
+ }
}
}
diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java
index 68710e22e50e..5d06fd83968a 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java
@@ -325,8 +325,13 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
final PsiCallExpression callExpression = parent instanceof PsiExpressionList && parent.getParent() instanceof PsiCallExpression ?
(PsiCallExpression)parent.getParent() : null;
final JavaResolveResult containingCallResolveResult = callExpression != null ? callExpression.resolveMethodGenerics() : null;
- final String errorMessage = containingCallResolveResult instanceof MethodCandidateInfo ?
- ((MethodCandidateInfo)containingCallResolveResult).getInferenceErrorMessage() : null;
+ final String errorMessage;
+ if (containingCallResolveResult instanceof MethodCandidateInfo) {
+ errorMessage = ((MethodCandidateInfo)containingCallResolveResult).getParentInferenceErrorMessage((PsiExpressionList)parent);
+ }
+ else {
+ errorMessage = null;
+ }
if (errorMessage != null) {
HighlightInfo result = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
.range(expression).descriptionAndTooltip(errorMessage).create();
@@ -926,7 +931,7 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
if (!myHolder.hasErrorResults()) {
PsiIdentifier nameId = pair.getNameIdentifier();
if (nameId != null) {
- HighlightInfo result = HighlightInfo.newHighlightInfo(HighlightInfoType.ANNOTATION_ATTRIBUTE_NAME).range(nameId).create();
+ HighlightInfo result = HighlightInfo.newHighlightInfo(JavaHighlightInfoTypes.ANNOTATION_ATTRIBUTE_NAME).range(nameId).create();
myHolder.add(result);
}
}
@@ -1080,7 +1085,7 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
!PsiTreeUtil.isAncestor(containingClass, variable, false) &&
!(variable instanceof PsiField)) {
if (!PsiTreeUtil.isAncestor(((PsiAnonymousClass) containingClass).getArgumentList(), ref, false)) {
- myHolder.add(HighlightInfo.newHighlightInfo(HighlightInfoType.IMPLICIT_ANONYMOUS_CLASS_PARAMETER).range(ref).create());
+ myHolder.add(HighlightInfo.newHighlightInfo(JavaHighlightInfoTypes.IMPLICIT_ANONYMOUS_CLASS_PARAMETER).range(ref).create());
}
}
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/AnonymousCanBeLambdaInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/AnonymousCanBeLambdaInspection.java
index 808af618006b..15787fbaca3b 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/AnonymousCanBeLambdaInspection.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/AnonymousCanBeLambdaInspection.java
@@ -134,7 +134,7 @@ public class AnonymousCanBeLambdaInspection extends BaseJavaBatchLocalInspection
return checker.hasForbiddenRefs();
}
- private static PsiType getInferredType(PsiAnonymousClass aClass) {
+ private static PsiType getInferredType(PsiAnonymousClass aClass, PsiMethod method) {
final PsiExpression expression = (PsiExpression)aClass.getParent();
final PsiType psiType = PsiTypesUtil.getExpectedTypeByParent(expression);
if (psiType != null) {
@@ -151,35 +151,18 @@ public class AnonymousCanBeLambdaInspection extends BaseJavaBatchLocalInspection
PsiExpressionList expressionList = (PsiExpressionList)parent;
final PsiElement callExpr = expressionList.getParent();
if (callExpr instanceof PsiCallExpression) {
- final JavaResolveResult result = ((PsiCallExpression)callExpr).resolveMethodGenerics();
- if (result instanceof MethodCandidateInfo) {
- final PsiMethod method = ((MethodCandidateInfo)result).getElement();
- PsiExpression[] expressions = expressionList.getExpressions();
- int i = ArrayUtilRt.find(expressions, topExpr);
- if (i < 0) return null;
- expressions[i] = null;
-
- final PsiParameter[] parameters = method.getParameterList().getParameters();
- final PsiSubstitutor substitutor = PsiResolveHelper.SERVICE.getInstance(aClass.getProject())
- .inferTypeArguments(method.getTypeParameters(), parameters, expressions,
- ((MethodCandidateInfo)result).getSiteSubstitutor(), callExpr.getParent(),
- DefaultParameterTypeInferencePolicy.INSTANCE);
- PsiType paramType;
- if (i < parameters.length) {
- paramType = parameters[i].getType();
- }
- else if (parameters.length > 0) {
- paramType = parameters[parameters.length - 1].getType();
- if (!(paramType instanceof PsiEllipsisType)) {
- return null;
- }
- paramType = ((PsiEllipsisType)paramType).getComponentType();
- }
- else {
- return null;
- }
-
- return substitutor.substitute(paramType);
+ PsiExpression[] expressions = expressionList.getExpressions();
+ int i = ArrayUtilRt.find(expressions, topExpr);
+ if (i < 0) return null;
+ final PsiCallExpression copy = (PsiCallExpression)callExpr.copy();
+ final PsiExpressionList argumentList = copy.getArgumentList();
+ if (argumentList != null) {
+ final PsiExpression classArg = argumentList.getExpressions()[i];
+ PsiExpression lambda = JavaPsiFacade.getElementFactory(aClass.getProject())
+ .createExpressionFromText(ReplaceWithLambdaFix.composeLambdaText(method), expression);
+ lambda = (PsiExpression)classArg.replace(lambda);
+ ((PsiLambdaExpression)lambda).getBody().replace(method.getBody());
+ return LambdaUtil.getFunctionalInterfaceType(lambda, true);
}
}
}
@@ -224,7 +207,6 @@ public class AnonymousCanBeLambdaInspection extends BaseJavaBatchLocalInspection
if (anonymousClass == null) return null;
ChangeContextUtil.encodeContextInfo(anonymousClass, true);
- final PsiElement lambdaContext = anonymousClass.getParent().getParent();
final String canonicalText = anonymousClass.getBaseClassType().getCanonicalText();
final PsiMethod method;
@@ -438,7 +420,7 @@ public class AnonymousCanBeLambdaInspection extends BaseJavaBatchLocalInspection
PsiAnonymousClass aClass) {
myMethod = method;
myAnonymClass = aClass;
- final PsiType inferredType = FunctionalInterfaceParameterizationUtil.getGroundTargetType(getInferredType(aClass));
+ final PsiType inferredType = FunctionalInterfaceParameterizationUtil.getGroundTargetType(getInferredType(aClass, method));
final PsiClassType baseClassType = aClass.getBaseClassType();
myInferredType = !baseClassType.equals(inferredType) ? inferredType : null;
}
@@ -511,6 +493,7 @@ public class AnonymousCanBeLambdaInspection extends BaseJavaBatchLocalInspection
final PsiElement resolved = expression.resolve();
if (resolved instanceof PsiField &&
((PsiField)resolved).hasModifierProperty(PsiModifier.FINAL) &&
+ ((PsiField)resolved).getInitializer() == null &&
((PsiField)resolved).getContainingClass() == method.getContainingClass()) {
try {
final PsiCodeBlock constructorBody = method.getBody();
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/StreamApiMigrationInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/StreamApiMigrationInspection.java
index 49d6839f5b25..e6851105c7ae 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/StreamApiMigrationInspection.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/StreamApiMigrationInspection.java
@@ -126,12 +126,16 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
if (ExceptionUtil.getThrownCheckedExceptions(new PsiElement[] {body}).isEmpty()) {
if (!(iteratedValueType instanceof PsiClassType && ((PsiClassType)iteratedValueType).isRaw()) &&
isCollectCall(body, statement.getIterationParameter())) {
- holder.registerProblem(iteratedValue, "Can be replaced with collect call",
- ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new ReplaceWithCollectCallFix());
+ boolean addAll = isAddAllCall(statement, body);
+ holder.registerProblem(iteratedValue, "Can be replaced with " + (addAll ? "addAll call" : "collect call"),
+ ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
+ new ReplaceWithCollectCallFix("Replace with " + (addAll ? "addAll" : "collect")));
}
else if (REPLACE_TRIVIAL_FOREACH || !isTrivial(body, statement.getIterationParameter())) {
holder.registerProblem(iteratedValue, "Can be replaced with foreach call",
- ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new ReplaceWithForeachCallFix());
+ ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
+ new ReplaceWithForeachCallFix("forEach"),
+ new ReplaceWithForeachCallFix("forEachOrdered"));
}
}
}
@@ -145,6 +149,17 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
};
}
+ private static boolean isAddAllCall(PsiForeachStatement statement, PsiStatement body) {
+ final PsiIfStatement ifStatement = extractIfStatement(body);
+ if (ifStatement == null) {
+ final PsiParameter parameter = statement.getIterationParameter();
+ final PsiMethodCallExpression methodCallExpression = extractAddCall(body, null);
+ LOG.assertTrue(methodCallExpression != null);
+ return isIdentityMapping(parameter, methodCallExpression.getArgumentList().getExpressions()[0]);
+ }
+ return false;
+ }
+
private static boolean isCollectCall(PsiStatement body, final PsiParameter parameter) {
PsiIfStatement ifStatement = extractIfStatement(body);
final PsiMethodCallExpression methodCallExpression = extractAddCall(body, ifStatement);
@@ -265,7 +280,17 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
}) != null;
}
+ private static boolean isIdentityMapping(PsiParameter parameter, PsiExpression mapperCall) {
+ return mapperCall instanceof PsiReferenceExpression && ((PsiReferenceExpression)mapperCall).resolve() == parameter;
+ }
+
private static class ReplaceWithForeachCallFix implements LocalQuickFix {
+ private final String myForEachMethodName;
+
+ private ReplaceWithForeachCallFix(String forEachMethodName) {
+ myForEachMethodName = forEachMethodName;
+ }
+
@NotNull
@Override
public String getName() {
@@ -275,7 +300,7 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
@NotNull
@Override
public String getFamilyName() {
- return "Replace with forEach";
+ return "Replace with " + myForEachMethodName;
}
@Override
@@ -300,7 +325,7 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
body = thenBranch;
}
- buffer.append(".forEach(");
+ buffer.append("." + myForEachMethodName + "(");
final String functionalExpressionText = createForEachFunctionalExpressionText(project, body, parameter);
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
@@ -360,6 +385,13 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
}
private static class ReplaceWithCollectCallFix implements LocalQuickFix {
+
+ private final String myName;
+
+ public ReplaceWithCollectCallFix(String name) {
+ myName = name;
+ }
+
@NotNull
@Override
public String getName() {
@@ -369,7 +401,7 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
@NotNull
@Override
public String getFamilyName() {
- return "Replace with collect";
+ return myName;
}
@Override
@@ -377,15 +409,27 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
final PsiForeachStatement foreachStatement = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiForeachStatement.class);
if (foreachStatement != null) {
if (!FileModificationService.getInstance().preparePsiElementForWrite(foreachStatement)) return;
+ final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
PsiStatement body = foreachStatement.getBody();
final PsiExpression iteratedValue = foreachStatement.getIteratedValue();
if (body != null && iteratedValue != null) {
final PsiParameter parameter = foreachStatement.getIterationParameter();
- final StringBuilder builder = new StringBuilder(getIteratedValueText(iteratedValue) + ".stream()");
-
final PsiIfStatement ifStatement = extractIfStatement(body);
final PsiMethodCallExpression methodCallExpression = extractAddCall(body, ifStatement);
+ if (methodCallExpression == null) return;
+
+ if (isAddAllCall(foreachStatement, body)) {
+ restoreComments(foreachStatement, body);
+ final PsiExpression qualifierExpression = methodCallExpression.getMethodExpression().getQualifierExpression();
+ final String qualifierText = qualifierExpression != null ? qualifierExpression.getText() : "";
+ final String callText = StringUtil.getQualifiedName(qualifierText, "addAll(" + getIteratedValueText(iteratedValue) + ");");
+ PsiElement result = foreachStatement.replace(elementFactory.createStatementFromText(callText, foreachStatement));
+ reformatWhenNeeded(project, result);
+ return;
+ }
+ final StringBuilder builder = new StringBuilder(getIteratedValueText(iteratedValue) + ".stream()");
+
builder.append(createFiltersChainText(body, parameter, ifStatement));
builder.append(createMapperFunctionalExpressionText(project, parameter, methodCallExpression.getArgumentList().getExpressions()[0]));
@@ -393,7 +437,6 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
PsiElement result = null;
try {
final PsiExpression qualifierExpression = methodCallExpression.getMethodExpression().getQualifierExpression();
- final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
if (qualifierExpression instanceof PsiReferenceExpression) {
final PsiElement resolve = ((PsiReferenceExpression)qualifierExpression).resolve();
if (resolve instanceof PsiVariable) {
@@ -420,14 +463,18 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
simplifyRedundantCast(result);
}
finally {
- if (result != null) {
- CodeStyleManager.getInstance(project).reformat(JavaCodeStyleManager.getInstance(project).shortenClassReferences(result));
- }
+ reformatWhenNeeded(project, result);
}
}
}
}
+ private static void reformatWhenNeeded(@NotNull Project project, PsiElement result) {
+ if (result != null) {
+ CodeStyleManager.getInstance(project).reformat(JavaCodeStyleManager.getInstance(project).shortenClassReferences(result));
+ }
+ }
+
private static String createInitializerReplacementText(PsiType varType, PsiExpression initializer) {
final PsiType initializerType = initializer.getType();
final PsiClassType rawType = initializerType instanceof PsiClassType ? ((PsiClassType)initializerType).rawType() : null;
@@ -470,10 +517,6 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
}
return iteration;
}
-
- private static boolean isIdentityMapping(PsiParameter parameter, PsiExpression mapperCall) {
- return mapperCall instanceof PsiReferenceExpression && ((PsiReferenceExpression)mapperCall).resolve() == parameter;
- }
}
private static void simplifyRedundantCast(PsiElement result) {
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/BytecodeAnalysisConverter.java b/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/BytecodeAnalysisConverter.java
index 7a59184693d5..bfb6b42a82e2 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/BytecodeAnalysisConverter.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/BytecodeAnalysisConverter.java
@@ -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.
@@ -18,6 +18,7 @@ package com.intellij.codeInspection.bytecodeAnalysis;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.ThreadLocalCachedValue;
import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.TypeConversionUtil;
@@ -28,8 +29,8 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
-import static com.intellij.codeInspection.bytecodeAnalysis.ProjectBytecodeAnalysis.LOG;
import static com.intellij.codeInspection.bytecodeAnalysis.Direction.*;
+import static com.intellij.codeInspection.bytecodeAnalysis.ProjectBytecodeAnalysis.LOG;
/**
* @author lambdamix
@@ -121,9 +122,9 @@ public class BytecodeAnalysisConverter {
*/
@NotNull
public static HKey asmKey(@NotNull Key key, @NotNull MessageDigest md) {
- byte[] classDigest = md.digest(key.method.internalClassName.getBytes());
- md.update(key.method.methodName.getBytes());
- md.update(key.method.methodDesc.getBytes());
+ byte[] classDigest = md.digest(key.method.internalClassName.getBytes(CharsetToolkit.UTF8_CHARSET));
+ md.update(key.method.methodName.getBytes(CharsetToolkit.UTF8_CHARSET));
+ md.update(key.method.methodDesc.getBytes(CharsetToolkit.UTF8_CHARSET));
byte[] sigDigest = md.digest();
byte[] digest = new byte[HASH_SIZE];
System.arraycopy(classDigest, 0, digest, 0, CLASS_HASH_SIZE);
@@ -161,7 +162,7 @@ public class BytecodeAnalysisConverter {
if (descriptor == null) {
return null;
}
- return md.digest(descriptor.getBytes());
+ return md.digest(descriptor.getBytes(CharsetToolkit.UTF8_CHARSET));
}
@Nullable
@@ -170,7 +171,7 @@ public class BytecodeAnalysisConverter {
if (descriptor == null) {
return null;
}
- return md.digest(descriptor.getBytes());
+ return md.digest(descriptor.getBytes(CharsetToolkit.UTF8_CHARSET));
}
@Nullable
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/concurrencyAnnotations/FieldAccessNotGuardedInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/concurrencyAnnotations/FieldAccessNotGuardedInspection.java
index 258634479f9b..18c2af6681c9 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/concurrencyAnnotations/FieldAccessNotGuardedInspection.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/concurrencyAnnotations/FieldAccessNotGuardedInspection.java
@@ -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.
@@ -62,7 +62,7 @@ public class FieldAccessNotGuardedInspection extends BaseJavaBatchLocalInspectio
@Override
public void visitReferenceExpression(PsiReferenceExpression expression) {
final PsiElement referent = expression.resolve();
- if (referent == null || !(referent instanceof PsiField)) {
+ if (!(referent instanceof PsiField)) {
return;
}
final PsiField field = (PsiField)referent;
@@ -132,7 +132,7 @@ public class FieldAccessNotGuardedInspection extends BaseJavaBatchLocalInspectio
}
tryStatement = PsiTreeUtil.getParentOfType(tryStatement, PsiTryStatement.class);
}
- return tryStatement;
+ return null;
}
private static boolean isLockGuardStatement(String guard, PsiElement element, final String lockMethodStart) {
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java
index 6880a6645710..d702d17b74fa 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java
@@ -1667,7 +1667,7 @@ public class ControlFlowAnalyzer extends JavaElementVisitor {
}
private void flushIncrementedValue(@Nullable PsiExpression operand) {
- if (operand instanceof PsiReferenceExpression) {
+ if (operand instanceof PsiReferenceExpression && PsiUtil.isAccessedForWriting(operand)) {
PsiVariable psiVariable = DfaValueFactory.resolveUnqualifiedVariable((PsiReferenceExpression)operand);
if (psiVariable != null) {
DfaVariableValue dfaVariable = myFactory.getVarFactory().createVariableValue(psiVariable, false);
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java
index 15e6d6b2e4c0..add2fbeced8d 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java
@@ -435,9 +435,12 @@ public class DataFlowInspectionBase extends BaseJavaBatchLocalInspectionTool {
}
private void reportCallMayProduceNpe(ProblemsHolder holder, PsiMethodCallExpression callExpression, boolean onTheFly) {
- LocalQuickFix[] fix = createNPEFixes(callExpression.getMethodExpression().getQualifierExpression(), callExpression, onTheFly);
+ PsiReferenceExpression methodExpression = callExpression.getMethodExpression();
+ LocalQuickFix[] fix = createNPEFixes(methodExpression.getQualifierExpression(), callExpression, onTheFly);
- holder.registerProblem(callExpression,
+ PsiElement toHighlight = methodExpression.getReferenceNameElement();
+ if (toHighlight == null) toHighlight = methodExpression;
+ holder.registerProblem(toHighlight,
InspectionsBundle.message("dataflow.message.npe.method.invocation"),
fix);
}
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/value/DfaExpressionFactory.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/value/DfaExpressionFactory.java
index fa391bc53d6c..73bf18d3ff7e 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/value/DfaExpressionFactory.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/value/DfaExpressionFactory.java
@@ -131,7 +131,7 @@ public class DfaExpressionFactory {
}
if (!var.hasModifierProperty(PsiModifier.VOLATILE)) {
- if (var instanceof PsiVariable && var.hasModifierProperty(PsiModifier.FINAL)) {
+ if (var instanceof PsiVariable && var.hasModifierProperty(PsiModifier.FINAL) && !PsiUtil.isAccessedForWriting(refExpr)) {
DfaValue constValue = myFactory.getConstFactory().create((PsiVariable)var);
if (constValue != null) return constValue;
}
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/sillyAssignment/SillyAssignmentInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/sillyAssignment/SillyAssignmentInspectionBase.java
index 55ddb1fdd1c8..fa4aaa4eb136 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/sillyAssignment/SillyAssignmentInspectionBase.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/sillyAssignment/SillyAssignmentInspectionBase.java
@@ -101,8 +101,9 @@ public class SillyAssignmentInspectionBase extends BaseJavaBatchLocalInspectionT
lExpression = PsiUtil.deparenthesizeExpression(lExpression);
if (!(lExpression instanceof PsiReferenceExpression)) return;
PsiReferenceExpression lRef = (PsiReferenceExpression)lExpression;
- final PsiVariable variable = (PsiVariable)lRef.resolve();
- if (variable == null) return;
+ final PsiElement resolved = lRef.resolve();
+ if (!(resolved instanceof PsiVariable)) return;
+ final PsiVariable variable = (PsiVariable)resolved;
rExpression = deparenthesizeRExpr(rExpression, variable);
diff --git a/java/java-analysis-impl/src/com/intellij/ide/highlighter/JavaHighlightingColors.java b/java/java-analysis-impl/src/com/intellij/ide/highlighter/JavaHighlightingColors.java
index cf309a2811db..c7dddf8ca015 100644
--- a/java/java-analysis-impl/src/com/intellij/ide/highlighter/JavaHighlightingColors.java
+++ b/java/java-analysis-impl/src/com/intellij/ide/highlighter/JavaHighlightingColors.java
@@ -16,7 +16,6 @@
package com.intellij.ide.highlighter;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
-import com.intellij.openapi.editor.SyntaxHighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
/**
@@ -24,25 +23,92 @@ import com.intellij.openapi.editor.colors.TextAttributesKey;
*
* @author Rustam Vishnyakov
*/
-@SuppressWarnings("deprecation")
public class JavaHighlightingColors {
- public static final TextAttributesKey LINE_COMMENT = SyntaxHighlighterColors.LINE_COMMENT;
- public static final TextAttributesKey JAVA_BLOCK_COMMENT = SyntaxHighlighterColors.JAVA_BLOCK_COMMENT;
- public static final TextAttributesKey DOC_COMMENT = SyntaxHighlighterColors.DOC_COMMENT;
- public static final TextAttributesKey KEYWORD = SyntaxHighlighterColors.KEYWORD;
- public static final TextAttributesKey NUMBER = SyntaxHighlighterColors.NUMBER;
- public static final TextAttributesKey STRING = SyntaxHighlighterColors.STRING;
- public static final TextAttributesKey OPERATION_SIGN = SyntaxHighlighterColors.OPERATION_SIGN;
- public static final TextAttributesKey PARENTHESES = SyntaxHighlighterColors.PARENTHS;
- public static final TextAttributesKey BRACKETS = SyntaxHighlighterColors.BRACKETS;
- public static final TextAttributesKey BRACES = SyntaxHighlighterColors.BRACES;
- public static final TextAttributesKey COMMA = SyntaxHighlighterColors.COMMA;
- public static final TextAttributesKey DOT = SyntaxHighlighterColors.DOT;
- public static final TextAttributesKey JAVA_SEMICOLON = SyntaxHighlighterColors.JAVA_SEMICOLON;
- public static final TextAttributesKey DOC_COMMENT_TAG = SyntaxHighlighterColors.DOC_COMMENT_TAG;
- public static final TextAttributesKey DOC_COMMENT_MARKUP = SyntaxHighlighterColors.DOC_COMMENT_MARKUP;
- public static final TextAttributesKey DOC_COMMENT_TAG_VALUE = TextAttributesKey.createTextAttributesKey(
- "DOC_COMMENT_TAG_VALUE", DefaultLanguageHighlighterColors.DOC_COMMENT_TAG_VALUE);
- public static final TextAttributesKey VALID_STRING_ESCAPE = SyntaxHighlighterColors.VALID_STRING_ESCAPE;
- public static final TextAttributesKey INVALID_STRING_ESCAPE = SyntaxHighlighterColors.INVALID_STRING_ESCAPE;
+ public static final TextAttributesKey LINE_COMMENT
+ = TextAttributesKey.createTextAttributesKey("JAVA_LINE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT);
+ public static final TextAttributesKey JAVA_BLOCK_COMMENT
+ = TextAttributesKey.createTextAttributesKey("JAVA_BLOCK_COMMENT", DefaultLanguageHighlighterColors.BLOCK_COMMENT);
+ public static final TextAttributesKey DOC_COMMENT
+ = TextAttributesKey.createTextAttributesKey("JAVA_DOC_COMMENT", DefaultLanguageHighlighterColors.DOC_COMMENT);
+ public static final TextAttributesKey KEYWORD
+ = TextAttributesKey.createTextAttributesKey("JAVA_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD);
+ public static final TextAttributesKey NUMBER
+ = TextAttributesKey.createTextAttributesKey("JAVA_NUMBER", DefaultLanguageHighlighterColors.NUMBER);
+ public static final TextAttributesKey STRING
+ = TextAttributesKey.createTextAttributesKey("JAVA_STRING", DefaultLanguageHighlighterColors.STRING);
+ public static final TextAttributesKey OPERATION_SIGN
+ = TextAttributesKey.createTextAttributesKey("JAVA_OPERATION_SIGN", DefaultLanguageHighlighterColors.OPERATION_SIGN);
+ public static final TextAttributesKey PARENTHESES
+ = TextAttributesKey.createTextAttributesKey("JAVA_PARENTH", DefaultLanguageHighlighterColors.PARENTHESES);
+ public static final TextAttributesKey BRACKETS
+ = TextAttributesKey.createTextAttributesKey("JAVA_BRACKETS", DefaultLanguageHighlighterColors.BRACKETS);
+ public static final TextAttributesKey BRACES
+ = TextAttributesKey.createTextAttributesKey("JAVA_BRACES", DefaultLanguageHighlighterColors.BRACES);
+ public static final TextAttributesKey COMMA
+ = TextAttributesKey.createTextAttributesKey("JAVA_COMMA", DefaultLanguageHighlighterColors.COMMA);
+ public static final TextAttributesKey DOT
+ = TextAttributesKey.createTextAttributesKey("JAVA_DOT", DefaultLanguageHighlighterColors.DOT);
+ public static final TextAttributesKey JAVA_SEMICOLON
+ = TextAttributesKey.createTextAttributesKey("JAVA_SEMICOLON", DefaultLanguageHighlighterColors.SEMICOLON);
+ public static final TextAttributesKey DOC_COMMENT_TAG
+ = TextAttributesKey.createTextAttributesKey("JAVA_DOC_TAG", DefaultLanguageHighlighterColors.DOC_COMMENT_TAG);
+ public static final TextAttributesKey DOC_COMMENT_MARKUP
+ = TextAttributesKey.createTextAttributesKey("JAVA_DOC_MARKUP", DefaultLanguageHighlighterColors.DOC_COMMENT_MARKUP);
+ public static final TextAttributesKey DOC_COMMENT_TAG_VALUE
+ = TextAttributesKey.createTextAttributesKey("DOC_COMMENT_TAG_VALUE", DefaultLanguageHighlighterColors.DOC_COMMENT_TAG_VALUE);
+ public static final TextAttributesKey VALID_STRING_ESCAPE
+ = TextAttributesKey.createTextAttributesKey("JAVA_VALID_STRING_ESCAPE", DefaultLanguageHighlighterColors.VALID_STRING_ESCAPE);
+ public static final TextAttributesKey INVALID_STRING_ESCAPE
+ = TextAttributesKey.createTextAttributesKey("JAVA_INVALID_STRING_ESCAPE", DefaultLanguageHighlighterColors.INVALID_STRING_ESCAPE);
+
+ public static final TextAttributesKey LOCAL_VARIABLE_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("LOCAL_VARIABLE_ATTRIBUTES", DefaultLanguageHighlighterColors.LOCAL_VARIABLE);
+ public static final TextAttributesKey PARAMETER_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("PARAMETER_ATTRIBUTES", DefaultLanguageHighlighterColors.PARAMETER);
+ public static final TextAttributesKey REASSIGNED_LOCAL_VARIABLE_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("REASSIGNED_LOCAL_VARIABLE_ATTRIBUTES", LOCAL_VARIABLE_ATTRIBUTES);
+ public static final TextAttributesKey REASSIGNED_PARAMETER_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("REASSIGNED_PARAMETER_ATTRIBUTES", PARAMETER_ATTRIBUTES);
+ public static final TextAttributesKey INSTANCE_FIELD_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("INSTANCE_FIELD_ATTRIBUTES", DefaultLanguageHighlighterColors.INSTANCE_FIELD);
+ public static final TextAttributesKey INSTANCE_FINAL_FIELD_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("INSTANCE_FINAL_FIELD_ATTRIBUTES", INSTANCE_FIELD_ATTRIBUTES);
+ public static final TextAttributesKey STATIC_FIELD_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("STATIC_FIELD_ATTRIBUTES", DefaultLanguageHighlighterColors.STATIC_FIELD);
+ public static final TextAttributesKey STATIC_FINAL_FIELD_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("STATIC_FINAL_FIELD_ATTRIBUTES", STATIC_FIELD_ATTRIBUTES);
+ public static final TextAttributesKey CLASS_NAME_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("CLASS_NAME_ATTRIBUTES", DefaultLanguageHighlighterColors.CLASS_NAME);
+ public static final TextAttributesKey ANONYMOUS_CLASS_NAME_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("ANONYMOUS_CLASS_NAME_ATTRIBUTES", CLASS_NAME_ATTRIBUTES);
+ public static final TextAttributesKey IMPLICIT_ANONYMOUS_CLASS_PARAMETER_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("IMPLICIT_ANONYMOUS_CLASS_PARAMETER_ATTRIBUTES", CLASS_NAME_ATTRIBUTES);
+ public static final TextAttributesKey TYPE_PARAMETER_NAME_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("TYPE_PARAMETER_NAME_ATTRIBUTES", DefaultLanguageHighlighterColors.PARAMETER);
+ public static final TextAttributesKey INTERFACE_NAME_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("INTERFACE_NAME_ATTRIBUTES", DefaultLanguageHighlighterColors.INTERFACE_NAME);
+ public static final TextAttributesKey ENUM_NAME_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("ENUM_NAME_ATTRIBUTES", CLASS_NAME_ATTRIBUTES);
+ public static final TextAttributesKey ABSTRACT_CLASS_NAME_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("ABSTRACT_CLASS_NAME_ATTRIBUTES", CLASS_NAME_ATTRIBUTES);
+ public static final TextAttributesKey METHOD_CALL_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("METHOD_CALL_ATTRIBUTES", DefaultLanguageHighlighterColors.FUNCTION_CALL);
+ public static final TextAttributesKey METHOD_DECLARATION_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("METHOD_DECLARATION_ATTRIBUTES", DefaultLanguageHighlighterColors.FUNCTION_DECLARATION);
+ public static final TextAttributesKey STATIC_METHOD_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("STATIC_METHOD_ATTRIBUTES", DefaultLanguageHighlighterColors.STATIC_METHOD);
+ public static final TextAttributesKey ABSTRACT_METHOD_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("ABSTRACT_METHOD_ATTRIBUTES", METHOD_CALL_ATTRIBUTES);
+ public static final TextAttributesKey INHERITED_METHOD_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("INHERITED_METHOD_ATTRIBUTES", METHOD_CALL_ATTRIBUTES);
+ public static final TextAttributesKey CONSTRUCTOR_CALL_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("CONSTRUCTOR_CALL_ATTRIBUTES", DefaultLanguageHighlighterColors.FUNCTION_CALL);
+ public static final TextAttributesKey CONSTRUCTOR_DECLARATION_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("CONSTRUCTOR_DECLARATION_ATTRIBUTES", DefaultLanguageHighlighterColors.FUNCTION_DECLARATION);
+ public static final TextAttributesKey ANNOTATION_NAME_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("ANNOTATION_NAME_ATTRIBUTES", DefaultLanguageHighlighterColors.METADATA);
+ public static final TextAttributesKey ANNOTATION_ATTRIBUTE_NAME_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("ANNOTATION_ATTRIBUTE_NAME_ATTRIBUTES", DefaultLanguageHighlighterColors.METADATA);
+ public static final TextAttributesKey ANNOTATION_ATTRIBUTE_VALUE_ATTRIBUTES
+ = TextAttributesKey.createTextAttributesKey("ANNOTATION_ATTRIBUTE_VALUE_ATTRIBUTES", DefaultLanguageHighlighterColors.METADATA);
}
diff --git a/java/java-impl/java-impl.iml b/java/java-impl/java-impl.iml
index eb22a86d630c..3a2e9d845261 100644
--- a/java/java-impl/java-impl.iml
+++ b/java/java-impl/java-impl.iml
@@ -1,6 +1,6 @@
-
+
diff --git a/java/java-impl/src/com/intellij/application/options/ImportLayoutPanel.java b/java/java-impl/src/com/intellij/application/options/ImportLayoutPanel.java
index 9e343fbbca3e..92e42e5deec2 100644
--- a/java/java-impl/src/com/intellij/application/options/ImportLayoutPanel.java
+++ b/java/java-impl/src/com/intellij/application/options/ImportLayoutPanel.java
@@ -17,6 +17,8 @@ package com.intellij.application.options;
import com.intellij.ide.highlighter.JavaHighlightingColors;
import com.intellij.openapi.actionSystem.AnActionEvent;
+import com.intellij.openapi.actionSystem.CommonShortcuts;
+import com.intellij.openapi.actionSystem.ShortcutSet;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.psi.codeStyle.PackageEntry;
@@ -93,45 +95,58 @@ public abstract class ImportLayoutPanel extends JPanel {
refresh();
}
});
- this.add(myCbLayoutStaticImportsSeparately, BorderLayout.NORTH);
+
+ add(myCbLayoutStaticImportsSeparately, BorderLayout.NORTH);
+
+ JPanel importLayoutPanel = ToolbarDecorator.createDecorator(myImportLayoutTable = createTableForPackageEntries(myImportLayoutList, this))
+ .addExtraAction(new DumbAwareActionButton(ApplicationBundle.message("button.add.package"), IconUtil.getAddPackageIcon()) {
+ @Override
+ public void actionPerformed(AnActionEvent e) {
+ addPackageToImportLayouts();
+ }
- this.add(
- ToolbarDecorator.createDecorator(myImportLayoutTable = createTableForPackageEntries(myImportLayoutList, this))
- .addExtraAction(new DumbAwareActionButton(ApplicationBundle.message("button.add.package"), IconUtil.getAddPackageIcon()) {
- @Override
- public void actionPerformed(AnActionEvent e) {
- addPackageToImportLayouts();
- }
- }).addExtraAction(new DumbAwareActionButton(ApplicationBundle.message("button.add.blank"), IconUtil.getAddBlankLineIcon()) {
+ @Override
+ public ShortcutSet getShortcut() {
+ return CommonShortcuts.getNewForDialogs();
+ }
+ })
+ .addExtraAction(new DumbAwareActionButton(ApplicationBundle.message("button.add.blank"), IconUtil.getAddBlankLineIcon()) {
@Override
public void actionPerformed(AnActionEvent e) {
addBlankLine();
}
- }).setRemoveAction(new AnActionButtonRunnable() {
+ })
+ .setRemoveAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
removeEntryFromImportLayouts();
}
- }).setMoveUpAction(new AnActionButtonRunnable() {
+ })
+ .setMoveUpAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
moveRowUp();
}
- }).setMoveDownAction(new AnActionButtonRunnable() {
+ })
+ .setMoveDownAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
moveRowDown();
}
- }).setRemoveActionUpdater(new AnActionButtonUpdater() {
+ })
+ .setRemoveActionUpdater(new AnActionButtonUpdater() {
@Override
public boolean isEnabled(AnActionEvent e) {
int selectedImport = myImportLayoutTable.getSelectedRow();
PackageEntry entry = selectedImport < 0 ? null : myImportLayoutList.getEntryAt(selectedImport);
return entry != null && entry != PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY && entry != PackageEntry.ALL_OTHER_IMPORTS_ENTRY;
}
- }).setButtonComparator(ApplicationBundle.message("button.add.package"), ApplicationBundle.message("button.add.blank"),
- "Remove", "Up", "Down")
- .setPreferredSize(new Dimension(-1, 100)).createPanel(), BorderLayout.CENTER);
+ })
+ .setButtonComparator(ApplicationBundle.message("button.add.package"), ApplicationBundle.message("button.add.blank"), "Remove", "Up", "Down")
+ .setPreferredSize(new Dimension(-1, 100)).createPanel();
+
+
+ add(importLayoutPanel, BorderLayout.CENTER);
}
diff --git a/java/java-impl/src/com/intellij/application/options/editor/JavaAutoImportOptions.form b/java/java-impl/src/com/intellij/application/options/editor/JavaAutoImportOptions.form
index 0c61b43980d3..2a56f3f0bfb7 100644
--- a/java/java-impl/src/com/intellij/application/options/editor/JavaAutoImportOptions.form
+++ b/java/java-impl/src/com/intellij/application/options/editor/JavaAutoImportOptions.form
@@ -1,6 +1,6 @@
+
+
+
+
+
+
+
+
@@ -61,7 +69,7 @@
-
+
@@ -71,7 +79,7 @@
-
+
diff --git a/java/java-impl/src/com/intellij/application/options/editor/JavaAutoImportOptions.java b/java/java-impl/src/com/intellij/application/options/editor/JavaAutoImportOptions.java
index 32db6ea18abb..007e62e98b21 100644
--- a/java/java-impl/src/com/intellij/application/options/editor/JavaAutoImportOptions.java
+++ b/java/java-impl/src/com/intellij/application/options/editor/JavaAutoImportOptions.java
@@ -39,6 +39,7 @@ public class JavaAutoImportOptions implements AutoImportOptionsProvider {
private JCheckBox myCbShowImportPopup;
private JPanel myWholePanel;
private JCheckBox myCbAddUnambiguousImports;
+ private JCheckBox myCbAddMethodImports;
private JCheckBox myCbOptimizeImports;
private JPanel myExcludeFromImportAndCompletionPanel;
private final ExcludeTable myExcludePackagesTable;
@@ -78,6 +79,7 @@ public class JavaAutoImportOptions implements AutoImportOptionsProvider {
myCbShowImportPopup.setSelected(daemonSettings.isImportHintEnabled());
myCbOptimizeImports.setSelected(codeInsightSettings.OPTIMIZE_IMPORTS_ON_THE_FLY);
myCbAddUnambiguousImports.setSelected(codeInsightSettings.ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY);
+ myCbAddMethodImports.setSelected(codeInsightSettings.ADD_MEMBER_IMPORTS_ON_THE_FLY);
myExcludePackagesTable.reset();
}
@@ -94,6 +96,7 @@ public class JavaAutoImportOptions implements AutoImportOptionsProvider {
daemonSettings.setImportHintEnabled(myCbShowImportPopup.isSelected());
codeInsightSettings.OPTIMIZE_IMPORTS_ON_THE_FLY = myCbOptimizeImports.isSelected();
codeInsightSettings.ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = myCbAddUnambiguousImports.isSelected();
+ codeInsightSettings.ADD_MEMBER_IMPORTS_ON_THE_FLY = myCbAddMethodImports.isSelected();
myExcludePackagesTable.apply();
@@ -113,6 +116,7 @@ public class JavaAutoImportOptions implements AutoImportOptionsProvider {
boolean isModified = isModified(myCbShowImportPopup, daemonSettings.isImportHintEnabled());
isModified |= isModified(myCbOptimizeImports, codeInsightSettings.OPTIMIZE_IMPORTS_ON_THE_FLY);
isModified |= isModified(myCbAddUnambiguousImports, codeInsightSettings.ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY);
+ isModified |= isModified(myCbAddMethodImports, codeInsightSettings.ADD_MEMBER_IMPORTS_ON_THE_FLY);
isModified |= getSmartPasteValue() != codeInsightSettings.ADD_IMPORTS_ON_PASTE;
isModified |= myExcludePackagesTable.isModified();
diff --git a/java/java-impl/src/com/intellij/codeInsight/CodeInsightUtil.java b/java/java-impl/src/com/intellij/codeInsight/CodeInsightUtil.java
index d842830abdb6..0fc7d26ba879 100644
--- a/java/java-impl/src/com/intellij/codeInsight/CodeInsightUtil.java
+++ b/java/java-impl/src/com/intellij/codeInsight/CodeInsightUtil.java
@@ -21,14 +21,11 @@ import com.intellij.codeInsight.completion.JavaCompletionUtil;
import com.intellij.codeInsight.completion.PrefixMatcher;
import com.intellij.lang.Language;
import com.intellij.lang.StdLanguages;
-import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
-import com.intellij.openapi.util.Computable;
-import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
@@ -276,33 +273,15 @@ public class CodeInsightUtil {
psiType = psiType.getDeepComponentType();
if (!(psiType instanceof PsiClassType)) return;
- final Condition shortNameCondition = new Condition() {
- @Override
- public boolean value(String s) {
- return matcher.prefixMatches(s);
- }
- };
-
- final PsiClassType baseType = (PsiClassType)psiType;
- final PsiClassType.ClassResolveResult baseResult =
- ApplicationManager.getApplication().runReadAction(new Computable() {
- @Override
- public PsiClassType.ClassResolveResult compute() {
- return JavaCompletionUtil.originalize(baseType).resolveGenerics();
- }
- });
- final PsiClass baseClass = baseResult.getElement();
- final PsiSubstitutor baseSubstitutor = baseResult.getSubstitutor();
+ PsiClassType baseType = JavaCompletionUtil.originalize((PsiClassType)psiType);
+ PsiClassType.ClassResolveResult baseResult = baseType.resolveGenerics();
+ PsiClass baseClass = baseResult.getElement();
+ PsiSubstitutor baseSubstitutor = baseResult.getSubstitutor();
if(baseClass == null) return;
- final GlobalSearchScope scope = ApplicationManager.getApplication().runReadAction(new Computable() {
- @Override
- public GlobalSearchScope compute() {
- return context.getResolveScope();
- }
- });
+ GlobalSearchScope scope = context.getResolveScope();
- final Processor inheritorsProcessor =
+ Processor inheritorsProcessor =
createInheritorsProcessor(context, baseType, arrayDim, getRawSubtypes, consumer, baseClass, baseSubstitutor);
addContextTypeArguments(context, baseType, inheritorsProcessor);
@@ -310,118 +289,98 @@ public class CodeInsightUtil {
if (baseClass.hasModifierProperty(PsiModifier.FINAL)) return;
if (matcher.getPrefix().length() > 2) {
- AllClassesGetter.processJavaClasses(matcher, context.getProject(), scope, new Processor() {
- @Override
- public boolean process(PsiClass psiClass) {
- if (psiClass.isInheritor(baseClass, true)) {
- return inheritorsProcessor.process(psiClass);
- }
- return true;
+ AllClassesGetter.processJavaClasses(matcher, context.getProject(), scope, psiClass -> {
+ if (psiClass.isInheritor(baseClass, true)) {
+ return inheritorsProcessor.process(psiClass);
}
+ return true;
});
} else {
- final Query baseQuery = ClassInheritorsSearch.search(
- new ClassInheritorsSearch.SearchParameters(baseClass, scope, true, false, false, shortNameCondition));
- final Query query = new FilteredQuery(baseQuery, new Condition() {
- @Override
- public boolean value(final PsiClass psiClass) {
- return !(psiClass instanceof PsiTypeParameter);
- }
- });
+ Query baseQuery = ClassInheritorsSearch.search(
+ new ClassInheritorsSearch.SearchParameters(baseClass, scope, true, false, false, matcher::prefixMatches));
+ Query query = new FilteredQuery<>(baseQuery, psiClass -> !(psiClass instanceof PsiTypeParameter));
query.forEach(inheritorsProcessor);
}
-
}
- private static void addContextTypeArguments(final PsiElement context,
- final PsiClassType baseType,
- final Processor inheritorsProcessor) {
- ApplicationManager.getApplication().runReadAction(new Runnable() {
- @Override
- public void run() {
- Set usedNames = ContainerUtil.newHashSet();
- PsiElementFactory factory = JavaPsiFacade.getElementFactory(context.getProject());
- PsiElement each = context;
- while (true) {
- PsiTypeParameterListOwner typed = PsiTreeUtil.getParentOfType(each, PsiTypeParameterListOwner.class);
- if (typed == null) break;
- for (PsiTypeParameter parameter : typed.getTypeParameters()) {
- if (baseType.isAssignableFrom(factory.createType(parameter)) && usedNames.add(parameter.getName())) {
- inheritorsProcessor.process(CompletionUtil.getOriginalOrSelf(parameter));
- }
- }
-
- each = typed;
+ private static void addContextTypeArguments(PsiElement context, PsiClassType baseType, Processor inheritorsProcessor) {
+ Set usedNames = ContainerUtil.newHashSet();
+ PsiElementFactory factory = JavaPsiFacade.getElementFactory(context.getProject());
+ PsiElement each = context;
+ while (true) {
+ PsiTypeParameterListOwner typed = PsiTreeUtil.getParentOfType(each, PsiTypeParameterListOwner.class);
+ if (typed == null) break;
+ for (PsiTypeParameter parameter : typed.getTypeParameters()) {
+ if (baseType.isAssignableFrom(factory.createType(parameter)) && usedNames.add(parameter.getName())) {
+ inheritorsProcessor.process(CompletionUtil.getOriginalOrSelf(parameter));
}
}
- });
+
+ each = typed;
+ }
}
- public static Processor createInheritorsProcessor(final PsiElement context, final PsiClassType baseType,
- final int arrayDim,
- final boolean getRawSubtypes,
- final Consumer result, @NotNull final PsiClass baseClass, final PsiSubstitutor baseSubstitutor) {
- final PsiManager manager = context.getManager();
- final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
- final PsiResolveHelper resolveHelper = facade.getResolveHelper();
+ public static Processor createInheritorsProcessor(PsiElement context,
+ PsiClassType baseType,
+ int arrayDim,
+ boolean getRawSubtypes,
+ Consumer result,
+ @NotNull PsiClass baseClass,
+ PsiSubstitutor baseSubstitutor) {
+ PsiManager manager = context.getManager();
+ JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
+ PsiResolveHelper resolveHelper = facade.getResolveHelper();
- return new Processor() {
- @Override
- public boolean process(final PsiClass inheritor) {
- ProgressManager.checkCanceled();
+ return inheritor -> {
+ ProgressManager.checkCanceled();
- return ApplicationManager.getApplication().runReadAction(new Computable() {
- @Override
- public Boolean compute() {
- if (!context.isValid() || !inheritor.isValid() || !facade.getResolveHelper().isAccessible(inheritor, context, null))
- return true;
+ if (!facade.getResolveHelper().isAccessible(inheritor, context, null)) {
+ return true;
+ }
- if (inheritor.getQualifiedName() == null &&
- !manager.areElementsEquivalent(inheritor.getContainingFile(), context.getContainingFile().getOriginalFile())) {
- return true;
- }
+ if (inheritor.getQualifiedName() == null &&
+ !manager.areElementsEquivalent(inheritor.getContainingFile(), context.getContainingFile().getOriginalFile())) {
+ return true;
+ }
- if (JavaCompletionUtil.isInExcludedPackage(inheritor, false)) return true;
+ if (JavaCompletionUtil.isInExcludedPackage(inheritor, false)) return true;
- PsiSubstitutor superSubstitutor = TypeConversionUtil.getClassSubstitutor(baseClass, inheritor, PsiSubstitutor.EMPTY);
- if (superSubstitutor == null) return true;
- if (getRawSubtypes) {
- result.consume(createType(inheritor, facade.getElementFactory().createRawSubstitutor(inheritor), arrayDim));
- return true;
- }
+ PsiSubstitutor superSubstitutor = TypeConversionUtil.getClassSubstitutor(baseClass, inheritor, PsiSubstitutor.EMPTY);
+ if (superSubstitutor == null) return true;
+ if (getRawSubtypes) {
+ result.consume(createType(inheritor, facade.getElementFactory().createRawSubstitutor(inheritor), arrayDim));
+ return true;
+ }
- PsiSubstitutor inheritorSubstitutor = PsiSubstitutor.EMPTY;
- for (PsiTypeParameter inheritorParameter : PsiUtil.typeParametersIterable(inheritor)) {
- for (PsiTypeParameter baseParameter : PsiUtil.typeParametersIterable(baseClass)) {
- final PsiType substituted = superSubstitutor.substitute(baseParameter);
- PsiType arg = baseSubstitutor.substitute(baseParameter);
- if (arg instanceof PsiWildcardType) {
- PsiType bound = ((PsiWildcardType)arg).getBound();
- arg = bound != null ? bound : ((PsiWildcardType)arg).getExtendsBound();
- }
- PsiType substitution = resolveHelper.getSubstitutionForTypeParameter(inheritorParameter,
- substituted,
- arg,
- true,
- PsiUtil.getLanguageLevel(context));
- if (PsiType.NULL.equals(substitution) || substitution instanceof PsiWildcardType) continue;
- if (substitution == null) {
- result.consume(createType(inheritor, facade.getElementFactory().createRawSubstitutor(inheritor), arrayDim));
- return true;
- }
- inheritorSubstitutor = inheritorSubstitutor.put(inheritorParameter, substitution);
- break;
- }
- }
-
- PsiType toAdd = createType(inheritor, inheritorSubstitutor, arrayDim);
- if (baseType.isAssignableFrom(toAdd)) {
- result.consume(toAdd);
- }
+ PsiSubstitutor inheritorSubstitutor = PsiSubstitutor.EMPTY;
+ for (PsiTypeParameter inheritorParameter : PsiUtil.typeParametersIterable(inheritor)) {
+ for (PsiTypeParameter baseParameter : PsiUtil.typeParametersIterable(baseClass)) {
+ final PsiType substituted = superSubstitutor.substitute(baseParameter);
+ PsiType arg = baseSubstitutor.substitute(baseParameter);
+ if (arg instanceof PsiWildcardType) {
+ PsiType bound = ((PsiWildcardType)arg).getBound();
+ arg = bound != null ? bound : ((PsiWildcardType)arg).getExtendsBound();
+ }
+ PsiType substitution = resolveHelper.getSubstitutionForTypeParameter(inheritorParameter,
+ substituted,
+ arg,
+ true,
+ PsiUtil.getLanguageLevel(context));
+ if (PsiType.NULL.equals(substitution) || substitution instanceof PsiWildcardType) continue;
+ if (substitution == null) {
+ result.consume(createType(inheritor, facade.getElementFactory().createRawSubstitutor(inheritor), arrayDim));
return true;
}
- }).booleanValue();
+ inheritorSubstitutor = inheritorSubstitutor.put(inheritorParameter, substitution);
+ break;
+ }
}
+
+ PsiType toAdd = createType(inheritor, inheritorSubstitutor, arrayDim);
+ if (baseType.isAssignableFrom(toAdd)) {
+ result.consume(toAdd);
+ }
+ return true;
};
}
diff --git a/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java b/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java
index c6dcf130c3f8..656bae7f13e5 100644
--- a/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java
+++ b/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java
@@ -337,18 +337,21 @@ public class ExpectedTypesProvider {
type = ((PsiAnnotationMethod)parent).getReturnType();
}
if (type instanceof PsiArrayType) {
- myResult.add(createInfoImpl(((PsiArrayType)type).getComponentType(), type));
+ final PsiType componentType = ((PsiArrayType)type).getComponentType();
+ myResult.add(createInfoImpl(componentType, componentType));
}
}
@Override public void visitNameValuePair(@NotNull PsiNameValuePair pair) {
final PsiType type = getAnnotationMethodType(pair);
if (type == null) return;
- myResult.add(createInfoImpl(type, type));
if (type instanceof PsiArrayType) {
PsiType componentType = ((PsiArrayType)type).getComponentType();
myResult.add(createInfoImpl(componentType, componentType));
}
+ else {
+ myResult.add(createInfoImpl(type, type));
+ }
}
@Nullable
diff --git a/java/java-impl/src/com/intellij/codeInsight/JavaProjectCodeInsightSettings.java b/java/java-impl/src/com/intellij/codeInsight/JavaProjectCodeInsightSettings.java
index 45b61aef8740..cab9767a1323 100644
--- a/java/java-impl/src/com/intellij/codeInsight/JavaProjectCodeInsightSettings.java
+++ b/java/java-impl/src/com/intellij/codeInsight/JavaProjectCodeInsightSettings.java
@@ -65,7 +65,8 @@ public class JavaProjectCodeInsightSettings implements PersistentStateComponent<
}
private static boolean nameMatches(@NotNull String name, String excluded) {
- return name.equals(excluded) || name.startsWith(excluded + ".");
+ return name.startsWith(excluded) &&
+ (name.length() == excluded.length() || name.charAt(excluded.length()) == '.');
}
@Nullable
diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaChainLookupElement.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaChainLookupElement.java
index 928ffe49d232..67ad744e305b 100644
--- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaChainLookupElement.java
+++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaChainLookupElement.java
@@ -102,6 +102,9 @@ public class JavaChainLookupElement extends LookupElementDecorator processJavaReference(PsiElement element, PsiJavaReference javaReference, ElementFilter elementFilter,
+ public static Set processJavaReference(final PsiElement element,
+ final PsiJavaReference javaReference,
+ final ElementFilter elementFilter,
+ final JavaCompletionProcessor.Options options,
+ final PrefixMatcher matcher,
+ final CompletionParameters parameters) {
+ PsiElement elementParent = element.getContext();
+ if (elementParent instanceof PsiReferenceExpression) {
+ final PsiExpression qualifierExpression = ((PsiReferenceExpression)elementParent).getQualifierExpression();
+ if (qualifierExpression instanceof PsiReferenceExpression) {
+ final PsiElement resolve = ((PsiReferenceExpression)qualifierExpression).resolve();
+ if (resolve instanceof PsiParameter) {
+ final PsiElement declarationScope = ((PsiParameter)resolve).getDeclarationScope();
+ if (((PsiParameter)resolve).getType() instanceof PsiLambdaParameterType) {
+ final PsiLambdaExpression lambdaExpression = (PsiLambdaExpression)declarationScope;
+ final int parameterIndex = lambdaExpression.getParameterList().getParameterIndex((PsiParameter)resolve);
+ final Set set = new LinkedHashSet();
+ final boolean overloadsFound = LambdaUtil.processParentOverloads(lambdaExpression, new Consumer() {
+ @Override
+ public void consume(PsiType functionalInterfaceType) {
+ PsiType qualifierType = LambdaUtil.getLambdaParameterFromType(functionalInterfaceType, parameterIndex);
+ PsiReferenceExpression fakeRef = createReference("xxx.xxx", createContextWithXxxVariable(element, qualifierType));
+ set.addAll(processJavaQualifiedReference(fakeRef.getReferenceNameElement(), fakeRef, elementFilter, options, matcher, parameters));
+ }
+ });
+ if (overloadsFound) return set;
+ }
+ }
+ }
+ }
+ return processJavaQualifiedReference(element, javaReference, elementFilter, options, matcher, parameters);
+ }
+
+ private static Set processJavaQualifiedReference(PsiElement element, PsiJavaReference javaReference, ElementFilter elementFilter,
JavaCompletionProcessor.Options options,
final PrefixMatcher matcher, CompletionParameters parameters) {
final Set set = new LinkedHashSet();
@@ -880,4 +913,19 @@ public class JavaCompletionUtil {
}
return generics;
}
+
+ public static boolean isEffectivelyDeprecated(PsiDocCommentOwner member) {
+ if (member.isDeprecated()) {
+ return true;
+ }
+
+ PsiClass aClass = member.getContainingClass();
+ while (aClass != null) {
+ if (aClass.isDeprecated()) {
+ return true;
+ }
+ aClass = aClass.getContainingClass();
+ }
+ return false;
+ }
}
diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaInheritorsGetter.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaInheritorsGetter.java
index cceb1668a231..22bbe113448c 100644
--- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaInheritorsGetter.java
+++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaInheritorsGetter.java
@@ -26,7 +26,9 @@ import com.intellij.openapi.diagnostic.Logger;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.filters.getters.ExpectedTypesGetter;
+import com.intellij.psi.impl.PsiClassImplUtil;
import com.intellij.psi.impl.source.PsiClassReferenceType;
+import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.statistics.JavaStatisticsManager;
import com.intellij.psi.statistics.StatisticsInfo;
import com.intellij.psi.statistics.StatisticsManager;
@@ -34,6 +36,7 @@ import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.*;
+import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -67,12 +70,8 @@ public class JavaInheritorsGetter extends CompletionProvider infoCollection = Arrays.asList(infos);
- generateVariants(parameters, result.getPrefixMatcher(), infos, new Consumer() {
- @Override
- public void consume(LookupElement lookupElement) {
- result.addElement(JavaSmartCompletionContributor.decorate(lookupElement, infoCollection));
- }
- });
+ generateVariants(parameters, result.getPrefixMatcher(), infos,
+ lookupElement -> result.addElement(JavaSmartCompletionContributor.decorate(lookupElement, infoCollection)));
}
public void generateVariants(final CompletionParameters parameters, final PrefixMatcher prefixMatcher, final Consumer consumer) {
@@ -84,13 +83,10 @@ public class JavaInheritorsGetter extends CompletionProvider() {
- @Override
- public void consume(final PsiType type) {
- final LookupElement element = addExpectedType(type, parameters);
- if (element != null) {
- consumer.consume(element);
- }
+ processInheritors(parameters, extractClassTypes(infos), prefixMatcher, type -> {
+ final LookupElement element = addExpectedType(type, parameters);
+ if (element != null) {
+ consumer.consume(element);
}
});
}
@@ -116,7 +112,7 @@ public class JavaInheritorsGetter extends CompletionProvider extractClassTypes(ExpectedTypeInfo[] infos) {
- final List expectedClassTypes = new SmartList();
+ final List expectedClassTypes = new SmartList<>();
for (PsiType type : ExpectedTypesGetter.extractTypes(infos, true)) {
if (type instanceof PsiClassType) {
final PsiClassType classType = (PsiClassType)type;
@@ -205,7 +201,6 @@ public class JavaInheritorsGetter extends CompletionProvider expectedClassTypes,
+ Collection expectedClassTypes,
final PrefixMatcher matcher, final Consumer consumer) {
- processInheritors(parameters.getOriginalFile(), parameters.getPosition(), expectedClassTypes, matcher, consumer);
- }
+ final PsiElement context = parameters.getPosition();
+ GlobalSearchScope scope = context.getResolveScope();
+ expectedClassTypes = ContainerUtil.mapNotNull(expectedClassTypes, type -> PsiClassImplUtil.correctType(type, scope));
- public static void processInheritors(final PsiFile file,
- final PsiElement context,
- final Collection expectedClassTypes,
- final PrefixMatcher matcher, final Consumer consumer) {
//quick
- if (!processMostProbableInheritors(file, context, expectedClassTypes, consumer)) return;
+ if (!processMostProbableInheritors(parameters.getOriginalFile(), context, expectedClassTypes, consumer)) return;
//long
for (final PsiClassType type : expectedClassTypes) {
diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/SlowerTypeConversions.java b/java/java-impl/src/com/intellij/codeInsight/completion/SlowerTypeConversions.java
index 982cf2c8924c..fdd56255e8c9 100644
--- a/java/java-impl/src/com/intellij/codeInsight/completion/SlowerTypeConversions.java
+++ b/java/java-impl/src/com/intellij/codeInsight/completion/SlowerTypeConversions.java
@@ -115,7 +115,7 @@ class SlowerTypeConversions implements Runnable {
FromArrayConversion.addConversions(element, prefix, itemType, result, qualifier, expectedType);
- ToArrayConversion.addConversions(element, object, prefix, itemType, result, qualifier, expectedType);
+ ToArrayConversion.addConversions(element, prefix, itemType, result, qualifier, expectedType);
ArrayMemberAccess.addMemberAccessors(element, prefix, itemType, qualifier, result, (PsiModifierListOwner)object, expectedType);
}
diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/ToArrayConversion.java b/java/java-impl/src/com/intellij/codeInsight/completion/ToArrayConversion.java
index c4b0e12da1f2..9f2690cae1aa 100644
--- a/java/java-impl/src/com/intellij/codeInsight/completion/ToArrayConversion.java
+++ b/java/java-impl/src/com/intellij/codeInsight/completion/ToArrayConversion.java
@@ -36,10 +36,9 @@ import static com.intellij.codeInsight.completion.ReferenceExpressionCompletionC
* @author peter
*/
public class ToArrayConversion {
- static void addConversions(final PsiElement element, final Object object, final String prefix, final PsiType itemType,
+ static void addConversions(final PsiElement element, final String prefix, final PsiType itemType,
final Consumer result, @Nullable final PsiElement qualifier,
final PsiType expectedType) {
- final String callSpace = getSpace(CodeStyleSettingsManager.getSettings(element.getProject()).SPACE_WITHIN_METHOD_CALL_PARENTHESES);
final PsiType componentType = PsiUtil.extractIterableTypeParameter(itemType, true);
if (componentType == null || !(expectedType instanceof PsiArrayType)) return;
@@ -50,40 +49,36 @@ public class ToArrayConversion {
}
final String bracketSpace = getSpace(CodeStyleSettingsManager.getSettings(element.getProject()).SPACE_WITHIN_BRACKETS);
- if (object instanceof PsiVariable && !JavaCompletionUtil.mayHaveSideEffects(qualifier)) {
- final PsiVariable variable = (PsiVariable)object;
- addToArrayConversion(element, prefix,
- "new " + componentType.getCanonicalText() +
- "[" + bracketSpace + getQualifierText(qualifier) + variable.getName() + ".size(" + callSpace + ")" + bracketSpace + "]",
- "new " + getQualifierText(qualifier) + componentType.getPresentableText() + "[" + variable.getName() + ".size()]", result, qualifier);
- } else {
- boolean hasEmptyArrayField = false;
- final PsiClass psiClass = PsiUtil.resolveClassInType(type);
- if (psiClass != null) {
- for (final PsiField field : psiClass.getAllFields()) {
- if (field.hasModifierProperty(PsiModifier.STATIC) && field.hasModifierProperty(PsiModifier.FINAL) &&
- JavaPsiFacade.getInstance(field.getProject()).getResolveHelper().isAccessible(field, element, null) &&
- type.isAssignableFrom(field.getType()) && isEmptyArrayInitializer(field.getInitializer())) {
- boolean needQualify;
- try {
- needQualify = !field.isEquivalentTo(((PsiReferenceExpression)createExpression(field.getName(), element)).resolve());
- }
- catch (IncorrectOperationException e) {
- continue;
- }
-
- addToArrayConversion(element, prefix,
- (needQualify ? field.getContainingClass().getQualifiedName() + "." : "") + field.getName(),
- (needQualify ? field.getContainingClass().getName() + "." : "") + field.getName(), result, qualifier);
- hasEmptyArrayField = true;
+ boolean hasEmptyArrayField = false;
+ final PsiClass psiClass = PsiUtil.resolveClassInType(type);
+ if (psiClass != null) {
+ for (final PsiField field : psiClass.getAllFields()) {
+ if (field.hasModifierProperty(PsiModifier.STATIC) && field.hasModifierProperty(PsiModifier.FINAL) &&
+ JavaPsiFacade.getInstance(field.getProject()).getResolveHelper().isAccessible(field, element, null) &&
+ type.isAssignableFrom(field.getType()) && isEmptyArrayInitializer(field.getInitializer())) {
+ boolean needQualify;
+ try {
+ needQualify = !field.isEquivalentTo(((PsiReferenceExpression)createExpression(field.getName(), element)).resolve());
}
+ catch (IncorrectOperationException e) {
+ continue;
+ }
+
+ PsiClass containingClass = field.getContainingClass();
+ if (containingClass == null) continue;
+
+ addToArrayConversion(element, prefix,
+ (needQualify ? containingClass.getQualifiedName() + "." : "") + field.getName(),
+ (needQualify ? containingClass.getName() + "." : "") + field.getName(), result, qualifier);
+ hasEmptyArrayField = true;
}
}
- if (!hasEmptyArrayField) {
- addToArrayConversion(element, prefix,
- "new " + componentType.getCanonicalText() + "[" + bracketSpace + "0" + bracketSpace + "]",
- "new " + componentType.getPresentableText() + "[0]", result, qualifier);
- }
+ }
+
+ if (!hasEmptyArrayField) {
+ addToArrayConversion(element, prefix,
+ "new " + componentType.getCanonicalText() + "[" + bracketSpace + "0" + bracketSpace + "]",
+ "new " + componentType.getPresentableText() + "[0]", result, qualifier);
}
}
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/actions/AddImportAction.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/actions/AddImportAction.java
index ce827c34353c..b64b91a65b6a 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/actions/AddImportAction.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/actions/AddImportAction.java
@@ -46,6 +46,7 @@ import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
@@ -120,27 +121,7 @@ public class AddImportAction implements QuestionAction {
return FINAL_CHOICE;
}
- String qname = selectedValue.getQualifiedName();
- if (qname == null) return FINAL_CHOICE;
-
- List toExclude = getAllExcludableStrings(qname);
-
- return new BaseListPopupStep(null, toExclude) {
- @NotNull
- @Override
- public String getTextFor(String value) {
- return "Exclude '" + value + "' from auto-import";
- }
-
- @Override
- public PopupStep onChosen(String selectedValue, boolean finalChoice) {
- if (finalChoice) {
- excludeFromImport(myProject, selectedValue);
- }
-
- return super.onChosen(selectedValue, finalChoice);
- }
- };
+ return getExcludesStep(selectedValue.getQualifiedName(), myProject);
}
@Override
@@ -179,6 +160,30 @@ public class AddImportAction implements QuestionAction {
popup.showInBestPositionFor(myEditor);
}
+ @Nullable
+ public static PopupStep getExcludesStep(String qname, final Project project) {
+ if (qname == null) return PopupStep.FINAL_CHOICE;
+
+ List toExclude = getAllExcludableStrings(qname);
+
+ return new BaseListPopupStep(null, toExclude) {
+ @NotNull
+ @Override
+ public String getTextFor(String value) {
+ return "Exclude '" + value + "' from auto-import";
+ }
+
+ @Override
+ public PopupStep onChosen(String selectedValue, boolean finalChoice) {
+ if (finalChoice) {
+ excludeFromImport(project, selectedValue);
+ }
+
+ return super.onChosen(selectedValue, finalChoice);
+ }
+ };
+ }
+
public static void excludeFromImport(final Project project, final String prefix) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeClassSignatureFromUsageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeClassSignatureFromUsageFix.java
index dec599e916bf..76d449dee2f8 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeClassSignatureFromUsageFix.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeClassSignatureFromUsageFix.java
@@ -24,6 +24,7 @@ import com.intellij.refactoring.changeClassSignature.ChangeClassSignatureDialog;
import com.intellij.refactoring.changeClassSignature.TypeParameterInfo;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import java.util.*;
@@ -86,31 +87,62 @@ public class ChangeClassSignatureFromUsageFix extends BaseIntentionAction {
}
@NotNull
- private static Map createTypeParameters(@NotNull JavaCodeFragmentFactory factory,
- @NotNull List classTypeParameters,
- @NotNull List typeElements) {
- final LinkedHashMap result = new LinkedHashMap();
+ private static List createTypeParameters(@NotNull JavaCodeFragmentFactory factory,
+ @NotNull List classTypeParameters,
+ @NotNull List typeElements) {
final TypeParameterNameSuggester suggester = new TypeParameterNameSuggester(classTypeParameters);
+ List result = new ArrayList();
int listIndex = 0;
for (PsiTypeElement typeElement : typeElements) {
if (listIndex < classTypeParameters.size()) {
final PsiTypeParameter typeParameter = classTypeParameters.get(listIndex);
if (isAssignable(typeParameter, typeElement.getType())) {
- result.put(new TypeParameterInfo(listIndex++), null);
+ result.add(new TypeParameterInfoView(new TypeParameterInfo.Existing(listIndex++), null, null));
continue;
}
}
- final PsiType type = typeElement.getType();
- final String suggestedName = type instanceof PsiClassType ? suggester.suggest((PsiClassType)type) : suggester.suggestUnusedName("T");
- result.put(new TypeParameterInfo(suggestedName, type),
- factory.createTypeCodeFragment(suggestedName, typeElement, true));
+ final PsiType defaultType = typeElement.getType();
+ final String suggestedName;
+ PsiClassType boundType = null;
+ if (defaultType instanceof PsiClassType) {
+ suggestedName = suggester.suggest((PsiClassType)defaultType);
+ final PsiClass resolved = ((PsiClassType)defaultType).resolve();
+ if (resolved != null) {
+ final PsiReferenceList extendsList = resolved.getExtendsList();
+ if (extendsList != null) {
+ final PsiClassType[] types = extendsList.getReferencedTypes();
+ if (types.length == 1) {
+ boundType = types[0];
+ }
+ }
+ }
+ }
+ else {
+ suggestedName = suggester.suggestUnusedName("T");
+ }
+ final PsiTypeCodeFragment boundFragment = createBoundCodeFragment(boundType, typeElement, factory);
+ result.add(new TypeParameterInfoView(new TypeParameterInfo.New(suggestedName, defaultType, null),
+ boundFragment,
+ boundType == null ? factory.createTypeCodeFragment(suggestedName, typeElement, true)
+ : createBoundCodeFragment(boundType, typeElement, factory)));
}
return result;
}
+ private static PsiTypeCodeFragment createBoundCodeFragment(@Nullable PsiClassType boundType,
+ @NotNull PsiElement context,
+ @NotNull JavaCodeFragmentFactory factory) {
+ final PsiTypeCodeFragment boundFragment =
+ factory.createTypeCodeFragment(boundType == null ? "" : boundType.getClassName(), context, true);
+ if (boundType != null) {
+ boundFragment.addImportsFromString(boundType.getCanonicalText());
+ }
+ return boundFragment;
+ }
+
private static boolean isAssignable(@NotNull PsiTypeParameter typeParameter, @NotNull PsiType type) {
for (PsiClassType t : typeParameter.getExtendsListTypes()) {
if (!t.isAssignableFrom(type)) {
@@ -157,4 +189,28 @@ public class ChangeClassSignatureFromUsageFix extends BaseIntentionAction {
return suggestUnusedName(type.getClassName().substring(0, 1).toUpperCase());
}
}
+
+ public static class TypeParameterInfoView {
+ private final TypeParameterInfo myInfo;
+ private final PsiTypeCodeFragment myBoundValueFragment;
+ private final PsiTypeCodeFragment myDefaultValueFragment;
+
+ public TypeParameterInfoView(TypeParameterInfo info, PsiTypeCodeFragment boundValueFragment, PsiTypeCodeFragment defaultValueFragment) {
+ myInfo = info;
+ myBoundValueFragment = boundValueFragment;
+ myDefaultValueFragment = defaultValueFragment;
+ }
+
+ public TypeParameterInfo getInfo() {
+ return myInfo;
+ }
+
+ public PsiTypeCodeFragment getBoundValueFragment() {
+ return myBoundValueFragment;
+ }
+
+ public PsiTypeCodeFragment getDefaultValueFragment() {
+ return myDefaultValueFragment;
+ }
+ }
}
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DefaultQuickFixProvider.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DefaultQuickFixProvider.java
index b5dc43e0f84a..7151726b0fb2 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DefaultQuickFixProvider.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DefaultQuickFixProvider.java
@@ -39,6 +39,7 @@ public class DefaultQuickFixProvider extends UnresolvedReferenceQuickFixProvider
public void registerFixes(@NotNull PsiJavaCodeReferenceElement ref, @NotNull QuickFixActionRegistrar registrar) {
QuickFixFactory factory = QuickFixFactory.getInstance();
registrar.register(new ImportClassFix(ref));
+ registrar.register(new StaticImportConstantFix(ref));
registrar.register(factory.createSetupJDKFix());
OrderEntryFix.registerFixes(registrar, ref);
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFixBase.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFixBase.java
index 88efb04b4827..03ffdf147a7c 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFixBase.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFixBase.java
@@ -317,7 +317,11 @@ public abstract class ImportClassFixBase rExpressions = new ArrayList(constructors.size());
final LookupElement[] suggestedInitializers = AddVariableInitializerFix.suggestInitializer(field);
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportConstantFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportConstantFix.java
new file mode 100644
index 000000000000..2f5229b06fc9
--- /dev/null
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportConstantFix.java
@@ -0,0 +1,102 @@
+/*
+ * 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.daemon.impl.quickfix;
+
+import com.intellij.codeInsight.daemon.QuickFixBundle;
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.project.Project;
+import com.intellij.psi.*;
+import com.intellij.psi.search.PsiShortNamesCache;
+import com.intellij.psi.util.PsiFormatUtil;
+import com.intellij.psi.util.PsiFormatUtilBase;
+import com.intellij.psi.util.TypeConversionUtil;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.Collections;
+import java.util.List;
+
+public class StaticImportConstantFix extends StaticImportMemberFix {
+ private final SmartPsiElementPointer myRef;
+
+ public StaticImportConstantFix(@NotNull PsiJavaCodeReferenceElement referenceElement) {
+ myRef = SmartPointerManager.getInstance(referenceElement.getProject()).createSmartPsiElementPointer(referenceElement);
+ }
+
+ @NotNull
+ @Override
+ protected String getBaseText() {
+ return "Static import constant";
+ }
+
+ @NotNull
+ @Override
+ protected String getMemberPresentableText(PsiField field) {
+ return PsiFormatUtil.formatVariable(field, PsiFormatUtilBase.SHOW_NAME |
+ PsiFormatUtilBase.SHOW_CONTAINING_CLASS |
+ PsiFormatUtilBase.SHOW_FQ_NAME, PsiSubstitutor.EMPTY);
+ }
+
+ @NotNull
+ @Override
+ protected List getMembersToImport(boolean applicableOnly) {
+ final Project project = myRef.getProject();
+ PsiShortNamesCache cache = PsiShortNamesCache.getInstance(project);
+ final PsiJavaCodeReferenceElement element = myRef.getElement();
+ String name = element != null ? element.getReferenceName() : null;
+ if (name == null) return Collections.emptyList();
+ final StaticMembersProcessor processor = new StaticMembersProcessor(element) {
+ @Override
+ protected boolean isApplicable(PsiField field, PsiElement place) {
+ final PsiType expectedType = getExpectedType();
+ return expectedType == null || TypeConversionUtil.isAssignable(expectedType, field.getType());
+ }
+ };
+ cache.processFieldsWithName(name, processor, element.getResolveScope(), null);
+ return processor.getMembersToImport(applicableOnly);
+ }
+
+ @NotNull
+ protected StaticImportMethodQuestionAction createQuestionAction(List methodsToImport, @NotNull Project project, Editor editor) {
+ return new StaticImportMethodQuestionAction(project, editor, methodsToImport, myRef) {
+ @NotNull
+ @Override
+ protected String getPopupTitle() {
+ return QuickFixBundle.message("field.to.import.chooser.title");
+ }
+ };
+ }
+
+ @Nullable
+ @Override
+ protected PsiElement getElement() {
+ return myRef.getElement();
+ }
+
+ @Nullable
+ @Override
+ protected PsiElement getQualifierExpression() {
+ final PsiJavaCodeReferenceElement element = myRef.getElement();
+ return element != null ? element.getQualifier() : null;
+ }
+
+ @Nullable
+ @Override
+ protected PsiElement resolveRef() {
+ final PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement)getElement();
+ return referenceElement != null ? referenceElement.resolve() : null;
+ }
+}
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportMemberFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportMemberFix.java
new file mode 100644
index 000000000000..c8e86410d662
--- /dev/null
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportMemberFix.java
@@ -0,0 +1,160 @@
+/*
+ * 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.daemon.impl.quickfix;
+
+import com.intellij.codeInsight.CodeInsightSettings;
+import com.intellij.codeInsight.FileModificationService;
+import com.intellij.codeInsight.daemon.impl.DaemonListeners;
+import com.intellij.codeInsight.daemon.impl.ShowAutoImportPass;
+import com.intellij.codeInsight.hint.HintManager;
+import com.intellij.codeInsight.hint.QuestionAction;
+import com.intellij.codeInsight.intention.IntentionAction;
+import com.intellij.codeInspection.HintAction;
+import com.intellij.lang.java.JavaLanguage;
+import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.application.impl.LaterInvocator;
+import com.intellij.openapi.command.CommandProcessor;
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.TextRange;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiFile;
+import com.intellij.psi.PsiMember;
+import com.intellij.psi.util.FileTypeUtils;
+import com.intellij.psi.util.PsiUtil;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.List;
+
+public abstract class StaticImportMemberFix implements IntentionAction, HintAction {
+ private List candidates;
+
+ @NotNull protected abstract String getBaseText();
+ @NotNull protected abstract String getMemberPresentableText(T t);
+
+ @Override
+ @NotNull
+ public String getText() {
+ String text = getBaseText();
+ if (candidates != null && candidates.size() == 1) {
+ text += " '" + getMemberPresentableText(candidates.get(0)) + "'";
+ }
+ else {
+ text += "...";
+ }
+ return text;
+ }
+
+ @Override
+ @NotNull
+ public String getFamilyName() {
+ return getText();
+ }
+
+ @Override
+ public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
+ return PsiUtil.isLanguageLevel5OrHigher(file)
+ && file.getLanguage().isKindOf(JavaLanguage.INSTANCE)
+ && getElement() != null
+ && getElement().isValid()
+ && getQualifierExpression() == null
+ && resolveRef() == null
+ && file.getManager().isInProject(file)
+ && !(candidates == null ? candidates = getMembersToImport(false) : candidates).isEmpty()
+ ;
+ }
+
+ @NotNull protected abstract List getMembersToImport(boolean applicableOnly);
+ @NotNull protected abstract QuestionAction createQuestionAction(List methodsToImport, @NotNull Project project, Editor editor);
+
+ @Nullable protected abstract PsiElement getElement();
+ @Nullable protected abstract PsiElement getQualifierExpression();
+ @Nullable protected abstract PsiElement resolveRef();
+
+ @Override
+ public void invoke(@NotNull final Project project, final Editor editor, PsiFile file) {
+ if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;
+ ApplicationManager.getApplication().runWriteAction(new Runnable() {
+ @Override
+ public void run() {
+ final List methodsToImport = getMembersToImport(false);
+ if (methodsToImport.isEmpty()) return;
+ createQuestionAction(methodsToImport, project, editor).execute();
+ }
+ });
+ }
+
+ private ImportClassFixBase.Result doFix(Editor editor) {
+ if (!CodeInsightSettings.getInstance().ADD_MEMBER_IMPORTS_ON_THE_FLY) {
+ return ImportClassFixBase.Result.POPUP_NOT_SHOWN;
+ }
+ final List candidates = getMembersToImport(true);
+ if (candidates.isEmpty()) {
+ return ImportClassFixBase.Result.POPUP_NOT_SHOWN;
+ }
+
+ final PsiElement element = getElement();
+ if (element == null) {
+ return ImportClassFixBase.Result.POPUP_NOT_SHOWN;
+ }
+
+ final QuestionAction action = createQuestionAction(candidates, element.getProject(), editor);
+ PsiFile psiFile = element.getContainingFile();
+ if (candidates.size() == 1 &&
+ (FileTypeUtils.isInServerPageFile(psiFile) ?
+ CodeInsightSettings.getInstance().JSP_ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY :
+ CodeInsightSettings.getInstance().ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY) &&
+ (ApplicationManager.getApplication().isUnitTestMode() || DaemonListeners.canChangeFileSilently(psiFile)) &&
+ !LaterInvocator.isInModalContext()) {
+ CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
+ @Override
+ public void run() {
+ action.execute();
+ }
+ });
+ return ImportClassFixBase.Result.CLASS_AUTO_IMPORTED;
+ }
+
+ String hintText = ShowAutoImportPass.getMessage(candidates.size() > 1, getMemberPresentableText(candidates.get(0)));
+ if (!ApplicationManager.getApplication().isUnitTestMode() && !HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true)) {
+ final TextRange textRange = element.getTextRange();
+ HintManager.getInstance().showQuestionHint(editor, hintText,
+ textRange.getStartOffset(),
+ textRange.getEndOffset(), action);
+ }
+ return ImportClassFixBase.Result.POPUP_SHOWN;
+ }
+
+
+
+ @Override
+ public boolean startInWriteAction() {
+ return false;
+ }
+
+ @Override
+ public boolean showHint(@NotNull Editor editor) {
+ final PsiElement callExpression = getElement();
+ if (callExpression == null ||
+ getQualifierExpression() != null) {
+ return false;
+ }
+ ImportClassFixBase.Result result = doFix(editor);
+ return result == ImportClassFixBase.Result.POPUP_SHOWN || result == ImportClassFixBase.Result.CLASS_AUTO_IMPORTED;
+ }
+
+}
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportMethodFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportMethodFix.java
index 79e2f69eee20..e0b847c7b4d2 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportMethodFix.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportMethodFix.java
@@ -15,245 +15,56 @@
*/
package com.intellij.codeInsight.daemon.impl.quickfix;
-import com.intellij.codeInsight.FileModificationService;
import com.intellij.codeInsight.JavaProjectCodeInsightSettings;
-import com.intellij.codeInsight.completion.JavaCompletionUtil;
import com.intellij.codeInsight.daemon.QuickFixBundle;
-import com.intellij.codeInsight.daemon.impl.ShowAutoImportPass;
-import com.intellij.codeInsight.hint.HintManager;
-import com.intellij.codeInsight.intention.IntentionAction;
-import com.intellij.codeInspection.HintAction;
-import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.command.CommandProcessor;
-import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
-import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
-import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.DefaultParameterTypeInferencePolicy;
-import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiShortNamesCache;
-import com.intellij.psi.util.*;
-import com.intellij.psi.util.proximity.PsiProximityComparator;
-import com.intellij.util.ArrayUtilRt;
-import com.intellij.util.Processor;
-import com.intellij.util.containers.LinkedMultiMap;
-import com.intellij.util.containers.MultiMap;
+import com.intellij.psi.util.PsiFormatUtil;
+import com.intellij.psi.util.PsiFormatUtilBase;
+import com.intellij.psi.util.PsiUtil;
+import com.intellij.psi.util.TypeConversionUtil;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
-import java.util.*;
+import java.util.Collections;
+import java.util.List;
-public class StaticImportMethodFix implements IntentionAction, HintAction {
- private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.StaticImportMethodFix");
+public class StaticImportMethodFix extends StaticImportMemberFix {
private final SmartPsiElementPointer myMethodCall;
- private List candidates;
public StaticImportMethodFix(@NotNull PsiMethodCallExpression methodCallExpression) {
myMethodCall = SmartPointerManager.getInstance(methodCallExpression.getProject()).createSmartPsiElementPointer(methodCallExpression);
}
+ @NotNull
@Override
- @NotNull
- public String getText() {
- String text = QuickFixBundle.message("static.import.method.text");
- if (candidates != null && candidates.size() == 1) {
- text += " '" + getMethodPresentableText() + "'";
- }
- else {
- text += "...";
- }
- return text;
+ protected String getBaseText() {
+ return QuickFixBundle.message("static.import.method.text");
}
@NotNull
- private String getMethodPresentableText() {
- return PsiFormatUtil.formatMethod(candidates.get(0), PsiSubstitutor.EMPTY, PsiFormatUtilBase.SHOW_NAME |
- PsiFormatUtilBase.SHOW_CONTAINING_CLASS |
- PsiFormatUtilBase.SHOW_FQ_NAME, 0);
- }
-
@Override
- @NotNull
- public String getFamilyName() {
- return getText();
+ protected String getMemberPresentableText(PsiMethod method) {
+ return PsiFormatUtil.formatMethod(method, PsiSubstitutor.EMPTY, PsiFormatUtilBase.SHOW_NAME |
+ PsiFormatUtilBase.SHOW_CONTAINING_CLASS |
+ PsiFormatUtilBase.SHOW_FQ_NAME, 0);
}
+ @NotNull
@Override
- public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
- return PsiUtil.isLanguageLevel5OrHigher(file)
- && file instanceof PsiJavaFile
- && myMethodCall.getElement() != null
- && myMethodCall.getElement().isValid()
- && myMethodCall.getElement().getMethodExpression().getQualifierExpression() == null
- && myMethodCall.getElement().resolveMethod() == null
- && file.getManager().isInProject(file)
- && !(candidates == null ? candidates = getMethodsToImport() : candidates).isEmpty()
- ;
- }
-
- private PsiType getExpectedType() {
- final PsiMethodCallExpression methodCall = myMethodCall.getElement();
- if (methodCall == null) return null;
- final PsiElement parent = PsiUtil.skipParenthesizedExprUp(methodCall.getParent());
-
- if (parent instanceof PsiVariable) {
- if (methodCall.equals(PsiUtil.skipParenthesizedExprDown(((PsiVariable)parent).getInitializer()))) {
- return ((PsiVariable)parent).getType();
- }
- }
- else if (parent instanceof PsiAssignmentExpression) {
- if (methodCall.equals(PsiUtil.skipParenthesizedExprDown(((PsiAssignmentExpression)parent).getRExpression()))) {
- return ((PsiAssignmentExpression)parent).getLExpression().getType();
- }
- }
- else if (parent instanceof PsiReturnStatement) {
- final PsiElement psiElement = PsiTreeUtil.getParentOfType(parent, PsiLambdaExpression.class, PsiMethod.class);
- if (psiElement instanceof PsiLambdaExpression) {
- return LambdaUtil.getFunctionalInterfaceReturnType(((PsiLambdaExpression)psiElement).getFunctionalInterfaceType());
- }
- else if (psiElement instanceof PsiMethod) {
- return ((PsiMethod)psiElement).getReturnType();
- }
- }
- else if (parent instanceof PsiExpressionList) {
- final PsiElement pParent = parent.getParent();
- if (pParent instanceof PsiCallExpression && parent.equals(((PsiCallExpression)pParent).getArgumentList())) {
- final JavaResolveResult resolveResult = ((PsiCallExpression)pParent).resolveMethodGenerics();
- final PsiElement psiElement = resolveResult.getElement();
- if (psiElement instanceof PsiMethod) {
- final PsiMethod psiMethod = (PsiMethod)psiElement;
- final PsiParameter[] parameters = psiMethod.getParameterList().getParameters();
- final int idx = ArrayUtilRt.find(((PsiExpressionList)parent).getExpressions(), PsiUtil.skipParenthesizedExprUp(methodCall));
- if (idx > -1 && parameters.length > 0) {
- PsiType parameterType = parameters[Math.min(idx, parameters.length - 1)].getType();
- if (idx >= parameters.length - 1) {
- final PsiParameter lastParameter = parameters[parameters.length - 1];
- if (lastParameter.isVarArgs()) {
- parameterType = ((PsiEllipsisType)lastParameter.getType()).getComponentType();
- }
- }
- return resolveResult.getSubstitutor().substitute(parameterType);
- }
- else {
- return null;
- }
- }
- }
- }
- else if (parent instanceof PsiLambdaExpression) {
- return LambdaUtil.getFunctionalInterfaceReturnType(((PsiLambdaExpression)parent).getFunctionalInterfaceType());
- }
- return null;
- }
-
- @NotNull
- private List getMethodsToImport() {
+ protected List getMembersToImport(boolean applicableOnly) {
final Project project = myMethodCall.getProject();
PsiShortNamesCache cache = PsiShortNamesCache.getInstance(project);
final PsiMethodCallExpression element = myMethodCall.getElement();
- PsiReferenceExpression reference = element.getMethodExpression();
- final PsiExpressionList argumentList = element.getArgumentList();
- String name = reference.getReferenceName();
- final List list = new ArrayList();
- if (name == null) return list;
- GlobalSearchScope scope = element.getResolveScope();
- final Map possibleClasses = new HashMap();
- final PsiType expectedType = getExpectedType();
- final List applicableList = new ArrayList();
- final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(project).getResolveHelper();
-
- final MultiMap deprecated = new LinkedMultiMap();
- final MultiMap suggestions = new LinkedMultiMap();
- class RegisterMethodsProcessor {
- private void registerMethod(PsiClass containingClass, Collection methods) {
- final Boolean alreadyMentioned = possibleClasses.get(containingClass);
- if (alreadyMentioned == Boolean.TRUE) return;
- if (alreadyMentioned == null) {
- if (!methods.isEmpty()) {
- list.add(methods.iterator().next());
- }
- possibleClasses.put(containingClass, false);
- }
- for (PsiMethod method : methods) {
- if (!PsiUtil.isAccessible(project, method, element, containingClass)) {
- continue;
- }
- PsiSubstitutor substitutorForMethod = resolveHelper
- .inferTypeArguments(method.getTypeParameters(), method.getParameterList().getParameters(),
- argumentList.getExpressions(),
- PsiSubstitutor.EMPTY, element.getParent(), DefaultParameterTypeInferencePolicy.INSTANCE);
- if (PsiUtil.isApplicable(method, substitutorForMethod, argumentList)) {
- final PsiType returnType = substitutorForMethod.substitute(method.getReturnType());
- if (expectedType == null || returnType == null || TypeConversionUtil.isAssignable(expectedType, returnType)) {
- applicableList.add(method);
- possibleClasses.put(containingClass, true);
- break;
- }
- }
- }
- }
- }
-
- final RegisterMethodsProcessor registrar = new RegisterMethodsProcessor();
- cache.processMethodsWithName(name, scope, new Processor() {
- @Override
- public boolean process(PsiMethod method) {
- ProgressManager.checkCanceled();
- if (JavaCompletionUtil.isInExcludedPackage(method, false)
- || !method.hasModifierProperty(PsiModifier.STATIC)) return true;
- PsiFile file = method.getContainingFile();
- final PsiClass containingClass = method.getContainingClass();
- if (file instanceof PsiJavaFile
- //do not show methods from default package
- && !((PsiJavaFile)file).getPackageName().isEmpty()) {
- if (isEffectivelyDeprecated(method)) {
- deprecated.putValue(containingClass, method);
- return processCondition();
- }
- suggestions.putValue(containingClass, method);
- }
- return processCondition();
- }
-
- private boolean isEffectivelyDeprecated(PsiMethod method) {
- if (method.isDeprecated()) {
- return true;
- }
- PsiClass aClass = method.getContainingClass();
- while (aClass != null) {
- if (aClass.isDeprecated()) {
- return true;
- }
- aClass = aClass.getContainingClass();
- }
- return false;
- }
-
- private boolean processCondition() {
- return suggestions.size() + deprecated.size() < 50;
- }
- });
-
- for (Map.Entry> methodEntry : suggestions.entrySet()) {
- registrar.registerMethod(methodEntry.getKey(), methodEntry.getValue());
- }
-
- for (Map.Entry> deprecatedMethod : deprecated.entrySet()) {
- registrar.registerMethod(deprecatedMethod.getKey(), deprecatedMethod.getValue());
- }
-
- List result = applicableList.isEmpty() ? list : applicableList;
- for (int i = result.size() - 1; i >= 0; i--) {
- ProgressManager.checkCanceled();
- PsiMethod method = result.get(i);
- // check for manually excluded
- if (isExcluded(method)) {
- result.remove(i);
- }
- }
- Collections.sort(result, new PsiProximityComparator(argumentList));
- return result;
+ PsiReferenceExpression reference = element == null ? null : element.getMethodExpression();
+ String name = reference == null ? null : reference.getReferenceName();
+ if (name == null) return Collections.emptyList();
+ final StaticMembersProcessor processor = new MyStaticMethodProcessor(element);
+ cache.processMethodsWithName(name, element.getResolveScope(), processor);
+ return processor.getMembersToImport(applicableOnly);
}
public static boolean isExcluded(PsiMember method) {
@@ -261,68 +72,51 @@ public class StaticImportMethodFix implements IntentionAction, HintAction {
return name != null && JavaProjectCodeInsightSettings.getSettings(method.getProject()).isExcluded(name);
}
- @Override
- public void invoke(@NotNull final Project project, final Editor editor, PsiFile file) {
- if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;
- ApplicationManager.getApplication().runWriteAction(new Runnable() {
- @Override
- public void run() {
- final List methodsToImport = getMethodsToImport();
- if (methodsToImport.isEmpty()) return;
- createQuestionAction(methodsToImport, project, editor).execute();
- }
- });
- }
-
@NotNull
- private StaticImportMethodQuestionAction createQuestionAction(List methodsToImport, @NotNull Project project, Editor editor) {
- return new StaticImportMethodQuestionAction(project, editor, methodsToImport, myMethodCall);
+ protected StaticImportMethodQuestionAction createQuestionAction(List methodsToImport, @NotNull Project project, Editor editor) {
+ return new StaticImportMethodQuestionAction(project, editor, methodsToImport, myMethodCall);
}
- private ImportClassFixBase.Result doFix(Editor editor) {
- if (candidates.isEmpty()) {
- return ImportClassFixBase.Result.POPUP_NOT_SHOWN;
- }
-
- final StaticImportMethodQuestionAction action = createQuestionAction(candidates, myMethodCall.getProject(), editor);
+ @Nullable
+ @Override
+ protected PsiElement getElement() {
+ return myMethodCall.getElement();
+ }
+ @Nullable
+ @Override
+ protected PsiElement getQualifierExpression() {
final PsiMethodCallExpression element = myMethodCall.getElement();
- if (element == null) {
- return ImportClassFixBase.Result.POPUP_NOT_SHOWN;
- }
-
- if (candidates.size() == 1 && ImportClassFixBase.canAddUnambiguousImport(element.getContainingFile())) {
- CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
- @Override
- public void run() {
- action.execute();
- }
- });
- return ImportClassFixBase.Result.CLASS_AUTO_IMPORTED;
- }
-
- String hintText = ShowAutoImportPass.getMessage(candidates.size() > 1, getMethodPresentableText());
- if (!ApplicationManager.getApplication().isUnitTestMode() && !HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true)) {
- final TextRange textRange = element.getTextRange();
- HintManager.getInstance().showQuestionHint(editor, hintText,
- textRange.getStartOffset(),
- textRange.getEndOffset(), action);
- }
- return ImportClassFixBase.Result.POPUP_SHOWN;
+ return element != null ? element.getMethodExpression().getQualifierExpression() : null;
}
+ @Nullable
@Override
- public boolean startInWriteAction() {
- return false;
+ protected PsiElement resolveRef() {
+ final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)getElement();
+ return methodCallExpression != null ? methodCallExpression.resolveMethod() : null;
}
- @Override
- public boolean showHint(@NotNull Editor editor) {
- final PsiMethodCallExpression callExpression = myMethodCall.getElement();
- if (callExpression == null || callExpression.getMethodExpression().getQualifierExpression() != null) {
+ private static class MyStaticMethodProcessor extends StaticMembersProcessor {
+
+ private MyStaticMethodProcessor(PsiMethodCallExpression place) {
+ super(place);
+ }
+
+ @Override
+ protected boolean isApplicable(PsiMethod method, PsiElement place) {
+ final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(place.getProject()).getResolveHelper();
+ final PsiExpressionList argumentList = ((PsiMethodCallExpression)place).getArgumentList();
+ PsiSubstitutor substitutorForMethod = resolveHelper
+ .inferTypeArguments(method.getTypeParameters(), method.getParameterList().getParameters(),
+ argumentList.getExpressions(),
+ PsiSubstitutor.EMPTY, place.getParent(), DefaultParameterTypeInferencePolicy.INSTANCE);
+ if (PsiUtil.isApplicable(method, substitutorForMethod, argumentList)) {
+ final PsiType returnType = substitutorForMethod.substitute(method.getReturnType());
+ final PsiType expectedType = getExpectedType();
+ return expectedType == null || returnType == null || TypeConversionUtil.isAssignable(expectedType, returnType);
+ }
return false;
}
- ImportClassFixBase.Result result = doFix(editor);
- return result == ImportClassFixBase.Result.POPUP_SHOWN || result == ImportClassFixBase.Result.CLASS_AUTO_IMPORTED;
}
}
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportMethodQuestionAction.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportMethodQuestionAction.java
index 4f83e31e79ed..5a6bf7d635ad 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportMethodQuestionAction.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportMethodQuestionAction.java
@@ -19,7 +19,8 @@ import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.daemon.impl.actions.AddImportAction;
import com.intellij.codeInsight.hint.QuestionAction;
import com.intellij.codeInsight.intention.impl.AddSingleMemberStaticImportAction;
-import com.intellij.ide.util.MethodCellRenderer;
+import com.intellij.ide.util.PsiClassListCellRenderer;
+import com.intellij.ide.util.PsiElementListCellRenderer;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
@@ -29,7 +30,7 @@ import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.PopupStep;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.psi.*;
-import com.intellij.psi.util.PsiFormatUtilBase;
+import com.intellij.psi.presentation.java.ClassPresentationUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.ui.popup.list.ListPopupImpl;
import com.intellij.ui.popup.list.PopupListElementRenderer;
@@ -42,33 +43,38 @@ import javax.swing.*;
import java.awt.*;
import java.util.List;
-public class StaticImportMethodQuestionAction implements QuestionAction {
+public class StaticImportMethodQuestionAction implements QuestionAction {
private static final Logger LOG = Logger.getInstance("#" + StaticImportMethodQuestionAction.class.getName());
private final Project myProject;
private final Editor myEditor;
- private List myCandidates;
- private final SmartPsiElementPointer myMethodCall;
+ private List myCandidates;
+ private final SmartPsiElementPointer extends PsiElement> myRef;
public StaticImportMethodQuestionAction(Project project,
Editor editor,
- List candidates,
- SmartPsiElementPointer methodCall) {
+ List candidates,
+ SmartPsiElementPointer extends PsiElement> ref) {
myProject = project;
myEditor = editor;
myCandidates = candidates;
- myMethodCall = methodCall;
+ myRef = ref;
+ }
+
+ @NotNull
+ protected String getPopupTitle() {
+ return QuickFixBundle.message("method.to.import.chooser.title");
}
@Override
public boolean execute() {
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
- final PsiMethodCallExpression element = myMethodCall.getElement();
+ final PsiElement element = myRef.getElement();
if (element == null || !element.isValid()){
return false;
}
- for (PsiMethod targetMethod : myCandidates) {
+ for (T targetMethod : myCandidates) {
if (!targetMethod.isValid()) {
return false;
}
@@ -83,7 +89,7 @@ public class StaticImportMethodQuestionAction implements QuestionAction {
return true;
}
- private void doImport(final PsiMethod toImport) {
+ private void doImport(final T toImport) {
final Project project = toImport.getProject();
CommandProcessor.getInstance().executeCommand(project, new Runnable(){
@Override
@@ -92,7 +98,7 @@ public class StaticImportMethodQuestionAction implements QuestionAction {
@Override
public void run() {
try {
- PsiMethodCallExpression element = myMethodCall.getElement();
+ PsiElement element = myRef.getElement();
if (element != null) {
AddSingleMemberStaticImportAction.bindAllClassRefs(element.getContainingFile(), toImport, toImport.getName(), toImport.getContainingClass());
}
@@ -113,11 +119,11 @@ public class StaticImportMethodQuestionAction implements QuestionAction {
doImport(myCandidates.get(0));
return;
}
- final BaseListPopupStep step =
- new BaseListPopupStep(QuickFixBundle.message("method.to.import.chooser.title"), myCandidates) {
+ final BaseListPopupStep step =
+ new BaseListPopupStep(getPopupTitle(), myCandidates) {
@Override
- public PopupStep onChosen(PsiMethod selectedValue, boolean finalChoice) {
+ public PopupStep onChosen(T selectedValue, boolean finalChoice) {
if (selectedValue == null) {
return FINAL_CHOICE;
}
@@ -129,40 +135,22 @@ public class StaticImportMethodQuestionAction implements QuestionAction {
return FINAL_CHOICE;
}
- String qname = PsiUtil.getMemberQualifiedName(selectedValue);
- if (qname == null) return FINAL_CHOICE;
- List excludableStrings = AddImportAction.getAllExcludableStrings(qname);
- return new BaseListPopupStep(null, excludableStrings) {
- @NotNull
- @Override
- public String getTextFor(String value) {
- return "Exclude '" + value + "' from auto-import";
- }
-
- @Override
- public PopupStep onChosen(String selectedValue, boolean finalChoice) {
- if (finalChoice) {
- AddImportAction.excludeFromImport(project, selectedValue);
- }
-
- return super.onChosen(selectedValue, finalChoice);
- }
- };
+ return AddImportAction.getExcludesStep(PsiUtil.getMemberQualifiedName(selectedValue), project);
}
@Override
- public boolean hasSubstep(PsiMethod selectedValue) {
+ public boolean hasSubstep(T selectedValue) {
return true;
}
@NotNull
@Override
- public String getTextFor(PsiMethod value) {
+ public String getTextFor(T value) {
return ObjectUtils.assertNotNull(value.getName());
}
@Override
- public Icon getIconFor(PsiMethod aValue) {
+ public Icon getIconFor(T aValue) {
return aValue.getIcon(0);
}
};
@@ -171,14 +159,27 @@ public class StaticImportMethodQuestionAction implements QuestionAction {
final PopupListElementRenderer rightArrow = new PopupListElementRenderer(this);
@Override
protected ListCellRenderer getListElementRenderer() {
- return new MethodCellRenderer(true, PsiFormatUtilBase.SHOW_NAME){
+ return new PsiElementListCellRenderer() {
+ public String getElementText(T element) {
+ final PsiClass aClass = element.getContainingClass();
+ LOG.assertTrue(aClass != null);
+ return ClassPresentationUtil.getNameForClass(aClass, false) + "." + element.getName();
+ }
+
+ public String getContainerText(final T element, final String name) {
+ return PsiClassListCellRenderer.getContainerTextStatic(element);
+ }
+
+ public int getIconFlags() {
+ return 0;
+ }
@Nullable
@Override
protected TextAttributes getNavigationItemAttributes(Object value) {
TextAttributes attrs = super.getNavigationItemAttributes(value);
- if (value instanceof PsiMethod && !((PsiMethod)value).isDeprecated()) {
- PsiClass psiClass = ((PsiMethod)value).getContainingClass();
+ if (value instanceof PsiDocCommentOwner && !((PsiDocCommentOwner)value).isDeprecated()) {
+ PsiClass psiClass = ((T)value).getContainingClass();
if (psiClass != null && psiClass.isDeprecated()) {
return TextAttributes.merge(attrs, super.getNavigationItemAttributes(psiClass));
}
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticMembersProcessor.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticMembersProcessor.java
new file mode 100644
index 000000000000..d7fbbe0d7315
--- /dev/null
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticMembersProcessor.java
@@ -0,0 +1,182 @@
+/*
+ * 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.daemon.impl.quickfix;
+
+import com.intellij.codeInsight.completion.JavaCompletionUtil;
+import com.intellij.openapi.progress.ProgressManager;
+import com.intellij.psi.*;
+import com.intellij.psi.util.PsiTreeUtil;
+import com.intellij.psi.util.PsiUtil;
+import com.intellij.psi.util.proximity.PsiProximityComparator;
+import com.intellij.util.ArrayUtilRt;
+import com.intellij.util.Processor;
+import com.intellij.util.containers.LinkedMultiMap;
+import com.intellij.util.containers.MultiMap;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.*;
+
+abstract class StaticMembersProcessor implements Processor {
+ private final MultiMap myDeprecated = new LinkedMultiMap();
+ private final MultiMap mySuggestions = new LinkedMultiMap();
+
+ private final Map myPossibleClasses = new HashMap();
+
+ private final PsiElement myPlace;
+ private PsiType myExpectedType;
+
+ protected StaticMembersProcessor(PsiElement place) {
+ myPlace = place;
+ myExpectedType = PsiType.NULL;
+ }
+
+ protected abstract boolean isApplicable(T member, PsiElement place);
+
+ @NotNull
+ public List getMembersToImport(boolean applicableOnly) {
+ final List list = new ArrayList();
+ final List applicableList = new ArrayList();
+ for (Map.Entry> methodEntry : mySuggestions.entrySet()) {
+ registerMember(methodEntry.getKey(), methodEntry.getValue(), list, applicableList);
+ }
+
+ for (Map.Entry> deprecatedMethod : myDeprecated.entrySet()) {
+ registerMember(deprecatedMethod.getKey(), deprecatedMethod.getValue(), list, applicableList);
+ }
+
+ List result = !applicableOnly && applicableList.isEmpty() ? list : applicableList;
+ for (int i = result.size() - 1; i >= 0; i--) {
+ ProgressManager.checkCanceled();
+ T method = result.get(i);
+ // check for manually excluded
+ if (StaticImportMethodFix.isExcluded(method)) {
+ result.remove(i);
+ }
+ }
+ Collections.sort(result, new PsiProximityComparator(myPlace));
+ return result;
+ }
+
+ public PsiType getExpectedType() {
+ if (myExpectedType == PsiType.NULL) {
+ myExpectedType = getExpectedTypeInternal();
+ }
+ return myExpectedType;
+ }
+
+ private PsiType getExpectedTypeInternal() {
+ if (myPlace == null) return null;
+ final PsiElement parent = PsiUtil.skipParenthesizedExprUp(myPlace.getParent());
+
+ if (parent instanceof PsiVariable) {
+ if (myPlace.equals(PsiUtil.skipParenthesizedExprDown(((PsiVariable)parent).getInitializer()))) {
+ return ((PsiVariable)parent).getType();
+ }
+ }
+ else if (parent instanceof PsiAssignmentExpression) {
+ if (myPlace.equals(PsiUtil.skipParenthesizedExprDown(((PsiAssignmentExpression)parent).getRExpression()))) {
+ return ((PsiAssignmentExpression)parent).getLExpression().getType();
+ }
+ }
+ else if (parent instanceof PsiReturnStatement) {
+ final PsiElement psiElement = PsiTreeUtil.getParentOfType(parent, PsiLambdaExpression.class, PsiMethod.class);
+ if (psiElement instanceof PsiLambdaExpression) {
+ return LambdaUtil.getFunctionalInterfaceReturnType(((PsiLambdaExpression)psiElement).getFunctionalInterfaceType());
+ }
+ else if (psiElement instanceof PsiMethod) {
+ return ((PsiMethod)psiElement).getReturnType();
+ }
+ }
+ else if (parent instanceof PsiExpressionList) {
+ final PsiElement pParent = parent.getParent();
+ if (pParent instanceof PsiCallExpression && parent.equals(((PsiCallExpression)pParent).getArgumentList())) {
+ final JavaResolveResult resolveResult = ((PsiCallExpression)pParent).resolveMethodGenerics();
+ final PsiElement psiElement = resolveResult.getElement();
+ if (psiElement instanceof PsiMethod) {
+ final PsiMethod psiMethod = (PsiMethod)psiElement;
+ final PsiParameter[] parameters = psiMethod.getParameterList().getParameters();
+ final int idx = ArrayUtilRt.find(((PsiExpressionList)parent).getExpressions(), PsiUtil.skipParenthesizedExprUp(myPlace));
+ if (idx > -1 && parameters.length > 0) {
+ PsiType parameterType = parameters[Math.min(idx, parameters.length - 1)].getType();
+ if (idx >= parameters.length - 1) {
+ final PsiParameter lastParameter = parameters[parameters.length - 1];
+ if (lastParameter.isVarArgs()) {
+ parameterType = ((PsiEllipsisType)lastParameter.getType()).getComponentType();
+ }
+ }
+ return resolveResult.getSubstitutor().substitute(parameterType);
+ }
+ else {
+ return null;
+ }
+ }
+ }
+ }
+ else if (parent instanceof PsiLambdaExpression) {
+ return LambdaUtil.getFunctionalInterfaceReturnType(((PsiLambdaExpression)parent).getFunctionalInterfaceType());
+ }
+ return null;
+ }
+
+ @Override
+ public boolean process(T member) {
+ ProgressManager.checkCanceled();
+ if (JavaCompletionUtil.isInExcludedPackage(member, false) || !member.hasModifierProperty(PsiModifier.STATIC)) return true;
+ PsiFile file = member.getContainingFile();
+ final PsiClass containingClass = member.getContainingClass();
+ if (file instanceof PsiJavaFile
+ //do not show methods from default package
+ && !((PsiJavaFile)file).getPackageName().isEmpty()) {
+ if (JavaCompletionUtil.isEffectivelyDeprecated((PsiDocCommentOwner)member)) {
+ myDeprecated.putValue(containingClass, member);
+ return processCondition();
+ }
+ mySuggestions.putValue(containingClass, member);
+ }
+ return processCondition();
+ }
+
+ private boolean processCondition() {
+ return mySuggestions.size() + myDeprecated.size() < 50;
+ }
+
+ private void registerMember(PsiClass containingClass,
+ Collection members,
+ List list,
+ List applicableList) {
+ final Boolean alreadyMentioned = myPossibleClasses.get(containingClass);
+ if (alreadyMentioned == Boolean.TRUE) return;
+ if (containingClass.getQualifiedName() == null) {
+ return;
+ }
+ if (alreadyMentioned == null) {
+ if (!members.isEmpty()) {
+ list.add(members.iterator().next());
+ }
+ myPossibleClasses.put(containingClass, false);
+ }
+ for (T member : members) {
+ if (!PsiUtil.isAccessible(myPlace.getProject(), member, myPlace, containingClass)) {
+ continue;
+ }
+ if (isApplicable(member, myPlace)) {
+ applicableList.add(member);
+ myPossibleClasses.put(containingClass, true);
+ break;
+ }
+ }
+ }
+}
diff --git a/java/java-impl/src/com/intellij/codeInsight/editorActions/AutoFormatTypedHandler.java b/java/java-impl/src/com/intellij/codeInsight/editorActions/AutoFormatTypedHandler.java
new file mode 100644
index 000000000000..0e2a3de30933
--- /dev/null
+++ b/java/java-impl/src/com/intellij/codeInsight/editorActions/AutoFormatTypedHandler.java
@@ -0,0 +1,195 @@
+/*
+ * 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.editorActions;
+
+import com.intellij.codeInsight.template.impl.editorActions.TypedActionHandlerBase;
+import com.intellij.lang.Language;
+import com.intellij.lang.java.JavaLanguage;
+import com.intellij.openapi.actionSystem.CommonDataKeys;
+import com.intellij.openapi.actionSystem.DataContext;
+import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.editor.EditorModificationUtil;
+import com.intellij.openapi.editor.actionSystem.TypedActionHandler;
+import com.intellij.openapi.editor.ex.EditorEx;
+import com.intellij.openapi.editor.highlighter.HighlighterIterator;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.registry.Registry;
+import com.intellij.psi.JavaTokenType;
+import com.intellij.psi.PsiDocumentManager;
+import com.intellij.psi.PsiFile;
+import com.intellij.psi.TokenType;
+import com.intellij.psi.codeStyle.CodeStyleSettings;
+import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
+import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
+import com.intellij.psi.tree.IElementType;
+import com.intellij.psi.util.PsiUtilBase;
+import com.intellij.util.containers.ContainerUtil;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.annotations.TestOnly;
+
+import java.util.List;
+
+public class AutoFormatTypedHandler extends TypedActionHandlerBase {
+ private static boolean myIsEnabledInTests = false;
+
+ private static char[] NO_SPACE_AFTER = {
+ '+', '-', '*', '/', '%', '&', '^', '|', '<', '>', '!', '=', ' '
+ };
+
+ private static final List COMPLEX_ASSIGNMENTS = ContainerUtil.newArrayList(
+ JavaTokenType.PLUSEQ, JavaTokenType.MINUSEQ,
+ JavaTokenType.ASTERISKEQ, JavaTokenType.DIVEQ,
+ JavaTokenType.PERCEQ,
+ JavaTokenType.ANDEQ, JavaTokenType.XOREQ, JavaTokenType.OREQ,
+ JavaTokenType.LTLTEQ, JavaTokenType.GTGTEQ
+ );
+
+ public AutoFormatTypedHandler(@Nullable TypedActionHandler originalHandler) {
+ super(originalHandler);
+ }
+
+ private static boolean isEnabled(Editor editor) {
+ boolean isEnabled = myIsEnabledInTests && ApplicationManager.getApplication().isUnitTestMode()
+ || Registry.is("editor.reformat.on.typing");
+
+ if (!isEnabled) {
+ return false;
+ }
+
+ Project project = editor.getProject();
+ Language language = null;
+ if (project != null) {
+ PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
+ if (file != null) {
+ language = file.getLanguage();
+ }
+ }
+
+ return language == JavaLanguage.INSTANCE;
+ }
+
+ @TestOnly
+ public static void setEnabledInTests(boolean value) {
+ myIsEnabledInTests = value;
+ }
+
+ @Override
+ public void execute(@NotNull Editor editor, char charTyped, @NotNull DataContext dataContext) {
+ if (!isEnabled(editor)) {
+ executeOriginalHandler(editor, charTyped, dataContext);
+ return;
+ }
+
+ if (isInsertSpaceAtCaret(editor, charTyped, dataContext)) {
+ EditorModificationUtil.insertStringAtCaret(editor, " ");
+ }
+
+ executeOriginalHandler(editor, charTyped, dataContext);
+ }
+
+ private static boolean isInsertSpaceAtCaret(@NotNull Editor editor, char charTyped, @NotNull DataContext dataContext) {
+ if (!isSpaceAroundAssignment(editor, dataContext)) {
+ return false;
+ }
+
+ int caretOffset = editor.getCaretModel().getOffset();
+ CharSequence text = editor.getDocument().getImmutableCharSequence();
+
+ HighlighterIterator lexerIterator = createLexerIterator(editor, caretOffset);
+ if (lexerIterator == null || lexerIterator.getTokenType() == JavaTokenType.STRING_LITERAL) {
+ return false;
+ }
+
+ boolean insertBeforeEq = charTyped == '=' && isInsertSpaceBeforeEq(caretOffset, text);
+ boolean insertAfterEq = caretOffset > 0 && caretOffset - 1 < text.length() && text.charAt(caretOffset - 1) == '='
+ && isAssignmentOperator(lexerIterator) && isInsertSpaceAfterEq(charTyped);
+
+ return (insertBeforeEq || insertAfterEq);
+ }
+
+ private static boolean isAssignmentOperator(HighlighterIterator iterator) {
+ IElementType type = iterator.getTokenType();
+ if (type == TokenType.WHITE_SPACE) {
+ iterator.retreat();
+ type = iterator.getTokenType();
+ }
+
+ if (COMPLEX_ASSIGNMENTS.indexOf(type) >= 0) {
+ return true;
+ }
+
+ if (type == JavaTokenType.EQ) {
+ iterator.retreat();
+ type = iterator.getTokenType();
+ if (type == JavaTokenType.GT) {
+ iterator.retreat();
+ type = iterator.getTokenType();
+ if (type == JavaTokenType.GT) {
+ return true;
+ }
+ }
+
+ else if (type == TokenType.WHITE_SPACE || type == JavaTokenType.IDENTIFIER) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private static boolean isInsertSpaceAfterEq(char charTyped) {
+ return charTyped != '=' && charTyped != ' ';
+ }
+
+ private static HighlighterIterator createLexerIterator(Editor editor, int offset) {
+ if (editor.getDocument().getTextLength() == 0) return null;
+ return editor instanceof EditorEx
+ ? ((EditorEx)editor).getHighlighter().createIterator(offset)
+ : null;
+ }
+
+ private void executeOriginalHandler(@NotNull Editor editor, char charTyped, @NotNull DataContext dataContext) {
+ if (myOriginalHandler != null) myOriginalHandler.execute(editor, charTyped, dataContext);
+ }
+
+ private static boolean isInsertSpaceBeforeEq(int caretOffset, CharSequence text) {
+ if (caretOffset == 0) return false;
+ char charBefore = text.charAt(caretOffset - 1);
+
+ for (char c : NO_SPACE_AFTER) {
+ if (c == charBefore) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static boolean isSpaceAroundAssignment(Editor editor, DataContext dataContext) {
+ final Project project = CommonDataKeys.PROJECT.getData(dataContext);
+ PsiFile file = project == null ? null : PsiUtilBase.getPsiFileInEditor(editor, project);
+ if (file != null) {
+ Language language = file.getLanguage();
+ CodeStyleSettings settings = CodeStyleSettingsManager.getInstance(project).getCurrentSettings();
+ CommonCodeStyleSettings common = settings.getCommonSettings(language);
+ return common.SPACE_AROUND_ASSIGNMENT_OPERATORS;
+ }
+ return false;
+ }
+
+}
diff --git a/java/java-impl/src/com/intellij/codeInsight/editorActions/moveLeftRight/JavaMoveLeftRightHandler.java b/java/java-impl/src/com/intellij/codeInsight/editorActions/moveLeftRight/JavaMoveLeftRightHandler.java
new file mode 100644
index 000000000000..75e93d61d754
--- /dev/null
+++ b/java/java-impl/src/com/intellij/codeInsight/editorActions/moveLeftRight/JavaMoveLeftRightHandler.java
@@ -0,0 +1,46 @@
+/*
+ * 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.editorActions.moveLeftRight;
+
+import com.intellij.psi.*;
+import com.intellij.psi.util.PsiTreeUtil;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+public class JavaMoveLeftRightHandler extends MoveElementLeftRightHandler {
+ @Nullable
+ @Override
+ public PsiElement[] getElementListInContext(@NotNull PsiElement element) {
+ while (element != null) {
+ if (element instanceof PsiParameterList) {
+ return ((PsiParameterList)element).getParameters();
+ }
+ else if (element instanceof PsiExpressionList) {
+ PsiExpression[] expressions = ((PsiExpressionList)element).getExpressions();
+ if (expressions.length > 1) return expressions;
+ }
+ else if (element instanceof PsiArrayInitializerExpression) {
+ PsiExpression[] expressions = ((PsiArrayInitializerExpression)element).getInitializers();
+ if (expressions.length > 1) return expressions;
+ }
+ else if (element instanceof PsiClass && ((PsiClass)element).isEnum()) {
+ return PsiTreeUtil.getChildrenOfType(element, PsiEnumConstant.class);
+ }
+ element = element.getParent();
+ }
+ return null;
+ }
+}
diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersUtil.java b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersUtil.java
index 0900dfac9e1c..16d8778e05b7 100644
--- a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersUtil.java
+++ b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersUtil.java
@@ -686,8 +686,17 @@ public class GenerateMembersUtil {
}
result = (PsiMethod)CodeStyleManager.getInstance(project).reformat(result);
- PsiModifierListOwner annotationTarget = isGetter ? result : result.getParameterList().getParameters()[0];
- NullableNotNullManager.getInstance(project).copyNullableOrNotNullAnnotation(field, annotationTarget);
+ PsiModifierListOwner annotationTarget;
+ if (isGetter) {
+ annotationTarget = result;
+ }
+ else {
+ final PsiParameter[] parameters = result.getParameterList().getParameters();
+ annotationTarget = parameters.length == 1 ? parameters[0] : null;
+ }
+ if (annotationTarget != null) {
+ NullableNotNullManager.getInstance(project).copyNullableOrNotNullAnnotation(field, annotationTarget);
+ }
return generatePrototype(field, result);
}
diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/ui/GenerateEqualsWizard.java b/java/java-impl/src/com/intellij/codeInsight/generation/ui/GenerateEqualsWizard.java
index 7ee8fc9b3b74..0098905f8488 100644
--- a/java/java-impl/src/com/intellij/codeInsight/generation/ui/GenerateEqualsWizard.java
+++ b/java/java-impl/src/com/intellij/codeInsight/generation/ui/GenerateEqualsWizard.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2000-2011 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.
@@ -40,6 +40,7 @@ import com.intellij.refactoring.util.classMembers.MemberInfo;
import com.intellij.ui.JBColor;
import com.intellij.ui.ListCellRendererWrapper;
import com.intellij.ui.NonFocusableCheckBox;
+import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.java.generate.psi.PsiAdapter;
@@ -429,7 +430,7 @@ public class GenerateEqualsWizard extends AbstractGenerateEqualsWizard,
- DumbAware {
- private static final Set ourArgumentListAllowedParentClassesSet = new HashSet(
- Arrays.asList(PsiMethodCallExpression.class, PsiNewExpression.class, PsiAnonymousClass.class, PsiEnumConstant.class));
+public class MethodParameterInfoHandler implements ParameterInfoHandlerWithTabActionSupport, DumbAware {
+ private static final Set ourArgumentListAllowedParentClassesSet = ContainerUtil.newHashSet(
+ PsiMethodCallExpression.class, PsiNewExpression.class, PsiAnonymousClass.class, PsiEnumConstant.class);
private static final Set extends Class> ourStopSearch = Collections.singleton(PsiMethod.class);
@Override
public Object[] getParametersForLookup(LookupElement item, ParameterInfoContext context) {
- final List extends PsiElement> allElements = JavaCompletionUtil.getAllPsiElements(item);
-
- if (allElements != null &&
- !allElements.isEmpty() &&
- allElements.get(0) instanceof PsiMethod) {
- return allElements.toArray(new PsiMethod[allElements.size()]);
- }
- return null;
+ final List extends PsiElement> elements = JavaCompletionUtil.getAllPsiElements(item);
+ return elements != null && !elements.isEmpty() && elements.get(0) instanceof PsiMethod ? elements.toArray() : null;
}
@Override
@@ -213,9 +209,9 @@ public class MethodParameterInfoHandler implements ParameterInfoHandlerWithTabAc
if (realResolve == null) {
PsiCall call = getCall(o);
if (call != null) realResolve = call.resolveMethod();
- if (realResolve == null) realResolve = PsiUtilBase.NULL_PSI_ELEMENT;
+ if (realResolve == null) realResolve = PsiUtilCore.NULL_PSI_ELEMENT;
}
- if (realResolve == PsiUtilBase.NULL_PSI_ELEMENT || realResolve == method) context.setHighlightedParameter(candidate);
+ if (realResolve == PsiUtilCore.NULL_PSI_ELEMENT || realResolve == method) context.setHighlightedParameter(candidate);
}
}
}
@@ -477,18 +473,20 @@ public class MethodParameterInfoHandler implements ParameterInfoHandlerWithTabAc
final PsiJavaCodeReferenceElement element = annotation.getNameReferenceElement();
if (element != null) {
final PsiElement resolved = element.resolve();
- if (resolved instanceof PsiClass && !JavaDocInfoGenerator.isDocumentedAnnotationType(resolved)) {
+ if (resolved instanceof PsiClass &&
+ (!JavaDocInfoGenerator.isDocumentedAnnotationType(resolved) ||
+ AnnotationTargetUtil.findAnnotationTarget((PsiClass)resolved, PsiAnnotation.TargetType.TYPE_USE) != null)) {
continue;
}
String referenceName = element.getReferenceName();
if (shownAnnotations.add(referenceName) || JavaDocInfoGenerator.isRepeatableAnnotationType(resolved)) {
- if (lastSize != buffer.length()) buffer.append(" ");
- buffer.append("@").append(referenceName);
+ if (lastSize != buffer.length()) buffer.append(' ');
+ buffer.append('@').append(referenceName);
}
}
}
- if (lastSize != buffer.length()) buffer.append(" ");
+ if (lastSize != buffer.length()) buffer.append(' ');
}
@Override
diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/IntroduceVariableIntentionAction.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/IntroduceVariableIntentionAction.java
index e45643fa52fb..e605591405f8 100644
--- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/IntroduceVariableIntentionAction.java
+++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/IntroduceVariableIntentionAction.java
@@ -54,7 +54,8 @@ public class IntroduceVariableIntentionAction extends BaseRefactoringIntentionAc
final PsiExpression expression = statement.getExpression();
- return !PsiType.VOID.equals(expression.getType()) && !(expression instanceof PsiAssignmentExpression);
+ final PsiType expressionType = expression.getType();
+ return expressionType != null && !PsiType.VOID.equals(expressionType) && !(expression instanceof PsiAssignmentExpression);
}
@Override
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/impl/JavaTemplateSubstitutor.java b/java/java-impl/src/com/intellij/codeInsight/template/impl/JavaTemplateSubstitutor.java
new file mode 100644
index 000000000000..14ba30fcfa63
--- /dev/null
+++ b/java/java-impl/src/com/intellij/codeInsight/template/impl/JavaTemplateSubstitutor.java
@@ -0,0 +1,49 @@
+/*
+ * 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.template.impl;
+
+import com.intellij.codeInsight.template.TemplateSubstitutor;
+import com.intellij.lang.java.JavaLanguage;
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.patterns.ElementPattern;
+import com.intellij.psi.JavaTokenType;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiFile;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import static com.intellij.patterns.PsiJavaPatterns.psiElement;
+
+/**
+ * @author peter
+ */
+public class JavaTemplateSubstitutor implements TemplateSubstitutor {
+ private static final ElementPattern EXPR_LAMBDA_BODY = psiElement().afterLeaf(psiElement(JavaTokenType.ARROW));
+
+ @Nullable
+ @Override
+ public TemplateImpl substituteTemplate(@NotNull PsiFile file, int caretOffset, @NotNull TemplateImpl template) {
+ if (file.getLanguage().isKindOf(JavaLanguage.INSTANCE) && EXPR_LAMBDA_BODY.accepts(file.findElementAt(caretOffset))) {
+ String text = template.getString();
+ if (!text.contains("\n") && text.endsWith(";")) {
+ TemplateImpl copy = template.copy();
+ copy.setString(StringUtil.trimEnd(text, ";"));
+ return copy;
+ }
+ }
+ return null;
+ }
+}
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/JavaPostfixTemplateProvider.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/JavaPostfixTemplateProvider.java
index dbfe90d7a27f..58614635bac2 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/JavaPostfixTemplateProvider.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/JavaPostfixTemplateProvider.java
@@ -63,7 +63,10 @@ public class JavaPostfixTemplateProvider implements PostfixTemplateProvider {
new ThrowExceptionPostfixTemplate(),
new TryStatementPostfixTemplate(),
new TryWithResourcesPostfixTemplate(),
- new WhileStatementPostfixTemplate());
+ new WhileStatementPostfixTemplate(),
+ new StreamPostfixTemplate(),
+ new OptionalPostfixTemplate(),
+ new LambdaPostfixTemplate());
}
@NotNull
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/LambdaPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/LambdaPostfixTemplate.java
new file mode 100644
index 000000000000..b9f276f79ff9
--- /dev/null
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/LambdaPostfixTemplate.java
@@ -0,0 +1,35 @@
+/*
+ * 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.template.postfix.templates;
+
+import com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils;
+import com.intellij.psi.PsiElement;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.selectorTopmost;
+
+public class LambdaPostfixTemplate extends StringBasedPostfixTemplate {
+ public LambdaPostfixTemplate() {
+ super("lambda", "() -> expr", JavaPostfixTemplatesUtils.atLeastJava8Selector(selectorTopmost()));
+ }
+
+ @Nullable
+ @Override
+ public String getTemplateString(@NotNull PsiElement element) {
+ return "() -> $expr$";
+ }
+}
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/OptionalPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/OptionalPostfixTemplate.java
new file mode 100644
index 000000000000..79c6e3558866
--- /dev/null
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/OptionalPostfixTemplate.java
@@ -0,0 +1,57 @@
+/*
+ * 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.template.postfix.templates;
+
+import com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiExpression;
+import com.intellij.psi.PsiPrimitiveType;
+import com.intellij.psi.PsiType;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.IS_NON_VOID;
+import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.selectorTopmost;
+
+public class OptionalPostfixTemplate extends StringBasedPostfixTemplate {
+ public OptionalPostfixTemplate() {
+ super("opt", "Optional.ofNullable(expr)", JavaPostfixTemplatesUtils.atLeastJava8Selector(selectorTopmost(IS_NON_VOID)));
+ }
+
+ @Nullable
+ @Override
+ public String getTemplateString(@NotNull PsiElement element) {
+ String className = "Optional";
+ String methodName = "ofNullable";
+
+ if (element instanceof PsiExpression) {
+ PsiType type = ((PsiExpression)element).getType();
+ if (type instanceof PsiPrimitiveType) {
+ if (PsiType.INT.equals(type)) {
+ className = "OptionalInt";
+ }
+ else if (PsiType.DOUBLE.equals(type)) {
+ className = "OptionalDouble";
+ }
+ else if (PsiType.LONG.equals(type)) {
+ className = "OptionalLong";
+ }
+ methodName = "of";
+ }
+ }
+ return "java.util." + className + "." + methodName + "($expr$)";
+ }
+}
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/StreamPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/StreamPostfixTemplate.java
new file mode 100644
index 000000000000..c1603123d715
--- /dev/null
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/StreamPostfixTemplate.java
@@ -0,0 +1,40 @@
+/*
+ * 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.template.postfix.templates;
+
+import com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils;
+import com.intellij.psi.PsiElement;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.selectorTopmost;
+
+public class StreamPostfixTemplate extends StringBasedPostfixTemplate {
+ public StreamPostfixTemplate() {
+ super("stream", "Arrays.stream(expr)", JavaPostfixTemplatesUtils.atLeastJava8Selector(selectorTopmost(JavaPostfixTemplatesUtils.IS_ARRAY)));
+ }
+
+ @Nullable
+ @Override
+ public String getTemplateString(@NotNull PsiElement element) {
+ return "java.util.Arrays.stream($expr$)";
+ }
+
+ @Override
+ protected PsiElement getElementToRemove(PsiElement expr) {
+ return expr;
+ }
+}
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/JavaPostfixTemplatesUtils.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/JavaPostfixTemplatesUtils.java
index 38d30e1a3a23..3bfacc324d9d 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/JavaPostfixTemplatesUtils.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/JavaPostfixTemplatesUtils.java
@@ -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.
@@ -27,6 +27,7 @@ import com.intellij.psi.*;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiExpressionTrimRenderer;
import com.intellij.psi.util.PsiTreeUtil;
+import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.introduceVariable.IntroduceVariableBase;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
@@ -43,6 +44,29 @@ public abstract class JavaPostfixTemplatesUtils {
private JavaPostfixTemplatesUtils() {
}
+ public static PostfixTemplateExpressionSelector atLeastJava8Selector(final PostfixTemplateExpressionSelector selector) {
+ return new PostfixTemplateExpressionSelector() {
+ @Override
+ public boolean hasExpression(@NotNull PsiElement context, @NotNull Document copyDocument, int newOffset) {
+ return PsiUtil.isLanguageLevel8OrHigher(context) && selector.hasExpression(context, copyDocument, newOffset);
+ }
+
+ @NotNull
+ @Override
+ public List getExpressions(@NotNull PsiElement context, @NotNull Document document, int offset) {
+ return PsiUtil.isLanguageLevel8OrHigher(context)
+ ? selector.getExpressions(context, document, offset)
+ : Collections.emptyList();
+ }
+
+ @NotNull
+ @Override
+ public Function getRenderer() {
+ return selector.getRenderer();
+ }
+ };
+ }
+
public static PostfixTemplateExpressionSelector selectorTopmost() {
return selectorTopmost(Conditions.alwaysTrue());
}
@@ -116,42 +140,52 @@ public abstract class JavaPostfixTemplatesUtils {
}
};
- public static Condition IS_NUMBER = new Condition() {
+ public static final Condition IS_NUMBER = new Condition() {
@Override
public boolean value(PsiElement element) {
return element instanceof PsiExpression && isNumber(((PsiExpression)element).getType());
}
};
- public static Condition IS_BOOLEAN = new Condition() {
+ public static final Condition IS_BOOLEAN = new Condition