mirror of
https://gitflic.ru/project/openide/openide.git
synced 2026-09-27 10:03:11 +07:00
line separators normalized
This commit is contained in:
Generated
+28
-28
@@ -1,29 +1,29 @@
|
||||
<component name="libraryTable">
|
||||
<library name="Ant">
|
||||
<CLASSES>
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-commons-net.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-jmf.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-apache-resolver.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-jai.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-apache-bsf.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-commons-logging.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-junit.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-jsch.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-apache-bcel.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-netrexx.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-apache-oro.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-antlr.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-jdepend.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-launcher.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-apache-regexp.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-apache-log4j.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-swing.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-javamail.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC />
|
||||
<SOURCES>
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/src/bundled_ant_src.zip!/bundled_ant_src/main" />
|
||||
</SOURCES>
|
||||
</library>
|
||||
<component name="libraryTable">
|
||||
<library name="Ant">
|
||||
<CLASSES>
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-commons-net.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-jmf.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-apache-resolver.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-jai.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-apache-bsf.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-commons-logging.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-junit.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-jsch.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-apache-bcel.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-netrexx.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-apache-oro.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-antlr.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-jdepend.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-launcher.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-apache-regexp.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-apache-log4j.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-swing.jar!/" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/lib/ant-javamail.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC />
|
||||
<SOURCES>
|
||||
<root url="jar://$PROJECT_DIR$/lib/ant/src/bundled_ant_src.zip!/bundled_ant_src/main" />
|
||||
</SOURCES>
|
||||
</library>
|
||||
</component>
|
||||
Generated
+10
-10
@@ -1,11 +1,11 @@
|
||||
<component name="libraryTable">
|
||||
<library name="Netty">
|
||||
<CLASSES>
|
||||
<root url="jar://$PROJECT_DIR$/lib/netty-3.5.10.Final.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC />
|
||||
<SOURCES>
|
||||
<root url="jar://$PROJECT_DIR$/lib/src/netty-3.5.10.Final-sources.jar!/" />
|
||||
</SOURCES>
|
||||
</library>
|
||||
<component name="libraryTable">
|
||||
<library name="Netty">
|
||||
<CLASSES>
|
||||
<root url="jar://$PROJECT_DIR$/lib/netty-3.5.10.Final.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC />
|
||||
<SOURCES>
|
||||
<root url="jar://$PROJECT_DIR$/lib/src/netty-3.5.10.Final-sources.jar!/" />
|
||||
</SOURCES>
|
||||
</library>
|
||||
</component>
|
||||
Generated
+13
-13
@@ -1,14 +1,14 @@
|
||||
<component name="libraryTable">
|
||||
<library name="Snappy-Java">
|
||||
<CLASSES>
|
||||
<root url="jar://$PROJECT_DIR$/lib/snappy-java-1.0.4.1.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC>
|
||||
<root url="jar://$PROJECT_DIR$/lib/src/snappy-java-1.0.4.1-src.zip!/snappy-java-1.0.4.1/wiki/apidocs" />
|
||||
</JAVADOC>
|
||||
<SOURCES>
|
||||
<root url="jar://$PROJECT_DIR$/lib/src/snappy-java-1.0.4.1-src.zip!/snappy-java-1.0.4.1/src/main/resources" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/src/snappy-java-1.0.4.1-src.zip!/snappy-java-1.0.4.1/src/main/java" />
|
||||
</SOURCES>
|
||||
</library>
|
||||
<component name="libraryTable">
|
||||
<library name="Snappy-Java">
|
||||
<CLASSES>
|
||||
<root url="jar://$PROJECT_DIR$/lib/snappy-java-1.0.4.1.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC>
|
||||
<root url="jar://$PROJECT_DIR$/lib/src/snappy-java-1.0.4.1-src.zip!/snappy-java-1.0.4.1/wiki/apidocs" />
|
||||
</JAVADOC>
|
||||
<SOURCES>
|
||||
<root url="jar://$PROJECT_DIR$/lib/src/snappy-java-1.0.4.1-src.zip!/snappy-java-1.0.4.1/src/main/resources" />
|
||||
<root url="jar://$PROJECT_DIR$/lib/src/snappy-java-1.0.4.1-src.zip!/snappy-java-1.0.4.1/src/main/java" />
|
||||
</SOURCES>
|
||||
</library>
|
||||
</component>
|
||||
Generated
+8
-8
@@ -1,9 +1,9 @@
|
||||
<component name="libraryTable">
|
||||
<library name="proxy-vole">
|
||||
<CLASSES>
|
||||
<root url="jar://$PROJECT_DIR$/lib/proxy-vole_20120920.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC />
|
||||
<SOURCES />
|
||||
</library>
|
||||
<component name="libraryTable">
|
||||
<library name="proxy-vole">
|
||||
<CLASSES>
|
||||
<root url="jar://$PROJECT_DIR$/lib/proxy-vole_20120920.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC />
|
||||
<SOURCES />
|
||||
</library>
|
||||
</component>
|
||||
@@ -1,20 +1,20 @@
|
||||
# IntelliJ IDEA Community Edition
|
||||
|
||||
This is the official GitHub mirror of the [IntelliJ IDEA Community Edition](http://www.jetbrains.com/idea/) source code.
|
||||
|
||||
## Building
|
||||
|
||||
To develop IntelliJ IDEA, you can use either IntelliJ IDEA Community Edition or IntelliJ IDEA Ultimate. To build and run the code:
|
||||
|
||||
* Make sure you have the Groovy plugin enabled. Parts of IntelliJ IDEA are written in Groovy, and you will get compilation errors if you don't have the plugin enabled.
|
||||
* Make sure you have the UI Designer plugin enabled. Most of IntelliJ IDEA's UI is built using the UI Designer, and the version you build will not run correctly if you don't have the plugin enabled.
|
||||
* Open the directory with the source code as a directory-based project
|
||||
* Configure a JSDK named "IDEA jdk", pointing to an installation of JDK 1.6
|
||||
* On Windows or Linux, add lib\tools.jar from the JDK installation directory to the classpath of IDEA jdk
|
||||
* Use Build | Make Project to build the code
|
||||
* To run the code, use the provided shared run configuration "IDEA".
|
||||
|
||||
## Contributing
|
||||
|
||||
Pull requests are welcome. Please make sure that you follow the [IntelliJ Coding Guidelines](http://www.jetbrains.org/display/IJOS/IntelliJ+Coding+Guidelines).
|
||||
Note that you'll need to submit a [Contributor Agreement](http://www.jetbrains.org/display/IJOS/Contributor+Agreement) before we can accept your pull request.
|
||||
# IntelliJ IDEA Community Edition
|
||||
|
||||
This is the official GitHub mirror of the [IntelliJ IDEA Community Edition](http://www.jetbrains.com/idea/) source code.
|
||||
|
||||
## Building
|
||||
|
||||
To develop IntelliJ IDEA, you can use either IntelliJ IDEA Community Edition or IntelliJ IDEA Ultimate. To build and run the code:
|
||||
|
||||
* Make sure you have the Groovy plugin enabled. Parts of IntelliJ IDEA are written in Groovy, and you will get compilation errors if you don't have the plugin enabled.
|
||||
* Make sure you have the UI Designer plugin enabled. Most of IntelliJ IDEA's UI is built using the UI Designer, and the version you build will not run correctly if you don't have the plugin enabled.
|
||||
* Open the directory with the source code as a directory-based project
|
||||
* Configure a JSDK named "IDEA jdk", pointing to an installation of JDK 1.6
|
||||
* On Windows or Linux, add lib\tools.jar from the JDK installation directory to the classpath of IDEA jdk
|
||||
* Use Build | Make Project to build the code
|
||||
* To run the code, use the provided shared run configuration "IDEA".
|
||||
|
||||
## Contributing
|
||||
|
||||
Pull requests are welcome. Please make sure that you follow the [IntelliJ Coding Guidelines](http://www.jetbrains.org/display/IJOS/IntelliJ+Coding+Guidelines).
|
||||
Note that you'll need to submit a [Contributor Agreement](http://www.jetbrains.org/display/IJOS/Contributor+Agreement) before we can accept your pull request.
|
||||
|
||||
@@ -1,220 +1,220 @@
|
||||
/*
|
||||
* Copyright 2006 Sascha Weinreuter
|
||||
*
|
||||
* 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 test;
|
||||
|
||||
import org.intellij.lang.regexp.RegExpFileType;
|
||||
import org.jdom.Document;
|
||||
import org.jdom.Element;
|
||||
import org.jdom.input.SAXBuilder;
|
||||
import org.jdom.xpath.XPath;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.regex.PatternSyntaxException;
|
||||
|
||||
public class MainParseTest extends BaseParseTestcase {
|
||||
|
||||
private ByteArrayOutputStream myOut;
|
||||
|
||||
enum Result {
|
||||
OK, ERR
|
||||
}
|
||||
|
||||
static class Test {
|
||||
String pattern;
|
||||
boolean showWarnings = true;
|
||||
boolean showInfo = false;
|
||||
Result expectedResult;
|
||||
|
||||
Test(String pattern, Result result, boolean warn, boolean info) {
|
||||
this.pattern = pattern;
|
||||
expectedResult = result;
|
||||
showWarnings = warn;
|
||||
showInfo = info;
|
||||
}
|
||||
}
|
||||
|
||||
private final Map<String, Test> myMap = new LinkedHashMap<String, Test>();
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
final Document document = new SAXBuilder().build(new File(getTestDataRoot(), "/RETest.xml"));
|
||||
final List<Element> list = XPath.selectNodes(document.getRootElement(), "//test");
|
||||
|
||||
int i = 0;
|
||||
for (Element element : list) {
|
||||
final String name;
|
||||
final Element parent = (Element)element.getParent();
|
||||
final String s = parent.getName();
|
||||
final String t = parent.getAttribute("id") == null ? "" : parent.getAttribute("id").getValue() + "-";
|
||||
if (!"tests".equals(s)) {
|
||||
name = s + "/test-" + t + ++i + ".regexp";
|
||||
}
|
||||
else {
|
||||
name = "test-" + t + ++i + ".regexp";
|
||||
}
|
||||
final Result result = Result.valueOf((String)XPath.selectSingleNode(element, "string(expected)"));
|
||||
final boolean warn = !"false".equals(element.getAttributeValue("warning"));
|
||||
final boolean info = "true".equals(element.getAttributeValue("info"));
|
||||
|
||||
final String pattern = (String)XPath.selectSingleNode(element, "string(pattern)");
|
||||
myMap.put(name, new Test(pattern, result, warn, info));
|
||||
if (!"false".equals(element.getAttributeValue("verify"))) {
|
||||
try {
|
||||
Pattern.compile(pattern);
|
||||
if (result == Result.ERR) {
|
||||
System.out.println("Incorrect FAIL value for " + pattern);
|
||||
}
|
||||
}
|
||||
catch (PatternSyntaxException e) {
|
||||
if (result == Result.OK) {
|
||||
System.out.println("Incorrect OK value for " + pattern);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
super.setUp();
|
||||
|
||||
myOut = new ByteArrayOutputStream();
|
||||
System.setErr(new PrintStream(myOut));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getTestDataPath() {
|
||||
return super.getTestDataPath() + "/gen/";
|
||||
}
|
||||
|
||||
public void testSimple() throws Exception {
|
||||
doTest("simple/");
|
||||
}
|
||||
|
||||
public void testQuantifiers() throws Exception {
|
||||
doTest("quantifiers/");
|
||||
}
|
||||
|
||||
public void testGroups() throws Exception {
|
||||
doTest("groups/");
|
||||
}
|
||||
|
||||
public void testCharclasses() throws Exception {
|
||||
doTest("charclasses/");
|
||||
}
|
||||
|
||||
public void testEscapes() throws Exception {
|
||||
doTest("escapes/");
|
||||
}
|
||||
|
||||
public void testAnchors() throws Exception {
|
||||
doTest("anchors/");
|
||||
}
|
||||
|
||||
public void testNamedchars() throws Exception {
|
||||
doTest("namedchars/");
|
||||
}
|
||||
|
||||
public void testBackrefs() throws Exception {
|
||||
doTest("backrefs/");
|
||||
}
|
||||
|
||||
public void testComplex() throws Exception {
|
||||
doTest("complex/");
|
||||
}
|
||||
|
||||
public void testIncomplete() throws Exception {
|
||||
doTest("incomplete/");
|
||||
}
|
||||
|
||||
public void testRealLife() throws Exception {
|
||||
doTest("real-life/");
|
||||
}
|
||||
|
||||
public void testRegressions() throws Exception {
|
||||
doTest("regressions/");
|
||||
}
|
||||
|
||||
public void testBugs() throws Exception {
|
||||
doTest("bug/");
|
||||
}
|
||||
|
||||
public void testFromXML() throws Exception {
|
||||
doTest(null);
|
||||
}
|
||||
|
||||
private void doTest(String prefix) throws IOException {
|
||||
int n = 0;
|
||||
int failed = 0;
|
||||
for (String name : myMap.keySet()) {
|
||||
if (prefix == null && name.contains("/")) {
|
||||
continue;
|
||||
}
|
||||
if (prefix != null && !name.startsWith(prefix)) {
|
||||
continue;
|
||||
}
|
||||
System.out.print("filename = " + name);
|
||||
n++;
|
||||
|
||||
final MainParseTest.Test test = myMap.get(name);
|
||||
try {
|
||||
myFixture.configureByText(RegExpFileType.INSTANCE, test.pattern);
|
||||
myFixture.testHighlighting(test.showWarnings, true, test.showInfo);
|
||||
|
||||
if (test.expectedResult == Result.ERR) {
|
||||
System.out.println(" FAILED. Expression incorrectly parsed OK: " + test.pattern);
|
||||
failed++;
|
||||
}
|
||||
else {
|
||||
System.out.println(" OK");
|
||||
}
|
||||
}
|
||||
catch (Throwable e) {
|
||||
if (test.expectedResult == Result.ERR) {
|
||||
System.out.println(" OK");
|
||||
}
|
||||
else {
|
||||
e.printStackTrace();
|
||||
System.out.println(" FAILED. Expression = " + test.pattern);
|
||||
if (myOut.size() > 0) {
|
||||
String line;
|
||||
final BufferedReader reader = new BufferedReader(new StringReader(myOut.toString()));
|
||||
do {
|
||||
line = reader.readLine();
|
||||
}
|
||||
while (line != null && (line.trim().length() == 0 || line.trim().equals("ERROR:")));
|
||||
if (line != null) {
|
||||
if (line.matches(".*java.lang.Error: junit.framework.AssertionFailedError:.*")) {
|
||||
System.out.println("ERROR: " + line.replace("java.lang.Error: junit.framework.AssertionFailedError:", ""));
|
||||
}
|
||||
}
|
||||
else {
|
||||
System.out.println("ERROR: " + myOut.toString());
|
||||
}
|
||||
}
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
myOut.reset();
|
||||
}
|
||||
|
||||
System.out.println("");
|
||||
System.out.println(n + " Tests executed, " + failed + " failed");
|
||||
|
||||
assertFalse(failed > 0);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2006 Sascha Weinreuter
|
||||
*
|
||||
* 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 test;
|
||||
|
||||
import org.intellij.lang.regexp.RegExpFileType;
|
||||
import org.jdom.Document;
|
||||
import org.jdom.Element;
|
||||
import org.jdom.input.SAXBuilder;
|
||||
import org.jdom.xpath.XPath;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.regex.PatternSyntaxException;
|
||||
|
||||
public class MainParseTest extends BaseParseTestcase {
|
||||
|
||||
private ByteArrayOutputStream myOut;
|
||||
|
||||
enum Result {
|
||||
OK, ERR
|
||||
}
|
||||
|
||||
static class Test {
|
||||
String pattern;
|
||||
boolean showWarnings = true;
|
||||
boolean showInfo = false;
|
||||
Result expectedResult;
|
||||
|
||||
Test(String pattern, Result result, boolean warn, boolean info) {
|
||||
this.pattern = pattern;
|
||||
expectedResult = result;
|
||||
showWarnings = warn;
|
||||
showInfo = info;
|
||||
}
|
||||
}
|
||||
|
||||
private final Map<String, Test> myMap = new LinkedHashMap<String, Test>();
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
final Document document = new SAXBuilder().build(new File(getTestDataRoot(), "/RETest.xml"));
|
||||
final List<Element> list = XPath.selectNodes(document.getRootElement(), "//test");
|
||||
|
||||
int i = 0;
|
||||
for (Element element : list) {
|
||||
final String name;
|
||||
final Element parent = (Element)element.getParent();
|
||||
final String s = parent.getName();
|
||||
final String t = parent.getAttribute("id") == null ? "" : parent.getAttribute("id").getValue() + "-";
|
||||
if (!"tests".equals(s)) {
|
||||
name = s + "/test-" + t + ++i + ".regexp";
|
||||
}
|
||||
else {
|
||||
name = "test-" + t + ++i + ".regexp";
|
||||
}
|
||||
final Result result = Result.valueOf((String)XPath.selectSingleNode(element, "string(expected)"));
|
||||
final boolean warn = !"false".equals(element.getAttributeValue("warning"));
|
||||
final boolean info = "true".equals(element.getAttributeValue("info"));
|
||||
|
||||
final String pattern = (String)XPath.selectSingleNode(element, "string(pattern)");
|
||||
myMap.put(name, new Test(pattern, result, warn, info));
|
||||
if (!"false".equals(element.getAttributeValue("verify"))) {
|
||||
try {
|
||||
Pattern.compile(pattern);
|
||||
if (result == Result.ERR) {
|
||||
System.out.println("Incorrect FAIL value for " + pattern);
|
||||
}
|
||||
}
|
||||
catch (PatternSyntaxException e) {
|
||||
if (result == Result.OK) {
|
||||
System.out.println("Incorrect OK value for " + pattern);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
super.setUp();
|
||||
|
||||
myOut = new ByteArrayOutputStream();
|
||||
System.setErr(new PrintStream(myOut));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getTestDataPath() {
|
||||
return super.getTestDataPath() + "/gen/";
|
||||
}
|
||||
|
||||
public void testSimple() throws Exception {
|
||||
doTest("simple/");
|
||||
}
|
||||
|
||||
public void testQuantifiers() throws Exception {
|
||||
doTest("quantifiers/");
|
||||
}
|
||||
|
||||
public void testGroups() throws Exception {
|
||||
doTest("groups/");
|
||||
}
|
||||
|
||||
public void testCharclasses() throws Exception {
|
||||
doTest("charclasses/");
|
||||
}
|
||||
|
||||
public void testEscapes() throws Exception {
|
||||
doTest("escapes/");
|
||||
}
|
||||
|
||||
public void testAnchors() throws Exception {
|
||||
doTest("anchors/");
|
||||
}
|
||||
|
||||
public void testNamedchars() throws Exception {
|
||||
doTest("namedchars/");
|
||||
}
|
||||
|
||||
public void testBackrefs() throws Exception {
|
||||
doTest("backrefs/");
|
||||
}
|
||||
|
||||
public void testComplex() throws Exception {
|
||||
doTest("complex/");
|
||||
}
|
||||
|
||||
public void testIncomplete() throws Exception {
|
||||
doTest("incomplete/");
|
||||
}
|
||||
|
||||
public void testRealLife() throws Exception {
|
||||
doTest("real-life/");
|
||||
}
|
||||
|
||||
public void testRegressions() throws Exception {
|
||||
doTest("regressions/");
|
||||
}
|
||||
|
||||
public void testBugs() throws Exception {
|
||||
doTest("bug/");
|
||||
}
|
||||
|
||||
public void testFromXML() throws Exception {
|
||||
doTest(null);
|
||||
}
|
||||
|
||||
private void doTest(String prefix) throws IOException {
|
||||
int n = 0;
|
||||
int failed = 0;
|
||||
for (String name : myMap.keySet()) {
|
||||
if (prefix == null && name.contains("/")) {
|
||||
continue;
|
||||
}
|
||||
if (prefix != null && !name.startsWith(prefix)) {
|
||||
continue;
|
||||
}
|
||||
System.out.print("filename = " + name);
|
||||
n++;
|
||||
|
||||
final MainParseTest.Test test = myMap.get(name);
|
||||
try {
|
||||
myFixture.configureByText(RegExpFileType.INSTANCE, test.pattern);
|
||||
myFixture.testHighlighting(test.showWarnings, true, test.showInfo);
|
||||
|
||||
if (test.expectedResult == Result.ERR) {
|
||||
System.out.println(" FAILED. Expression incorrectly parsed OK: " + test.pattern);
|
||||
failed++;
|
||||
}
|
||||
else {
|
||||
System.out.println(" OK");
|
||||
}
|
||||
}
|
||||
catch (Throwable e) {
|
||||
if (test.expectedResult == Result.ERR) {
|
||||
System.out.println(" OK");
|
||||
}
|
||||
else {
|
||||
e.printStackTrace();
|
||||
System.out.println(" FAILED. Expression = " + test.pattern);
|
||||
if (myOut.size() > 0) {
|
||||
String line;
|
||||
final BufferedReader reader = new BufferedReader(new StringReader(myOut.toString()));
|
||||
do {
|
||||
line = reader.readLine();
|
||||
}
|
||||
while (line != null && (line.trim().length() == 0 || line.trim().equals("ERROR:")));
|
||||
if (line != null) {
|
||||
if (line.matches(".*java.lang.Error: junit.framework.AssertionFailedError:.*")) {
|
||||
System.out.println("ERROR: " + line.replace("java.lang.Error: junit.framework.AssertionFailedError:", ""));
|
||||
}
|
||||
}
|
||||
else {
|
||||
System.out.println("ERROR: " + myOut.toString());
|
||||
}
|
||||
}
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
myOut.reset();
|
||||
}
|
||||
|
||||
System.out.println("");
|
||||
System.out.println(n + " Tests executed, " + failed + " failed");
|
||||
|
||||
assertFalse(failed > 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,143 +1,143 @@
|
||||
<idea-plugin version="2">
|
||||
|
||||
<vendor>JetBrains</vendor>
|
||||
|
||||
<extensions defaultExtensionNs="com.intellij">
|
||||
<errorHandler implementation="com.intellij.diagnostic.ITNReporter"/>
|
||||
<applicationConfigurable instance="org.intellij.images.options.impl.OptionsConfigurabe" id="Images" displayName="Images"/>
|
||||
<fileEditorProvider implementation="org.intellij.images.editor.impl.ImageFileEditorProvider"/>
|
||||
<selectInTarget implementation="org.intellij.images.thumbnail.impl.ThumbnailSelectInTarget"/>
|
||||
<applicationService serviceInterface="org.intellij.images.options.OptionsManager"
|
||||
serviceImplementation="org.intellij.images.options.impl.OptionsManagerImpl"/>
|
||||
<projectService serviceInterface="org.intellij.images.thumbnail.ThumbnailManager"
|
||||
serviceImplementation="org.intellij.images.thumbnail.impl.ThumbnailManagerImpl"/>
|
||||
<fileTypeFactory implementation="org.intellij.images.fileTypes.impl.ImageFileTypeManagerImpl" />
|
||||
<fileBasedIndex implementation="org.intellij.images.index.ImageInfoIndex"/>
|
||||
<fileLookupInfoProvider implementation="org.intellij.images.completion.ImageLookupInfoProvider"/>
|
||||
<documentationProvider implementation="org.intellij.images.fileTypes.ImageDocumentationProvider"/>
|
||||
</extensions>
|
||||
|
||||
<application-components>
|
||||
<component>
|
||||
<interface-class>org.intellij.images.fileTypes.ImageFileTypeManager</interface-class>
|
||||
<implementation-class>org.intellij.images.fileTypes.impl.ImageFileTypeManagerImpl</implementation-class>
|
||||
</component>
|
||||
</application-components>
|
||||
|
||||
<actions>
|
||||
<action id="images.color.picker" class="org.intellij.images.actions.ColorPickerForImageAction" text="Show Color Picker">
|
||||
<add-to-group anchor="after" group-id="ProjectViewPopupMenu" relative-to-action="EditSource"/>
|
||||
</action>
|
||||
<action class="org.intellij.images.actions.EditExternallyAction"
|
||||
id="Images.EditExternaly"
|
||||
icon="ImagesIcons.EditExternaly"
|
||||
text="Open Image in External Editor">
|
||||
<keyboard-shortcut first-keystroke="control alt F4" keymap="$default"/>
|
||||
<add-to-group anchor="after" group-id="ProjectViewPopupMenu" relative-to-action="EditSource"/>
|
||||
</action>
|
||||
<action class="org.intellij.images.actions.ShowThumbnailsAction"
|
||||
id="Images.ShowThumbnails" text="Show Image Thumbnails">
|
||||
<keyboard-shortcut first-keystroke="shift control T" keymap="$default"/>
|
||||
<add-to-group anchor="after" group-id="ProjectViewPopupMenu" relative-to-action="AddToFavorites"/>
|
||||
<add-to-group anchor="after" group-id="NavbarPopupMenu" relative-to-action="AddToFavorites"/>
|
||||
</action>
|
||||
<action class="org.intellij.images.actions.ToggleTransparencyChessboardAction"
|
||||
id="Images.ToggleTransparencyChessboard"
|
||||
icon="ImagesIcons.ToggleTransparencyChessboard"
|
||||
text="Show Chessboard"
|
||||
description="Show a chessboard on transparent image parts">
|
||||
</action>
|
||||
<group id="Images.EditorToolbar">
|
||||
<reference id="Images.ToggleTransparencyChessboard"/>
|
||||
<action class="org.intellij.images.editor.actions.ToggleGridAction"
|
||||
id="Images.Editor.ToggleGrid"
|
||||
icon="ImagesIcons.ToggleGrid"
|
||||
text="Show Grid">
|
||||
<keyboard-shortcut first-keystroke="control QUOTE" keymap="$default"/>
|
||||
</action>
|
||||
<separator/>
|
||||
<action class="org.intellij.images.editor.actions.ZoomInAction"
|
||||
id="Images.Editor.ZoomIn"
|
||||
icon="AllIcons.Graph.ZoomIn"
|
||||
text="Zoom In"
|
||||
use-shortcut-of="ExpandAll" />
|
||||
<action class="org.intellij.images.editor.actions.ZoomOutAction"
|
||||
id="Images.Editor.ZoomOut"
|
||||
icon="AllIcons.Graph.ZoomOut"
|
||||
text="Zoom Out"
|
||||
use-shortcut-of="CollapseAll"/>
|
||||
<action class="org.intellij.images.editor.actions.ActualSizeAction"
|
||||
id="Images.Editor.ActualSize"
|
||||
icon="AllIcons.Graph.ActualZoom"
|
||||
text="Zoom to Actual Size">
|
||||
<keyboard-shortcut first-keystroke="control DIVIDE" keymap="$default"/>
|
||||
<keyboard-shortcut first-keystroke="control SLASH" keymap="$default"/>
|
||||
</action>
|
||||
</group>
|
||||
<group id="Images.EditorPopupMenu">
|
||||
<reference id="CutCopyPasteGroup"/>
|
||||
<separator/>
|
||||
<reference id="FindUsages"/>
|
||||
<reference id="RefactoringMenu"/>
|
||||
<separator/>
|
||||
<reference id="Images.EditorToolbar"/>
|
||||
<separator/>
|
||||
<reference id="CloseEditor"/>
|
||||
<separator/>
|
||||
<reference id="AddToFavorites"/>
|
||||
<separator/>
|
||||
<reference id="VersionControlsGroup"/>
|
||||
<separator/>
|
||||
<reference id="images.color.picker" />
|
||||
<reference id="Images.EditExternaly"/>
|
||||
<reference id="ExternalToolsGroup"/>
|
||||
</group>
|
||||
<group id="Images.ThumbnailsToolbar">
|
||||
<action class="org.intellij.images.thumbnail.actions.UpFolderAction"
|
||||
id="Images.Thumbnails.UpFolder"
|
||||
text="Parent Folder"
|
||||
description="Show image thumbnails from the containing folder"
|
||||
icon="AllIcons.Nodes.UpFolder">
|
||||
<keyboard-shortcut first-keystroke="BACK_SPACE" keymap="$default"/>
|
||||
</action>
|
||||
<action class="org.intellij.images.thumbnail.actions.ToggleRecursiveAction"
|
||||
id="Images.Thumbnails.ToggleRecursive"
|
||||
text="Recursive"
|
||||
description="Toggle whether to show the images from subfolders recursively"
|
||||
icon="AllIcons.ObjectBrowser.FlattenPackages">
|
||||
<keyboard-shortcut first-keystroke="control MULTIPLY" keymap="$default"/>
|
||||
</action>
|
||||
<separator/>
|
||||
<reference id="Images.ToggleTransparencyChessboard"/>
|
||||
<separator/>
|
||||
<action class="org.intellij.images.thumbnail.actions.HideThumbnailsAction"
|
||||
id="Images.Thumbnails.Hide"
|
||||
text="Hide"
|
||||
description="Hide image thumbnails"
|
||||
icon="AllIcons.Actions.Cancel" use-shortcut-of="CloseContent"/>
|
||||
</group>
|
||||
<group id="Images.ThumbnailsPopupMenu">
|
||||
<reference id="CutCopyPasteGroup"/>
|
||||
<reference id="EditSource"/>
|
||||
<action class="org.intellij.images.thumbnail.actions.EnterAction"
|
||||
id="Images.Thumbnails.EnterAction">
|
||||
<keyboard-shortcut first-keystroke="ENTER" keymap="$default"/>
|
||||
</action>
|
||||
<separator/>
|
||||
<reference id="Images.ThumbnailsToolbar"/>
|
||||
<separator/>
|
||||
<reference id="FindUsages"/>
|
||||
<reference id="RefactoringMenu"/>
|
||||
<separator/>
|
||||
<reference id="AddToFavorites"/>
|
||||
<separator/>
|
||||
<reference id="$Delete"/>
|
||||
<separator/>
|
||||
<reference id="VersionControlsGroup"/>
|
||||
<reference id="CompareTwoFiles"/>
|
||||
<separator/>
|
||||
<reference id="Images.EditExternaly"/>
|
||||
<reference id="ExternalToolsGroup"/>
|
||||
</group>
|
||||
</actions>
|
||||
</idea-plugin>
|
||||
<idea-plugin version="2">
|
||||
|
||||
<vendor>JetBrains</vendor>
|
||||
|
||||
<extensions defaultExtensionNs="com.intellij">
|
||||
<errorHandler implementation="com.intellij.diagnostic.ITNReporter"/>
|
||||
<applicationConfigurable instance="org.intellij.images.options.impl.OptionsConfigurabe" id="Images" displayName="Images"/>
|
||||
<fileEditorProvider implementation="org.intellij.images.editor.impl.ImageFileEditorProvider"/>
|
||||
<selectInTarget implementation="org.intellij.images.thumbnail.impl.ThumbnailSelectInTarget"/>
|
||||
<applicationService serviceInterface="org.intellij.images.options.OptionsManager"
|
||||
serviceImplementation="org.intellij.images.options.impl.OptionsManagerImpl"/>
|
||||
<projectService serviceInterface="org.intellij.images.thumbnail.ThumbnailManager"
|
||||
serviceImplementation="org.intellij.images.thumbnail.impl.ThumbnailManagerImpl"/>
|
||||
<fileTypeFactory implementation="org.intellij.images.fileTypes.impl.ImageFileTypeManagerImpl" />
|
||||
<fileBasedIndex implementation="org.intellij.images.index.ImageInfoIndex"/>
|
||||
<fileLookupInfoProvider implementation="org.intellij.images.completion.ImageLookupInfoProvider"/>
|
||||
<documentationProvider implementation="org.intellij.images.fileTypes.ImageDocumentationProvider"/>
|
||||
</extensions>
|
||||
|
||||
<application-components>
|
||||
<component>
|
||||
<interface-class>org.intellij.images.fileTypes.ImageFileTypeManager</interface-class>
|
||||
<implementation-class>org.intellij.images.fileTypes.impl.ImageFileTypeManagerImpl</implementation-class>
|
||||
</component>
|
||||
</application-components>
|
||||
|
||||
<actions>
|
||||
<action id="images.color.picker" class="org.intellij.images.actions.ColorPickerForImageAction" text="Show Color Picker">
|
||||
<add-to-group anchor="after" group-id="ProjectViewPopupMenu" relative-to-action="EditSource"/>
|
||||
</action>
|
||||
<action class="org.intellij.images.actions.EditExternallyAction"
|
||||
id="Images.EditExternaly"
|
||||
icon="ImagesIcons.EditExternaly"
|
||||
text="Open Image in External Editor">
|
||||
<keyboard-shortcut first-keystroke="control alt F4" keymap="$default"/>
|
||||
<add-to-group anchor="after" group-id="ProjectViewPopupMenu" relative-to-action="EditSource"/>
|
||||
</action>
|
||||
<action class="org.intellij.images.actions.ShowThumbnailsAction"
|
||||
id="Images.ShowThumbnails" text="Show Image Thumbnails">
|
||||
<keyboard-shortcut first-keystroke="shift control T" keymap="$default"/>
|
||||
<add-to-group anchor="after" group-id="ProjectViewPopupMenu" relative-to-action="AddToFavorites"/>
|
||||
<add-to-group anchor="after" group-id="NavbarPopupMenu" relative-to-action="AddToFavorites"/>
|
||||
</action>
|
||||
<action class="org.intellij.images.actions.ToggleTransparencyChessboardAction"
|
||||
id="Images.ToggleTransparencyChessboard"
|
||||
icon="ImagesIcons.ToggleTransparencyChessboard"
|
||||
text="Show Chessboard"
|
||||
description="Show a chessboard on transparent image parts">
|
||||
</action>
|
||||
<group id="Images.EditorToolbar">
|
||||
<reference id="Images.ToggleTransparencyChessboard"/>
|
||||
<action class="org.intellij.images.editor.actions.ToggleGridAction"
|
||||
id="Images.Editor.ToggleGrid"
|
||||
icon="ImagesIcons.ToggleGrid"
|
||||
text="Show Grid">
|
||||
<keyboard-shortcut first-keystroke="control QUOTE" keymap="$default"/>
|
||||
</action>
|
||||
<separator/>
|
||||
<action class="org.intellij.images.editor.actions.ZoomInAction"
|
||||
id="Images.Editor.ZoomIn"
|
||||
icon="AllIcons.Graph.ZoomIn"
|
||||
text="Zoom In"
|
||||
use-shortcut-of="ExpandAll" />
|
||||
<action class="org.intellij.images.editor.actions.ZoomOutAction"
|
||||
id="Images.Editor.ZoomOut"
|
||||
icon="AllIcons.Graph.ZoomOut"
|
||||
text="Zoom Out"
|
||||
use-shortcut-of="CollapseAll"/>
|
||||
<action class="org.intellij.images.editor.actions.ActualSizeAction"
|
||||
id="Images.Editor.ActualSize"
|
||||
icon="AllIcons.Graph.ActualZoom"
|
||||
text="Zoom to Actual Size">
|
||||
<keyboard-shortcut first-keystroke="control DIVIDE" keymap="$default"/>
|
||||
<keyboard-shortcut first-keystroke="control SLASH" keymap="$default"/>
|
||||
</action>
|
||||
</group>
|
||||
<group id="Images.EditorPopupMenu">
|
||||
<reference id="CutCopyPasteGroup"/>
|
||||
<separator/>
|
||||
<reference id="FindUsages"/>
|
||||
<reference id="RefactoringMenu"/>
|
||||
<separator/>
|
||||
<reference id="Images.EditorToolbar"/>
|
||||
<separator/>
|
||||
<reference id="CloseEditor"/>
|
||||
<separator/>
|
||||
<reference id="AddToFavorites"/>
|
||||
<separator/>
|
||||
<reference id="VersionControlsGroup"/>
|
||||
<separator/>
|
||||
<reference id="images.color.picker" />
|
||||
<reference id="Images.EditExternaly"/>
|
||||
<reference id="ExternalToolsGroup"/>
|
||||
</group>
|
||||
<group id="Images.ThumbnailsToolbar">
|
||||
<action class="org.intellij.images.thumbnail.actions.UpFolderAction"
|
||||
id="Images.Thumbnails.UpFolder"
|
||||
text="Parent Folder"
|
||||
description="Show image thumbnails from the containing folder"
|
||||
icon="AllIcons.Nodes.UpFolder">
|
||||
<keyboard-shortcut first-keystroke="BACK_SPACE" keymap="$default"/>
|
||||
</action>
|
||||
<action class="org.intellij.images.thumbnail.actions.ToggleRecursiveAction"
|
||||
id="Images.Thumbnails.ToggleRecursive"
|
||||
text="Recursive"
|
||||
description="Toggle whether to show the images from subfolders recursively"
|
||||
icon="AllIcons.ObjectBrowser.FlattenPackages">
|
||||
<keyboard-shortcut first-keystroke="control MULTIPLY" keymap="$default"/>
|
||||
</action>
|
||||
<separator/>
|
||||
<reference id="Images.ToggleTransparencyChessboard"/>
|
||||
<separator/>
|
||||
<action class="org.intellij.images.thumbnail.actions.HideThumbnailsAction"
|
||||
id="Images.Thumbnails.Hide"
|
||||
text="Hide"
|
||||
description="Hide image thumbnails"
|
||||
icon="AllIcons.Actions.Cancel" use-shortcut-of="CloseContent"/>
|
||||
</group>
|
||||
<group id="Images.ThumbnailsPopupMenu">
|
||||
<reference id="CutCopyPasteGroup"/>
|
||||
<reference id="EditSource"/>
|
||||
<action class="org.intellij.images.thumbnail.actions.EnterAction"
|
||||
id="Images.Thumbnails.EnterAction">
|
||||
<keyboard-shortcut first-keystroke="ENTER" keymap="$default"/>
|
||||
</action>
|
||||
<separator/>
|
||||
<reference id="Images.ThumbnailsToolbar"/>
|
||||
<separator/>
|
||||
<reference id="FindUsages"/>
|
||||
<reference id="RefactoringMenu"/>
|
||||
<separator/>
|
||||
<reference id="AddToFavorites"/>
|
||||
<separator/>
|
||||
<reference id="$Delete"/>
|
||||
<separator/>
|
||||
<reference id="VersionControlsGroup"/>
|
||||
<reference id="CompareTwoFiles"/>
|
||||
<separator/>
|
||||
<reference id="Images.EditExternaly"/>
|
||||
<reference id="ExternalToolsGroup"/>
|
||||
</group>
|
||||
</actions>
|
||||
</idea-plugin>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,153 +1,153 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.compiler.options.CompilerUIConfigurable">
|
||||
<grid id="1663f" binding="myPanel" layout-manager="GridLayoutManager" row-count="10" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
|
||||
<margin top="0" left="0" bottom="0" right="0"/>
|
||||
<constraints>
|
||||
<xy x="28" y="24" width="883" height="379"/>
|
||||
</constraints>
|
||||
<properties/>
|
||||
<border type="none"/>
|
||||
<children>
|
||||
<vspacer id="67edf">
|
||||
<constraints>
|
||||
<grid row="9" column="0" row-span="1" col-span="3" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
</vspacer>
|
||||
<grid id="b341d" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="1">
|
||||
<margin top="0" left="0" bottom="0" right="0"/>
|
||||
<constraints>
|
||||
<grid row="0" column="0" row-span="1" col-span="3" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties/>
|
||||
<border type="none"/>
|
||||
<children>
|
||||
<component id="b0748" class="javax.swing.JLabel">
|
||||
<constraints>
|
||||
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text resource-bundle="messages/CompilerBundle" key="label.option.resource.patterns.text"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="263f1" class="javax.swing.JTextField" binding="myResourcePatternsField">
|
||||
<constraints>
|
||||
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
|
||||
<preferred-size width="150" height="-1"/>
|
||||
</grid>
|
||||
</constraints>
|
||||
<properties>
|
||||
<focusable value="true"/>
|
||||
<text value="" noi18n="true"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="78174" class="com.intellij.ui.components.JBLabel" binding="myPatternLegendLabel">
|
||||
<constraints>
|
||||
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="8" fill="0" indent="1" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<componentStyle value="SMALL"/>
|
||||
<fontColor value="BRIGHTER"/>
|
||||
<text value="label"/>
|
||||
</properties>
|
||||
</component>
|
||||
</children>
|
||||
</grid>
|
||||
<component id="889a8" class="javax.swing.JCheckBox" binding="myCbClearOutputDirectory">
|
||||
<constraints>
|
||||
<grid row="1" column="0" row-span="1" col-span="3" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text resource-bundle="messages/CompilerBundle" key="label.option.clear.output.directory.on.rebuild"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="366e" class="javax.swing.JCheckBox" binding="myCbAssertNotNull">
|
||||
<constraints>
|
||||
<grid row="2" column="0" row-span="1" col-span="3" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text resource-bundle="messages/CompilerBundle" key="add.notnull.assertions"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="348ee" class="javax.swing.JCheckBox" binding="myCbAutoShowFirstError">
|
||||
<constraints>
|
||||
<grid row="3" column="0" row-span="1" col-span="3" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text resource-bundle="messages/CompilerBundle" key="label.option.autoshow.first.error"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="ce617" class="javax.swing.JCheckBox" binding="myCbUseExternalBuild" default-binding="true">
|
||||
<constraints>
|
||||
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text value="Use external build"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="b9b2d" class="javax.swing.JCheckBox" binding="myCbEnableAutomake">
|
||||
<constraints>
|
||||
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text value="Make project automatically"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="17126" class="javax.swing.JLabel" binding="myHeapSizeLabel">
|
||||
<constraints>
|
||||
<grid row="7" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text value="Compiler process heap size (Mbytes):"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="a28b8" class="javax.swing.JTextField" binding="myHeapSizeField">
|
||||
<constraints>
|
||||
<grid row="7" column="1" row-span="1" col-span="2" vsize-policy="0" hsize-policy="6" anchor="8" fill="0" indent="0" use-parent-layout="false">
|
||||
<preferred-size width="50" height="-1"/>
|
||||
</grid>
|
||||
</constraints>
|
||||
<properties/>
|
||||
</component>
|
||||
<component id="5b86a" class="javax.swing.JLabel" binding="myVMOptionsLabel">
|
||||
<constraints>
|
||||
<grid row="8" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text value="Additional compiler process VM options:"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="b5547" class="javax.swing.JTextField" binding="myVMOptionsField">
|
||||
<constraints>
|
||||
<grid row="8" column="1" row-span="1" col-span="2" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
|
||||
<preferred-size width="150" height="-1"/>
|
||||
</grid>
|
||||
</constraints>
|
||||
<properties/>
|
||||
</component>
|
||||
<component id="ba694" class="javax.swing.JCheckBox" binding="myCbParallelCompilation">
|
||||
<constraints>
|
||||
<grid row="6" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text value="Compile independent modules in parallel"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="91979" class="javax.swing.JLabel">
|
||||
<constraints>
|
||||
<grid row="6" column="1" row-span="1" col-span="2" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text value="(may require larger heap size)"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="732b1" class="javax.swing.JLabel">
|
||||
<constraints>
|
||||
<grid row="5" column="1" row-span="1" col-span="2" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text value="(only works while not running / debugging)"/>
|
||||
</properties>
|
||||
</component>
|
||||
</children>
|
||||
</grid>
|
||||
</form>
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.compiler.options.CompilerUIConfigurable">
|
||||
<grid id="1663f" binding="myPanel" layout-manager="GridLayoutManager" row-count="10" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
|
||||
<margin top="0" left="0" bottom="0" right="0"/>
|
||||
<constraints>
|
||||
<xy x="28" y="24" width="883" height="379"/>
|
||||
</constraints>
|
||||
<properties/>
|
||||
<border type="none"/>
|
||||
<children>
|
||||
<vspacer id="67edf">
|
||||
<constraints>
|
||||
<grid row="9" column="0" row-span="1" col-span="3" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
</vspacer>
|
||||
<grid id="b341d" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="1">
|
||||
<margin top="0" left="0" bottom="0" right="0"/>
|
||||
<constraints>
|
||||
<grid row="0" column="0" row-span="1" col-span="3" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties/>
|
||||
<border type="none"/>
|
||||
<children>
|
||||
<component id="b0748" class="javax.swing.JLabel">
|
||||
<constraints>
|
||||
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text resource-bundle="messages/CompilerBundle" key="label.option.resource.patterns.text"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="263f1" class="javax.swing.JTextField" binding="myResourcePatternsField">
|
||||
<constraints>
|
||||
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
|
||||
<preferred-size width="150" height="-1"/>
|
||||
</grid>
|
||||
</constraints>
|
||||
<properties>
|
||||
<focusable value="true"/>
|
||||
<text value="" noi18n="true"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="78174" class="com.intellij.ui.components.JBLabel" binding="myPatternLegendLabel">
|
||||
<constraints>
|
||||
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="8" fill="0" indent="1" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<componentStyle value="SMALL"/>
|
||||
<fontColor value="BRIGHTER"/>
|
||||
<text value="label"/>
|
||||
</properties>
|
||||
</component>
|
||||
</children>
|
||||
</grid>
|
||||
<component id="889a8" class="javax.swing.JCheckBox" binding="myCbClearOutputDirectory">
|
||||
<constraints>
|
||||
<grid row="1" column="0" row-span="1" col-span="3" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text resource-bundle="messages/CompilerBundle" key="label.option.clear.output.directory.on.rebuild"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="366e" class="javax.swing.JCheckBox" binding="myCbAssertNotNull">
|
||||
<constraints>
|
||||
<grid row="2" column="0" row-span="1" col-span="3" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text resource-bundle="messages/CompilerBundle" key="add.notnull.assertions"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="348ee" class="javax.swing.JCheckBox" binding="myCbAutoShowFirstError">
|
||||
<constraints>
|
||||
<grid row="3" column="0" row-span="1" col-span="3" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text resource-bundle="messages/CompilerBundle" key="label.option.autoshow.first.error"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="ce617" class="javax.swing.JCheckBox" binding="myCbUseExternalBuild" default-binding="true">
|
||||
<constraints>
|
||||
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text value="Use external build"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="b9b2d" class="javax.swing.JCheckBox" binding="myCbEnableAutomake">
|
||||
<constraints>
|
||||
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text value="Make project automatically"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="17126" class="javax.swing.JLabel" binding="myHeapSizeLabel">
|
||||
<constraints>
|
||||
<grid row="7" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text value="Compiler process heap size (Mbytes):"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="a28b8" class="javax.swing.JTextField" binding="myHeapSizeField">
|
||||
<constraints>
|
||||
<grid row="7" column="1" row-span="1" col-span="2" vsize-policy="0" hsize-policy="6" anchor="8" fill="0" indent="0" use-parent-layout="false">
|
||||
<preferred-size width="50" height="-1"/>
|
||||
</grid>
|
||||
</constraints>
|
||||
<properties/>
|
||||
</component>
|
||||
<component id="5b86a" class="javax.swing.JLabel" binding="myVMOptionsLabel">
|
||||
<constraints>
|
||||
<grid row="8" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text value="Additional compiler process VM options:"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="b5547" class="javax.swing.JTextField" binding="myVMOptionsField">
|
||||
<constraints>
|
||||
<grid row="8" column="1" row-span="1" col-span="2" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
|
||||
<preferred-size width="150" height="-1"/>
|
||||
</grid>
|
||||
</constraints>
|
||||
<properties/>
|
||||
</component>
|
||||
<component id="ba694" class="javax.swing.JCheckBox" binding="myCbParallelCompilation">
|
||||
<constraints>
|
||||
<grid row="6" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text value="Compile independent modules in parallel"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="91979" class="javax.swing.JLabel">
|
||||
<constraints>
|
||||
<grid row="6" column="1" row-span="1" col-span="2" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text value="(may require larger heap size)"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="732b1" class="javax.swing.JLabel">
|
||||
<constraints>
|
||||
<grid row="5" column="1" row-span="1" col-span="2" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text value="(only works while not running / debugging)"/>
|
||||
</properties>
|
||||
</component>
|
||||
</children>
|
||||
</grid>
|
||||
</form>
|
||||
|
||||
+246
-246
@@ -1,246 +1,246 @@
|
||||
/*
|
||||
* Copyright 2000-2009 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.options;
|
||||
|
||||
import com.intellij.compiler.CompilerConfiguration;
|
||||
import com.intellij.compiler.CompilerConfigurationImpl;
|
||||
import com.intellij.compiler.CompilerWorkspaceConfiguration;
|
||||
import com.intellij.compiler.MalformedPatternException;
|
||||
import com.intellij.compiler.impl.TranslatingCompilerFilesMonitor;
|
||||
import com.intellij.compiler.server.BuildManager;
|
||||
import com.intellij.openapi.compiler.CompilerBundle;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.options.Configurable;
|
||||
import com.intellij.openapi.options.ConfigurationException;
|
||||
import com.intellij.openapi.options.SearchableConfigurable;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.util.io.FileUtil;
|
||||
import com.intellij.ui.components.JBLabel;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.awt.event.ItemEvent;
|
||||
import java.awt.event.ItemListener;
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
public class CompilerUIConfigurable implements SearchableConfigurable, Configurable.NoScroll {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.options.CompilerUIConfigurable");
|
||||
private JPanel myPanel;
|
||||
private final Project myProject;
|
||||
|
||||
private JTextField myResourcePatternsField;
|
||||
private JCheckBox myCbClearOutputDirectory;
|
||||
private JCheckBox myCbAssertNotNull;
|
||||
private JBLabel myPatternLegendLabel;
|
||||
private JCheckBox myCbAutoShowFirstError;
|
||||
private JCheckBox myCbUseExternalBuild;
|
||||
private JCheckBox myCbEnableAutomake;
|
||||
private JCheckBox myCbParallelCompilation;
|
||||
private JTextField myHeapSizeField;
|
||||
private JTextField myVMOptionsField;
|
||||
private JLabel myHeapSizeLabel;
|
||||
private JLabel myVMOptionsLabel;
|
||||
|
||||
public CompilerUIConfigurable(final Project project) {
|
||||
myProject = project;
|
||||
|
||||
myPatternLegendLabel.setText("<html>" +
|
||||
"Use <b>;</b> to separate patterns and <b>!</b> to negate a pattern. " +
|
||||
"Accepted wildcards: <b>?</b> — exactly one symbol; <b>*</b> — zero or more symbols; " +
|
||||
"<b>/</b> — path separator; <b>/**/</b> — any number of directories; " +
|
||||
"<i><dir_name></i>:<i><pattern></i> — restrict to source roots with the specified name" +
|
||||
"</html>");
|
||||
myCbUseExternalBuild.addItemListener(new ItemListener() {
|
||||
@Override
|
||||
public void itemStateChanged(ItemEvent e) {
|
||||
updateExternalMakeOptionControls(myCbUseExternalBuild.isSelected());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
|
||||
final CompilerConfigurationImpl configuration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject);
|
||||
final CompilerWorkspaceConfiguration workspaceConfiguration = CompilerWorkspaceConfiguration.getInstance(myProject);
|
||||
myCbAutoShowFirstError.setSelected(workspaceConfiguration.AUTO_SHOW_ERRORS_IN_EDITOR);
|
||||
myCbClearOutputDirectory.setSelected(workspaceConfiguration.CLEAR_OUTPUT_DIRECTORY);
|
||||
myCbAssertNotNull.setSelected(configuration.isAddNotNullAssertions());
|
||||
myCbUseExternalBuild.setSelected(workspaceConfiguration.USE_COMPILE_SERVER);
|
||||
myCbEnableAutomake.setSelected(workspaceConfiguration.MAKE_PROJECT_ON_SAVE);
|
||||
myCbParallelCompilation.setSelected(workspaceConfiguration.PARALLEL_COMPILATION);
|
||||
myHeapSizeField.setText(String.valueOf(workspaceConfiguration.COMPILER_PROCESS_HEAP_SIZE));
|
||||
final String options = workspaceConfiguration.COMPILER_PROCESS_ADDITIONAL_VM_OPTIONS;
|
||||
myVMOptionsField.setText(options == null? "" : options.trim());
|
||||
updateExternalMakeOptionControls(myCbUseExternalBuild.isSelected());
|
||||
|
||||
configuration.convertPatterns();
|
||||
|
||||
myResourcePatternsField.setText(patternsToString(configuration.getResourceFilePatterns()));
|
||||
}
|
||||
|
||||
private static String patternsToString(final String[] patterns) {
|
||||
final StringBuilder extensionsString = new StringBuilder();
|
||||
for (int idx = 0; idx < patterns.length; idx++) {
|
||||
if (idx > 0) {
|
||||
extensionsString.append(";");
|
||||
}
|
||||
extensionsString.append(patterns[idx]);
|
||||
}
|
||||
return extensionsString.toString();
|
||||
}
|
||||
|
||||
public void apply() throws ConfigurationException {
|
||||
|
||||
CompilerConfigurationImpl configuration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject);
|
||||
final CompilerWorkspaceConfiguration workspaceConfiguration = CompilerWorkspaceConfiguration.getInstance(myProject);
|
||||
workspaceConfiguration.AUTO_SHOW_ERRORS_IN_EDITOR = myCbAutoShowFirstError.isSelected();
|
||||
workspaceConfiguration.CLEAR_OUTPUT_DIRECTORY = myCbClearOutputDirectory.isSelected();
|
||||
boolean wasUsingExternalMake = workspaceConfiguration.USE_COMPILE_SERVER;
|
||||
workspaceConfiguration.USE_COMPILE_SERVER = myCbUseExternalBuild.isSelected();
|
||||
workspaceConfiguration.MAKE_PROJECT_ON_SAVE = myCbEnableAutomake.isSelected();
|
||||
workspaceConfiguration.PARALLEL_COMPILATION = myCbParallelCompilation.isSelected();
|
||||
try {
|
||||
workspaceConfiguration.COMPILER_PROCESS_HEAP_SIZE = Integer.parseInt(myHeapSizeField.getText().trim());
|
||||
}
|
||||
catch (NumberFormatException ignored) {
|
||||
LOG.info(ignored);
|
||||
}
|
||||
workspaceConfiguration.COMPILER_PROCESS_ADDITIONAL_VM_OPTIONS = myVMOptionsField.getText().trim();
|
||||
|
||||
configuration.setAddNotNullAssertions(myCbAssertNotNull.isSelected());
|
||||
configuration.removeResourceFilePatterns();
|
||||
String extensionString = myResourcePatternsField.getText().trim();
|
||||
applyResourcePatterns(extensionString, (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject));
|
||||
|
||||
// this will schedule for compilation all files that might become compilable after resource patterns' changing
|
||||
final TranslatingCompilerFilesMonitor monitor = TranslatingCompilerFilesMonitor.getInstance();
|
||||
if (workspaceConfiguration.USE_COMPILE_SERVER) {
|
||||
monitor.suspendProject(myProject);
|
||||
//noinspection SSBasedInspection
|
||||
SwingUtilities.invokeLater(new Runnable() {
|
||||
public void run() {
|
||||
BuildManager.getInstance().clearState(myProject);
|
||||
}
|
||||
});
|
||||
}
|
||||
else {
|
||||
// use old make
|
||||
if (wasUsingExternalMake) {
|
||||
monitor.watchProject(myProject);
|
||||
monitor.scanSourcesForCompilableFiles(myProject);
|
||||
if (!myProject.isDefault()) {
|
||||
final File buildSystem = BuildManager.getInstance().getBuildSystemDirectory();
|
||||
final File[] subdirs = buildSystem.listFiles();
|
||||
if (subdirs != null) {
|
||||
final String prefix = myProject.getName().toLowerCase(Locale.US) + "_";
|
||||
for (File subdir : subdirs) {
|
||||
if (subdir.getName().startsWith(prefix)) {
|
||||
FileUtil.asyncDelete(subdir);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void applyResourcePatterns(String extensionString, final CompilerConfigurationImpl configuration)
|
||||
throws ConfigurationException {
|
||||
StringTokenizer tokenizer = new StringTokenizer(extensionString, ";", false);
|
||||
List<String[]> errors = new ArrayList<String[]>();
|
||||
|
||||
while (tokenizer.hasMoreTokens()) {
|
||||
String namePattern = tokenizer.nextToken();
|
||||
try {
|
||||
configuration.addResourceFilePattern(namePattern);
|
||||
}
|
||||
catch (MalformedPatternException e) {
|
||||
errors.add(new String[]{namePattern, e.getLocalizedMessage()});
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.size() > 0) {
|
||||
final StringBuilder pattersnsWithErrors = new StringBuilder();
|
||||
for (final Object error : errors) {
|
||||
String[] pair = (String[])error;
|
||||
pattersnsWithErrors.append("\n");
|
||||
pattersnsWithErrors.append(pair[0]);
|
||||
pattersnsWithErrors.append(": ");
|
||||
pattersnsWithErrors.append(pair[1]);
|
||||
}
|
||||
|
||||
throw new ConfigurationException(
|
||||
CompilerBundle.message("error.compiler.configurable.malformed.patterns", pattersnsWithErrors.toString()), CompilerBundle.message("bad.resource.patterns.dialog.title")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isModified() {
|
||||
boolean isModified = false;
|
||||
final CompilerWorkspaceConfiguration workspaceConfiguration = CompilerWorkspaceConfiguration.getInstance(myProject);
|
||||
isModified |= ComparingUtils.isModified(myCbAutoShowFirstError, workspaceConfiguration.AUTO_SHOW_ERRORS_IN_EDITOR);
|
||||
isModified |= ComparingUtils.isModified(myCbUseExternalBuild, workspaceConfiguration.USE_COMPILE_SERVER);
|
||||
isModified |= ComparingUtils.isModified(myCbEnableAutomake, workspaceConfiguration.MAKE_PROJECT_ON_SAVE);
|
||||
isModified |= ComparingUtils.isModified(myCbParallelCompilation, workspaceConfiguration.PARALLEL_COMPILATION);
|
||||
isModified |= ComparingUtils.isModified(myHeapSizeField, workspaceConfiguration.COMPILER_PROCESS_HEAP_SIZE);
|
||||
isModified |= ComparingUtils.isModified(myVMOptionsField, workspaceConfiguration.COMPILER_PROCESS_ADDITIONAL_VM_OPTIONS);
|
||||
|
||||
final CompilerConfigurationImpl compilerConfiguration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject);
|
||||
isModified |= ComparingUtils.isModified(myCbAssertNotNull, compilerConfiguration.isAddNotNullAssertions());
|
||||
isModified |= ComparingUtils.isModified(myCbClearOutputDirectory, workspaceConfiguration.CLEAR_OUTPUT_DIRECTORY);
|
||||
isModified |= ComparingUtils.isModified(myResourcePatternsField, patternsToString(compilerConfiguration.getResourceFilePatterns()));
|
||||
|
||||
return isModified;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return "General";
|
||||
}
|
||||
|
||||
public String getHelpTopic() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getId() {
|
||||
return "compiler.general";
|
||||
}
|
||||
|
||||
public Runnable enableSearch(String option) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public JComponent createComponent() {
|
||||
return myPanel;
|
||||
}
|
||||
|
||||
public void disposeUIResources() {
|
||||
}
|
||||
|
||||
private void updateExternalMakeOptionControls(boolean enabled) {
|
||||
myCbEnableAutomake.setEnabled(enabled);
|
||||
myCbParallelCompilation.setEnabled(enabled);
|
||||
myHeapSizeField.setEnabled(enabled);
|
||||
myVMOptionsField.setEnabled(enabled);
|
||||
myHeapSizeLabel.setEnabled(enabled);
|
||||
myVMOptionsLabel.setEnabled(enabled);
|
||||
}
|
||||
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 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.options;
|
||||
|
||||
import com.intellij.compiler.CompilerConfiguration;
|
||||
import com.intellij.compiler.CompilerConfigurationImpl;
|
||||
import com.intellij.compiler.CompilerWorkspaceConfiguration;
|
||||
import com.intellij.compiler.MalformedPatternException;
|
||||
import com.intellij.compiler.impl.TranslatingCompilerFilesMonitor;
|
||||
import com.intellij.compiler.server.BuildManager;
|
||||
import com.intellij.openapi.compiler.CompilerBundle;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.options.Configurable;
|
||||
import com.intellij.openapi.options.ConfigurationException;
|
||||
import com.intellij.openapi.options.SearchableConfigurable;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.util.io.FileUtil;
|
||||
import com.intellij.ui.components.JBLabel;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.awt.event.ItemEvent;
|
||||
import java.awt.event.ItemListener;
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
public class CompilerUIConfigurable implements SearchableConfigurable, Configurable.NoScroll {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.options.CompilerUIConfigurable");
|
||||
private JPanel myPanel;
|
||||
private final Project myProject;
|
||||
|
||||
private JTextField myResourcePatternsField;
|
||||
private JCheckBox myCbClearOutputDirectory;
|
||||
private JCheckBox myCbAssertNotNull;
|
||||
private JBLabel myPatternLegendLabel;
|
||||
private JCheckBox myCbAutoShowFirstError;
|
||||
private JCheckBox myCbUseExternalBuild;
|
||||
private JCheckBox myCbEnableAutomake;
|
||||
private JCheckBox myCbParallelCompilation;
|
||||
private JTextField myHeapSizeField;
|
||||
private JTextField myVMOptionsField;
|
||||
private JLabel myHeapSizeLabel;
|
||||
private JLabel myVMOptionsLabel;
|
||||
|
||||
public CompilerUIConfigurable(final Project project) {
|
||||
myProject = project;
|
||||
|
||||
myPatternLegendLabel.setText("<html>" +
|
||||
"Use <b>;</b> to separate patterns and <b>!</b> to negate a pattern. " +
|
||||
"Accepted wildcards: <b>?</b> — exactly one symbol; <b>*</b> — zero or more symbols; " +
|
||||
"<b>/</b> — path separator; <b>/**/</b> — any number of directories; " +
|
||||
"<i><dir_name></i>:<i><pattern></i> — restrict to source roots with the specified name" +
|
||||
"</html>");
|
||||
myCbUseExternalBuild.addItemListener(new ItemListener() {
|
||||
@Override
|
||||
public void itemStateChanged(ItemEvent e) {
|
||||
updateExternalMakeOptionControls(myCbUseExternalBuild.isSelected());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
|
||||
final CompilerConfigurationImpl configuration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject);
|
||||
final CompilerWorkspaceConfiguration workspaceConfiguration = CompilerWorkspaceConfiguration.getInstance(myProject);
|
||||
myCbAutoShowFirstError.setSelected(workspaceConfiguration.AUTO_SHOW_ERRORS_IN_EDITOR);
|
||||
myCbClearOutputDirectory.setSelected(workspaceConfiguration.CLEAR_OUTPUT_DIRECTORY);
|
||||
myCbAssertNotNull.setSelected(configuration.isAddNotNullAssertions());
|
||||
myCbUseExternalBuild.setSelected(workspaceConfiguration.USE_COMPILE_SERVER);
|
||||
myCbEnableAutomake.setSelected(workspaceConfiguration.MAKE_PROJECT_ON_SAVE);
|
||||
myCbParallelCompilation.setSelected(workspaceConfiguration.PARALLEL_COMPILATION);
|
||||
myHeapSizeField.setText(String.valueOf(workspaceConfiguration.COMPILER_PROCESS_HEAP_SIZE));
|
||||
final String options = workspaceConfiguration.COMPILER_PROCESS_ADDITIONAL_VM_OPTIONS;
|
||||
myVMOptionsField.setText(options == null? "" : options.trim());
|
||||
updateExternalMakeOptionControls(myCbUseExternalBuild.isSelected());
|
||||
|
||||
configuration.convertPatterns();
|
||||
|
||||
myResourcePatternsField.setText(patternsToString(configuration.getResourceFilePatterns()));
|
||||
}
|
||||
|
||||
private static String patternsToString(final String[] patterns) {
|
||||
final StringBuilder extensionsString = new StringBuilder();
|
||||
for (int idx = 0; idx < patterns.length; idx++) {
|
||||
if (idx > 0) {
|
||||
extensionsString.append(";");
|
||||
}
|
||||
extensionsString.append(patterns[idx]);
|
||||
}
|
||||
return extensionsString.toString();
|
||||
}
|
||||
|
||||
public void apply() throws ConfigurationException {
|
||||
|
||||
CompilerConfigurationImpl configuration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject);
|
||||
final CompilerWorkspaceConfiguration workspaceConfiguration = CompilerWorkspaceConfiguration.getInstance(myProject);
|
||||
workspaceConfiguration.AUTO_SHOW_ERRORS_IN_EDITOR = myCbAutoShowFirstError.isSelected();
|
||||
workspaceConfiguration.CLEAR_OUTPUT_DIRECTORY = myCbClearOutputDirectory.isSelected();
|
||||
boolean wasUsingExternalMake = workspaceConfiguration.USE_COMPILE_SERVER;
|
||||
workspaceConfiguration.USE_COMPILE_SERVER = myCbUseExternalBuild.isSelected();
|
||||
workspaceConfiguration.MAKE_PROJECT_ON_SAVE = myCbEnableAutomake.isSelected();
|
||||
workspaceConfiguration.PARALLEL_COMPILATION = myCbParallelCompilation.isSelected();
|
||||
try {
|
||||
workspaceConfiguration.COMPILER_PROCESS_HEAP_SIZE = Integer.parseInt(myHeapSizeField.getText().trim());
|
||||
}
|
||||
catch (NumberFormatException ignored) {
|
||||
LOG.info(ignored);
|
||||
}
|
||||
workspaceConfiguration.COMPILER_PROCESS_ADDITIONAL_VM_OPTIONS = myVMOptionsField.getText().trim();
|
||||
|
||||
configuration.setAddNotNullAssertions(myCbAssertNotNull.isSelected());
|
||||
configuration.removeResourceFilePatterns();
|
||||
String extensionString = myResourcePatternsField.getText().trim();
|
||||
applyResourcePatterns(extensionString, (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject));
|
||||
|
||||
// this will schedule for compilation all files that might become compilable after resource patterns' changing
|
||||
final TranslatingCompilerFilesMonitor monitor = TranslatingCompilerFilesMonitor.getInstance();
|
||||
if (workspaceConfiguration.USE_COMPILE_SERVER) {
|
||||
monitor.suspendProject(myProject);
|
||||
//noinspection SSBasedInspection
|
||||
SwingUtilities.invokeLater(new Runnable() {
|
||||
public void run() {
|
||||
BuildManager.getInstance().clearState(myProject);
|
||||
}
|
||||
});
|
||||
}
|
||||
else {
|
||||
// use old make
|
||||
if (wasUsingExternalMake) {
|
||||
monitor.watchProject(myProject);
|
||||
monitor.scanSourcesForCompilableFiles(myProject);
|
||||
if (!myProject.isDefault()) {
|
||||
final File buildSystem = BuildManager.getInstance().getBuildSystemDirectory();
|
||||
final File[] subdirs = buildSystem.listFiles();
|
||||
if (subdirs != null) {
|
||||
final String prefix = myProject.getName().toLowerCase(Locale.US) + "_";
|
||||
for (File subdir : subdirs) {
|
||||
if (subdir.getName().startsWith(prefix)) {
|
||||
FileUtil.asyncDelete(subdir);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void applyResourcePatterns(String extensionString, final CompilerConfigurationImpl configuration)
|
||||
throws ConfigurationException {
|
||||
StringTokenizer tokenizer = new StringTokenizer(extensionString, ";", false);
|
||||
List<String[]> errors = new ArrayList<String[]>();
|
||||
|
||||
while (tokenizer.hasMoreTokens()) {
|
||||
String namePattern = tokenizer.nextToken();
|
||||
try {
|
||||
configuration.addResourceFilePattern(namePattern);
|
||||
}
|
||||
catch (MalformedPatternException e) {
|
||||
errors.add(new String[]{namePattern, e.getLocalizedMessage()});
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.size() > 0) {
|
||||
final StringBuilder pattersnsWithErrors = new StringBuilder();
|
||||
for (final Object error : errors) {
|
||||
String[] pair = (String[])error;
|
||||
pattersnsWithErrors.append("\n");
|
||||
pattersnsWithErrors.append(pair[0]);
|
||||
pattersnsWithErrors.append(": ");
|
||||
pattersnsWithErrors.append(pair[1]);
|
||||
}
|
||||
|
||||
throw new ConfigurationException(
|
||||
CompilerBundle.message("error.compiler.configurable.malformed.patterns", pattersnsWithErrors.toString()), CompilerBundle.message("bad.resource.patterns.dialog.title")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isModified() {
|
||||
boolean isModified = false;
|
||||
final CompilerWorkspaceConfiguration workspaceConfiguration = CompilerWorkspaceConfiguration.getInstance(myProject);
|
||||
isModified |= ComparingUtils.isModified(myCbAutoShowFirstError, workspaceConfiguration.AUTO_SHOW_ERRORS_IN_EDITOR);
|
||||
isModified |= ComparingUtils.isModified(myCbUseExternalBuild, workspaceConfiguration.USE_COMPILE_SERVER);
|
||||
isModified |= ComparingUtils.isModified(myCbEnableAutomake, workspaceConfiguration.MAKE_PROJECT_ON_SAVE);
|
||||
isModified |= ComparingUtils.isModified(myCbParallelCompilation, workspaceConfiguration.PARALLEL_COMPILATION);
|
||||
isModified |= ComparingUtils.isModified(myHeapSizeField, workspaceConfiguration.COMPILER_PROCESS_HEAP_SIZE);
|
||||
isModified |= ComparingUtils.isModified(myVMOptionsField, workspaceConfiguration.COMPILER_PROCESS_ADDITIONAL_VM_OPTIONS);
|
||||
|
||||
final CompilerConfigurationImpl compilerConfiguration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject);
|
||||
isModified |= ComparingUtils.isModified(myCbAssertNotNull, compilerConfiguration.isAddNotNullAssertions());
|
||||
isModified |= ComparingUtils.isModified(myCbClearOutputDirectory, workspaceConfiguration.CLEAR_OUTPUT_DIRECTORY);
|
||||
isModified |= ComparingUtils.isModified(myResourcePatternsField, patternsToString(compilerConfiguration.getResourceFilePatterns()));
|
||||
|
||||
return isModified;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return "General";
|
||||
}
|
||||
|
||||
public String getHelpTopic() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getId() {
|
||||
return "compiler.general";
|
||||
}
|
||||
|
||||
public Runnable enableSearch(String option) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public JComponent createComponent() {
|
||||
return myPanel;
|
||||
}
|
||||
|
||||
public void disposeUIResources() {
|
||||
}
|
||||
|
||||
private void updateExternalMakeOptionControls(boolean enabled) {
|
||||
myCbEnableAutomake.setEnabled(enabled);
|
||||
myCbParallelCompilation.setEnabled(enabled);
|
||||
myHeapSizeField.setEnabled(enabled);
|
||||
myVMOptionsField.setEnabled(enabled);
|
||||
myHeapSizeLabel.setEnabled(enabled);
|
||||
myVMOptionsLabel.setEnabled(enabled);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+260
-260
@@ -1,260 +1,260 @@
|
||||
/*
|
||||
* Copyright 2000-2009 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.packaging.impl.run;
|
||||
|
||||
import com.intellij.execution.BeforeRunTask;
|
||||
import com.intellij.execution.BeforeRunTaskProvider;
|
||||
import com.intellij.execution.RunManagerEx;
|
||||
import com.intellij.execution.configurations.RunConfiguration;
|
||||
import com.intellij.execution.impl.ConfigurationSettingsEditorWrapper;
|
||||
import com.intellij.execution.runners.ExecutionEnvironment;
|
||||
import com.intellij.icons.AllIcons;
|
||||
import com.intellij.ide.DataManager;
|
||||
import com.intellij.openapi.actionSystem.DataContext;
|
||||
import com.intellij.openapi.application.ApplicationManager;
|
||||
import com.intellij.openapi.application.ModalityState;
|
||||
import com.intellij.openapi.application.ReadAction;
|
||||
import com.intellij.openapi.application.Result;
|
||||
import com.intellij.openapi.compiler.*;
|
||||
import com.intellij.openapi.compiler.Compiler;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.ui.DialogBuilder;
|
||||
import com.intellij.openapi.ui.DialogWrapper;
|
||||
import com.intellij.openapi.util.Key;
|
||||
import com.intellij.openapi.util.Ref;
|
||||
import com.intellij.packaging.artifacts.*;
|
||||
import com.intellij.packaging.impl.compiler.ArtifactAwareCompiler;
|
||||
import com.intellij.packaging.impl.compiler.ArtifactCompileScope;
|
||||
import com.intellij.packaging.impl.compiler.ArtifactsCompiler;
|
||||
import com.intellij.util.concurrency.Semaphore;
|
||||
import com.intellij.util.containers.ContainerUtil;
|
||||
import gnu.trove.THashSet;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.awt.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author nik
|
||||
*/
|
||||
public class BuildArtifactsBeforeRunTaskProvider extends BeforeRunTaskProvider<BuildArtifactsBeforeRunTask> {
|
||||
@NonNls public static final String BUILD_ARTIFACTS_ID = "BuildArtifacts";
|
||||
public static final Key<BuildArtifactsBeforeRunTask> ID = Key.create(BUILD_ARTIFACTS_ID);
|
||||
private final Project myProject;
|
||||
|
||||
public BuildArtifactsBeforeRunTaskProvider(Project project) {
|
||||
myProject = project;
|
||||
project.getMessageBus().connect().subscribe(ArtifactManager.TOPIC, new ArtifactAdapter() {
|
||||
@Override
|
||||
public void artifactRemoved(@NotNull Artifact artifact) {
|
||||
final RunManagerEx runManager = RunManagerEx.getInstanceEx(myProject);
|
||||
for (RunConfiguration configuration : runManager.getAllConfigurations()) {
|
||||
final List<BuildArtifactsBeforeRunTask> tasks = runManager.getBeforeRunTasks(configuration, ID);
|
||||
for (BuildArtifactsBeforeRunTask task : tasks) {
|
||||
final String artifactName = artifact.getName();
|
||||
final List<ArtifactPointer> pointersList = task.getArtifactPointers();
|
||||
final ArtifactPointer[] pointers = pointersList.toArray(new ArtifactPointer[pointersList.size()]);
|
||||
for (ArtifactPointer pointer : pointers) {
|
||||
if (pointer.getArtifactName().equals(artifactName) && ArtifactManager.getInstance(myProject).findArtifact(artifactName) == null) {
|
||||
task.removeArtifact(pointer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Key<BuildArtifactsBeforeRunTask> getId() {
|
||||
return ID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Icon getIcon() {
|
||||
return AllIcons.Nodes.Artifact;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return CompilerBundle.message("build.artifacts.before.run.description.empty");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Icon getTaskIcon(BuildArtifactsBeforeRunTask task) {
|
||||
List<ArtifactPointer> pointers = task.getArtifactPointers();
|
||||
if (pointers == null || pointers.isEmpty())
|
||||
return getIcon();
|
||||
Artifact artifact = pointers.get(0).getArtifact();
|
||||
if (artifact == null)
|
||||
return getIcon();
|
||||
return artifact.getArtifactType().getIcon();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription(BuildArtifactsBeforeRunTask task) {
|
||||
final List<ArtifactPointer> pointers = task.getArtifactPointers();
|
||||
if (pointers.isEmpty()) {
|
||||
return CompilerBundle.message("build.artifacts.before.run.description.empty");
|
||||
}
|
||||
if (pointers.size() == 1) {
|
||||
return CompilerBundle.message("build.artifacts.before.run.description.single", pointers.get(0).getArtifactName());
|
||||
}
|
||||
return CompilerBundle.message("build.artifacts.before.run.description.multiple", pointers.size());
|
||||
}
|
||||
|
||||
public boolean isConfigurable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public BuildArtifactsBeforeRunTask createTask(RunConfiguration runConfiguration) {
|
||||
if (myProject.isDefault()) return null;
|
||||
return new BuildArtifactsBeforeRunTask(myProject);
|
||||
}
|
||||
|
||||
public boolean configureTask(RunConfiguration runConfiguration, BuildArtifactsBeforeRunTask task) {
|
||||
final Artifact[] artifacts = ArtifactManager.getInstance(myProject).getArtifacts();
|
||||
Set<ArtifactPointer> pointers = new THashSet<ArtifactPointer>();
|
||||
for (Artifact artifact : artifacts) {
|
||||
pointers.add(ArtifactPointerManager.getInstance(myProject).createPointer(artifact));
|
||||
}
|
||||
pointers.addAll(task.getArtifactPointers());
|
||||
ArtifactChooser chooser = new ArtifactChooser(new ArrayList<ArtifactPointer>(pointers));
|
||||
chooser.markElements(task.getArtifactPointers());
|
||||
chooser.setPreferredSize(new Dimension(400, 300));
|
||||
|
||||
DialogBuilder builder = new DialogBuilder(myProject);
|
||||
builder.setTitle(CompilerBundle.message("build.artifacts.before.run.selector.title"));
|
||||
builder.setDimensionServiceKey("#BuildArtifactsBeforeRunChooser");
|
||||
builder.addOkAction();
|
||||
builder.addCancelAction();
|
||||
builder.setCenterPanel(chooser);
|
||||
builder.setPreferedFocusComponent(chooser);
|
||||
if (builder.show() == DialogWrapper.OK_EXIT_CODE) {
|
||||
task.setArtifactPointers(chooser.getMarkedElements());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canExecuteTask(RunConfiguration configuration, BuildArtifactsBeforeRunTask task) {
|
||||
for (ArtifactPointer pointer: task.getArtifactPointers()) {
|
||||
if (pointer.getArtifact() != null)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean executeTask(DataContext context,
|
||||
RunConfiguration configuration,
|
||||
ExecutionEnvironment env,
|
||||
final BuildArtifactsBeforeRunTask task) {
|
||||
final Ref<Boolean> result = Ref.create(false);
|
||||
final Semaphore finished = new Semaphore();
|
||||
|
||||
final List<Artifact> artifacts = new ArrayList<Artifact>();
|
||||
new ReadAction() {
|
||||
protected void run(final Result result) {
|
||||
for (ArtifactPointer pointer : task.getArtifactPointers()) {
|
||||
ContainerUtil.addIfNotNull(pointer.getArtifact(), artifacts);
|
||||
}
|
||||
}
|
||||
}.execute();
|
||||
|
||||
final CompileStatusNotification callback = new CompileStatusNotification() {
|
||||
public void finished(boolean aborted, int errors, int warnings, CompileContext compileContext) {
|
||||
result.set(!aborted && errors == 0);
|
||||
finished.up();
|
||||
}
|
||||
};
|
||||
final CompilerFilter compilerFilter = new CompilerFilter() {
|
||||
public boolean acceptCompiler(Compiler compiler) {
|
||||
return compiler instanceof ArtifactsCompiler
|
||||
|| compiler instanceof ArtifactAwareCompiler && ((ArtifactAwareCompiler)compiler).shouldRun(artifacts);
|
||||
}
|
||||
};
|
||||
|
||||
ApplicationManager.getApplication().invokeAndWait(new Runnable() {
|
||||
public void run() {
|
||||
final CompilerManager manager = CompilerManager.getInstance(myProject);
|
||||
finished.down();
|
||||
manager.make(ArtifactCompileScope.createArtifactsScope(myProject, artifacts), compilerFilter, callback);
|
||||
}
|
||||
}, ModalityState.NON_MODAL);
|
||||
|
||||
finished.waitFor();
|
||||
return result.get();
|
||||
}
|
||||
|
||||
public static void setBuildArtifactBeforeRunOption(@NotNull JComponent runConfigurationEditorComponent,
|
||||
Project project,
|
||||
@NotNull Artifact artifact,
|
||||
final boolean enable) {
|
||||
final DataContext dataContext = DataManager.getInstance().getDataContext(runConfigurationEditorComponent);
|
||||
final ConfigurationSettingsEditorWrapper editor = ConfigurationSettingsEditorWrapper.CONFIGURATION_EDITOR_KEY.getData(dataContext);
|
||||
if (editor != null) {
|
||||
List<BeforeRunTask> tasks = editor.getStepsBeforeLaunch();
|
||||
List<BuildArtifactsBeforeRunTask> myTasks = new ArrayList<BuildArtifactsBeforeRunTask>();
|
||||
for (BeforeRunTask task : tasks) {
|
||||
if (task instanceof BuildArtifactsBeforeRunTask) {
|
||||
myTasks.add((BuildArtifactsBeforeRunTask)task);
|
||||
}
|
||||
}
|
||||
if (enable && myTasks.isEmpty()) {
|
||||
BuildArtifactsBeforeRunTask task = new BuildArtifactsBeforeRunTask(project);
|
||||
task.addArtifact(artifact);
|
||||
task.setEnabled(true);
|
||||
editor.addBeforeLaunchStep(task);
|
||||
}
|
||||
else {
|
||||
for (BuildArtifactsBeforeRunTask task : myTasks) {
|
||||
if (enable) {
|
||||
task.addArtifact(artifact);
|
||||
task.setEnabled(true);
|
||||
}
|
||||
else {
|
||||
task.removeArtifact(artifact);
|
||||
if (task.getArtifactPointers().isEmpty()) {
|
||||
task.setEnabled(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void setBuildArtifactBeforeRun(@NotNull Project project, @NotNull RunConfiguration configuration, @NotNull Artifact artifact) {
|
||||
RunManagerEx runManager = RunManagerEx.getInstanceEx(project);
|
||||
final List<BuildArtifactsBeforeRunTask> buildArtifactsTasks = runManager.getBeforeRunTasks(configuration, ID);
|
||||
if (buildArtifactsTasks.isEmpty()) { //Add new task if absent
|
||||
BuildArtifactsBeforeRunTask task = new BuildArtifactsBeforeRunTask(project);
|
||||
buildArtifactsTasks.add(task);
|
||||
List<BeforeRunTask> tasks = runManager.getBeforeRunTasks(configuration);
|
||||
tasks.add(task);
|
||||
runManager.setBeforeRunTasks(configuration, tasks, false);
|
||||
}
|
||||
|
||||
for (BuildArtifactsBeforeRunTask task : buildArtifactsTasks) {
|
||||
task.setEnabled(true);
|
||||
task.addArtifact(artifact);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 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.packaging.impl.run;
|
||||
|
||||
import com.intellij.execution.BeforeRunTask;
|
||||
import com.intellij.execution.BeforeRunTaskProvider;
|
||||
import com.intellij.execution.RunManagerEx;
|
||||
import com.intellij.execution.configurations.RunConfiguration;
|
||||
import com.intellij.execution.impl.ConfigurationSettingsEditorWrapper;
|
||||
import com.intellij.execution.runners.ExecutionEnvironment;
|
||||
import com.intellij.icons.AllIcons;
|
||||
import com.intellij.ide.DataManager;
|
||||
import com.intellij.openapi.actionSystem.DataContext;
|
||||
import com.intellij.openapi.application.ApplicationManager;
|
||||
import com.intellij.openapi.application.ModalityState;
|
||||
import com.intellij.openapi.application.ReadAction;
|
||||
import com.intellij.openapi.application.Result;
|
||||
import com.intellij.openapi.compiler.*;
|
||||
import com.intellij.openapi.compiler.Compiler;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.ui.DialogBuilder;
|
||||
import com.intellij.openapi.ui.DialogWrapper;
|
||||
import com.intellij.openapi.util.Key;
|
||||
import com.intellij.openapi.util.Ref;
|
||||
import com.intellij.packaging.artifacts.*;
|
||||
import com.intellij.packaging.impl.compiler.ArtifactAwareCompiler;
|
||||
import com.intellij.packaging.impl.compiler.ArtifactCompileScope;
|
||||
import com.intellij.packaging.impl.compiler.ArtifactsCompiler;
|
||||
import com.intellij.util.concurrency.Semaphore;
|
||||
import com.intellij.util.containers.ContainerUtil;
|
||||
import gnu.trove.THashSet;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.awt.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author nik
|
||||
*/
|
||||
public class BuildArtifactsBeforeRunTaskProvider extends BeforeRunTaskProvider<BuildArtifactsBeforeRunTask> {
|
||||
@NonNls public static final String BUILD_ARTIFACTS_ID = "BuildArtifacts";
|
||||
public static final Key<BuildArtifactsBeforeRunTask> ID = Key.create(BUILD_ARTIFACTS_ID);
|
||||
private final Project myProject;
|
||||
|
||||
public BuildArtifactsBeforeRunTaskProvider(Project project) {
|
||||
myProject = project;
|
||||
project.getMessageBus().connect().subscribe(ArtifactManager.TOPIC, new ArtifactAdapter() {
|
||||
@Override
|
||||
public void artifactRemoved(@NotNull Artifact artifact) {
|
||||
final RunManagerEx runManager = RunManagerEx.getInstanceEx(myProject);
|
||||
for (RunConfiguration configuration : runManager.getAllConfigurations()) {
|
||||
final List<BuildArtifactsBeforeRunTask> tasks = runManager.getBeforeRunTasks(configuration, ID);
|
||||
for (BuildArtifactsBeforeRunTask task : tasks) {
|
||||
final String artifactName = artifact.getName();
|
||||
final List<ArtifactPointer> pointersList = task.getArtifactPointers();
|
||||
final ArtifactPointer[] pointers = pointersList.toArray(new ArtifactPointer[pointersList.size()]);
|
||||
for (ArtifactPointer pointer : pointers) {
|
||||
if (pointer.getArtifactName().equals(artifactName) && ArtifactManager.getInstance(myProject).findArtifact(artifactName) == null) {
|
||||
task.removeArtifact(pointer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Key<BuildArtifactsBeforeRunTask> getId() {
|
||||
return ID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Icon getIcon() {
|
||||
return AllIcons.Nodes.Artifact;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return CompilerBundle.message("build.artifacts.before.run.description.empty");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Icon getTaskIcon(BuildArtifactsBeforeRunTask task) {
|
||||
List<ArtifactPointer> pointers = task.getArtifactPointers();
|
||||
if (pointers == null || pointers.isEmpty())
|
||||
return getIcon();
|
||||
Artifact artifact = pointers.get(0).getArtifact();
|
||||
if (artifact == null)
|
||||
return getIcon();
|
||||
return artifact.getArtifactType().getIcon();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription(BuildArtifactsBeforeRunTask task) {
|
||||
final List<ArtifactPointer> pointers = task.getArtifactPointers();
|
||||
if (pointers.isEmpty()) {
|
||||
return CompilerBundle.message("build.artifacts.before.run.description.empty");
|
||||
}
|
||||
if (pointers.size() == 1) {
|
||||
return CompilerBundle.message("build.artifacts.before.run.description.single", pointers.get(0).getArtifactName());
|
||||
}
|
||||
return CompilerBundle.message("build.artifacts.before.run.description.multiple", pointers.size());
|
||||
}
|
||||
|
||||
public boolean isConfigurable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public BuildArtifactsBeforeRunTask createTask(RunConfiguration runConfiguration) {
|
||||
if (myProject.isDefault()) return null;
|
||||
return new BuildArtifactsBeforeRunTask(myProject);
|
||||
}
|
||||
|
||||
public boolean configureTask(RunConfiguration runConfiguration, BuildArtifactsBeforeRunTask task) {
|
||||
final Artifact[] artifacts = ArtifactManager.getInstance(myProject).getArtifacts();
|
||||
Set<ArtifactPointer> pointers = new THashSet<ArtifactPointer>();
|
||||
for (Artifact artifact : artifacts) {
|
||||
pointers.add(ArtifactPointerManager.getInstance(myProject).createPointer(artifact));
|
||||
}
|
||||
pointers.addAll(task.getArtifactPointers());
|
||||
ArtifactChooser chooser = new ArtifactChooser(new ArrayList<ArtifactPointer>(pointers));
|
||||
chooser.markElements(task.getArtifactPointers());
|
||||
chooser.setPreferredSize(new Dimension(400, 300));
|
||||
|
||||
DialogBuilder builder = new DialogBuilder(myProject);
|
||||
builder.setTitle(CompilerBundle.message("build.artifacts.before.run.selector.title"));
|
||||
builder.setDimensionServiceKey("#BuildArtifactsBeforeRunChooser");
|
||||
builder.addOkAction();
|
||||
builder.addCancelAction();
|
||||
builder.setCenterPanel(chooser);
|
||||
builder.setPreferedFocusComponent(chooser);
|
||||
if (builder.show() == DialogWrapper.OK_EXIT_CODE) {
|
||||
task.setArtifactPointers(chooser.getMarkedElements());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canExecuteTask(RunConfiguration configuration, BuildArtifactsBeforeRunTask task) {
|
||||
for (ArtifactPointer pointer: task.getArtifactPointers()) {
|
||||
if (pointer.getArtifact() != null)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean executeTask(DataContext context,
|
||||
RunConfiguration configuration,
|
||||
ExecutionEnvironment env,
|
||||
final BuildArtifactsBeforeRunTask task) {
|
||||
final Ref<Boolean> result = Ref.create(false);
|
||||
final Semaphore finished = new Semaphore();
|
||||
|
||||
final List<Artifact> artifacts = new ArrayList<Artifact>();
|
||||
new ReadAction() {
|
||||
protected void run(final Result result) {
|
||||
for (ArtifactPointer pointer : task.getArtifactPointers()) {
|
||||
ContainerUtil.addIfNotNull(pointer.getArtifact(), artifacts);
|
||||
}
|
||||
}
|
||||
}.execute();
|
||||
|
||||
final CompileStatusNotification callback = new CompileStatusNotification() {
|
||||
public void finished(boolean aborted, int errors, int warnings, CompileContext compileContext) {
|
||||
result.set(!aborted && errors == 0);
|
||||
finished.up();
|
||||
}
|
||||
};
|
||||
final CompilerFilter compilerFilter = new CompilerFilter() {
|
||||
public boolean acceptCompiler(Compiler compiler) {
|
||||
return compiler instanceof ArtifactsCompiler
|
||||
|| compiler instanceof ArtifactAwareCompiler && ((ArtifactAwareCompiler)compiler).shouldRun(artifacts);
|
||||
}
|
||||
};
|
||||
|
||||
ApplicationManager.getApplication().invokeAndWait(new Runnable() {
|
||||
public void run() {
|
||||
final CompilerManager manager = CompilerManager.getInstance(myProject);
|
||||
finished.down();
|
||||
manager.make(ArtifactCompileScope.createArtifactsScope(myProject, artifacts), compilerFilter, callback);
|
||||
}
|
||||
}, ModalityState.NON_MODAL);
|
||||
|
||||
finished.waitFor();
|
||||
return result.get();
|
||||
}
|
||||
|
||||
public static void setBuildArtifactBeforeRunOption(@NotNull JComponent runConfigurationEditorComponent,
|
||||
Project project,
|
||||
@NotNull Artifact artifact,
|
||||
final boolean enable) {
|
||||
final DataContext dataContext = DataManager.getInstance().getDataContext(runConfigurationEditorComponent);
|
||||
final ConfigurationSettingsEditorWrapper editor = ConfigurationSettingsEditorWrapper.CONFIGURATION_EDITOR_KEY.getData(dataContext);
|
||||
if (editor != null) {
|
||||
List<BeforeRunTask> tasks = editor.getStepsBeforeLaunch();
|
||||
List<BuildArtifactsBeforeRunTask> myTasks = new ArrayList<BuildArtifactsBeforeRunTask>();
|
||||
for (BeforeRunTask task : tasks) {
|
||||
if (task instanceof BuildArtifactsBeforeRunTask) {
|
||||
myTasks.add((BuildArtifactsBeforeRunTask)task);
|
||||
}
|
||||
}
|
||||
if (enable && myTasks.isEmpty()) {
|
||||
BuildArtifactsBeforeRunTask task = new BuildArtifactsBeforeRunTask(project);
|
||||
task.addArtifact(artifact);
|
||||
task.setEnabled(true);
|
||||
editor.addBeforeLaunchStep(task);
|
||||
}
|
||||
else {
|
||||
for (BuildArtifactsBeforeRunTask task : myTasks) {
|
||||
if (enable) {
|
||||
task.addArtifact(artifact);
|
||||
task.setEnabled(true);
|
||||
}
|
||||
else {
|
||||
task.removeArtifact(artifact);
|
||||
if (task.getArtifactPointers().isEmpty()) {
|
||||
task.setEnabled(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void setBuildArtifactBeforeRun(@NotNull Project project, @NotNull RunConfiguration configuration, @NotNull Artifact artifact) {
|
||||
RunManagerEx runManager = RunManagerEx.getInstanceEx(project);
|
||||
final List<BuildArtifactsBeforeRunTask> buildArtifactsTasks = runManager.getBeforeRunTasks(configuration, ID);
|
||||
if (buildArtifactsTasks.isEmpty()) { //Add new task if absent
|
||||
BuildArtifactsBeforeRunTask task = new BuildArtifactsBeforeRunTask(project);
|
||||
buildArtifactsTasks.add(task);
|
||||
List<BeforeRunTask> tasks = runManager.getBeforeRunTasks(configuration);
|
||||
tasks.add(task);
|
||||
runManager.setBeforeRunTasks(configuration, tasks, false);
|
||||
}
|
||||
|
||||
for (BuildArtifactsBeforeRunTask task : buildArtifactsTasks) {
|
||||
task.setEnabled(true);
|
||||
task.addArtifact(artifact);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+65
-65
@@ -1,65 +1,65 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @author Eugene Zhuravlev
|
||||
*/
|
||||
package com.intellij.compiler;
|
||||
|
||||
import com.intellij.openapi.components.*;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.util.xmlb.XmlSerializerUtil;
|
||||
|
||||
@State(
|
||||
name = "CompilerWorkspaceConfiguration",
|
||||
storages = {
|
||||
@Storage(
|
||||
file = StoragePathMacros.WORKSPACE_FILE
|
||||
)}
|
||||
)
|
||||
public class CompilerWorkspaceConfiguration implements PersistentStateComponent<CompilerWorkspaceConfiguration> {
|
||||
public static final int DEFAULT_COMPILE_PROCESS_HEAP_SIZE = 700;
|
||||
public static final String DEFAULT_COMPILE_PROCESS_VM_OPTIONS = "-ea";
|
||||
|
||||
public boolean AUTO_SHOW_ERRORS_IN_EDITOR = true;
|
||||
@Deprecated public boolean CLOSE_MESSAGE_VIEW_IF_SUCCESS = true;
|
||||
public boolean CLEAR_OUTPUT_DIRECTORY = true;
|
||||
public boolean USE_COMPILE_SERVER = true;
|
||||
public boolean MAKE_PROJECT_ON_SAVE = true;
|
||||
public boolean PARALLEL_COMPILATION = false;
|
||||
public int COMPILER_PROCESS_HEAP_SIZE = DEFAULT_COMPILE_PROCESS_HEAP_SIZE;
|
||||
public String COMPILER_PROCESS_ADDITIONAL_VM_OPTIONS = DEFAULT_COMPILE_PROCESS_VM_OPTIONS;
|
||||
|
||||
public static CompilerWorkspaceConfiguration getInstance(Project project) {
|
||||
return ServiceManager.getService(project, CompilerWorkspaceConfiguration.class);
|
||||
}
|
||||
|
||||
public CompilerWorkspaceConfiguration getState() {
|
||||
return this;
|
||||
}
|
||||
|
||||
public void loadState(CompilerWorkspaceConfiguration state) {
|
||||
XmlSerializerUtil.copyBean(state, this);
|
||||
}
|
||||
|
||||
public boolean useOutOfProcessBuild() {
|
||||
return USE_COMPILE_SERVER;
|
||||
}
|
||||
|
||||
public boolean allowAutoMakeWhileRunningApplication() {
|
||||
return false;/*ALLOW_AUTOMAKE_WHILE_RUNNING_APPLICATION*/
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @author Eugene Zhuravlev
|
||||
*/
|
||||
package com.intellij.compiler;
|
||||
|
||||
import com.intellij.openapi.components.*;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.util.xmlb.XmlSerializerUtil;
|
||||
|
||||
@State(
|
||||
name = "CompilerWorkspaceConfiguration",
|
||||
storages = {
|
||||
@Storage(
|
||||
file = StoragePathMacros.WORKSPACE_FILE
|
||||
)}
|
||||
)
|
||||
public class CompilerWorkspaceConfiguration implements PersistentStateComponent<CompilerWorkspaceConfiguration> {
|
||||
public static final int DEFAULT_COMPILE_PROCESS_HEAP_SIZE = 700;
|
||||
public static final String DEFAULT_COMPILE_PROCESS_VM_OPTIONS = "-ea";
|
||||
|
||||
public boolean AUTO_SHOW_ERRORS_IN_EDITOR = true;
|
||||
@Deprecated public boolean CLOSE_MESSAGE_VIEW_IF_SUCCESS = true;
|
||||
public boolean CLEAR_OUTPUT_DIRECTORY = true;
|
||||
public boolean USE_COMPILE_SERVER = true;
|
||||
public boolean MAKE_PROJECT_ON_SAVE = true;
|
||||
public boolean PARALLEL_COMPILATION = false;
|
||||
public int COMPILER_PROCESS_HEAP_SIZE = DEFAULT_COMPILE_PROCESS_HEAP_SIZE;
|
||||
public String COMPILER_PROCESS_ADDITIONAL_VM_OPTIONS = DEFAULT_COMPILE_PROCESS_VM_OPTIONS;
|
||||
|
||||
public static CompilerWorkspaceConfiguration getInstance(Project project) {
|
||||
return ServiceManager.getService(project, CompilerWorkspaceConfiguration.class);
|
||||
}
|
||||
|
||||
public CompilerWorkspaceConfiguration getState() {
|
||||
return this;
|
||||
}
|
||||
|
||||
public void loadState(CompilerWorkspaceConfiguration state) {
|
||||
XmlSerializerUtil.copyBean(state, this);
|
||||
}
|
||||
|
||||
public boolean useOutOfProcessBuild() {
|
||||
return USE_COMPILE_SERVER;
|
||||
}
|
||||
|
||||
public boolean allowAutoMakeWhileRunningApplication() {
|
||||
return false;/*ALLOW_AUTOMAKE_WHILE_RUNNING_APPLICATION*/
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,189 +1,189 @@
|
||||
/*
|
||||
* Copyright 2000-2009 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.options;
|
||||
|
||||
import com.intellij.execution.BeforeRunTask;
|
||||
import com.intellij.execution.BeforeRunTaskProvider;
|
||||
import com.intellij.execution.ExecutionBundle;
|
||||
import com.intellij.execution.configurations.RunConfiguration;
|
||||
import com.intellij.execution.configurations.RunConfigurationBase;
|
||||
import com.intellij.execution.configurations.RunProfileWithCompileBeforeLaunchOption;
|
||||
import com.intellij.execution.remote.RemoteConfiguration;
|
||||
import com.intellij.execution.runners.ExecutionEnvironment;
|
||||
import com.intellij.icons.AllIcons;
|
||||
import com.intellij.openapi.actionSystem.DataContext;
|
||||
import com.intellij.openapi.compiler.CompileContext;
|
||||
import com.intellij.openapi.compiler.CompileScope;
|
||||
import com.intellij.openapi.compiler.CompileStatusNotification;
|
||||
import com.intellij.openapi.compiler.CompilerManager;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.module.Module;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.util.Key;
|
||||
import com.intellij.openapi.util.Ref;
|
||||
import com.intellij.util.concurrency.Semaphore;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @author spleaner
|
||||
*/
|
||||
public class CompileStepBeforeRun extends BeforeRunTaskProvider<CompileStepBeforeRun.MakeBeforeRunTask> {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.options.CompileStepBeforeRun");
|
||||
public static final Key<MakeBeforeRunTask> ID = Key.create("Make");
|
||||
private static final Key<RunConfiguration> RUN_CONFIGURATION = Key.create("RUN_CONFIGURATION");
|
||||
private static final Key<String> RUN_CONFIGURATION_TYPE_ID = Key.create("RUN_CONFIGURATION_TYPE_ID");
|
||||
private static final Key<String> RUNNER_ID = Key.create("RUNNER_ID");
|
||||
|
||||
@NonNls protected static final String MAKE_PROJECT_ON_RUN_KEY = "makeProjectOnRun";
|
||||
|
||||
private final Project myProject;
|
||||
|
||||
public CompileStepBeforeRun(@NotNull final Project project) {
|
||||
myProject = project;
|
||||
}
|
||||
|
||||
public Key<MakeBeforeRunTask> getId() {
|
||||
return ID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return ExecutionBundle.message("before.launch.compile.step");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription(MakeBeforeRunTask task) {
|
||||
return ExecutionBundle.message("before.launch.compile.step");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Icon getIcon() {
|
||||
return AllIcons.Actions.Compile;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Icon getTaskIcon(MakeBeforeRunTask task) {
|
||||
return AllIcons.Actions.Compile;
|
||||
}
|
||||
|
||||
public MakeBeforeRunTask createTask(RunConfiguration runConfiguration) {
|
||||
return !(runConfiguration instanceof RemoteConfiguration) && runConfiguration instanceof RunProfileWithCompileBeforeLaunchOption
|
||||
? new MakeBeforeRunTask()
|
||||
: null;
|
||||
}
|
||||
|
||||
public boolean configureTask(RunConfiguration runConfiguration, MakeBeforeRunTask task) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canExecuteTask(RunConfiguration configuration, MakeBeforeRunTask task) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean executeTask(DataContext context, final RunConfiguration configuration, final ExecutionEnvironment env, MakeBeforeRunTask task) {
|
||||
if (!(configuration instanceof RunProfileWithCompileBeforeLaunchOption)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (configuration instanceof RunConfigurationBase && ((RunConfigurationBase)configuration).excludeCompileBeforeLaunchOption()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
final RunProfileWithCompileBeforeLaunchOption runConfiguration = (RunProfileWithCompileBeforeLaunchOption)configuration;
|
||||
final Ref<Boolean> result = new Ref<Boolean>(Boolean.FALSE);
|
||||
try {
|
||||
|
||||
final Semaphore done = new Semaphore();
|
||||
done.down();
|
||||
final CompileStatusNotification callback = new CompileStatusNotification() {
|
||||
public void finished(final boolean aborted, final int errors, final int warnings, CompileContext compileContext) {
|
||||
if (errors == 0 && !aborted) {
|
||||
result.set(Boolean.TRUE);
|
||||
}
|
||||
done.up();
|
||||
}
|
||||
};
|
||||
|
||||
SwingUtilities.invokeAndWait(new Runnable() {
|
||||
public void run() {
|
||||
CompileScope scope;
|
||||
final CompilerManager compilerManager = CompilerManager.getInstance(myProject);
|
||||
if (Boolean.valueOf(System.getProperty(MAKE_PROJECT_ON_RUN_KEY, Boolean.FALSE.toString())).booleanValue()) {
|
||||
// user explicitly requested whole-project make
|
||||
scope = compilerManager.createProjectCompileScope(myProject);
|
||||
}
|
||||
else {
|
||||
final Module[] modules = runConfiguration.getModules();
|
||||
if (modules.length > 0) {
|
||||
for (Module module : modules) {
|
||||
if (module == null) {
|
||||
LOG.error("RunConfiguration should not return null modules. Configuration=" + runConfiguration.getName() + "; class=" +
|
||||
runConfiguration.getClass().getName());
|
||||
}
|
||||
}
|
||||
scope = compilerManager.createModulesCompileScope(modules, true);
|
||||
}
|
||||
else {
|
||||
scope = compilerManager.createProjectCompileScope(myProject);
|
||||
}
|
||||
}
|
||||
|
||||
if (!myProject.isDisposed()) {
|
||||
scope.putUserData(RUN_CONFIGURATION, configuration);
|
||||
scope.putUserData(RUN_CONFIGURATION_TYPE_ID, configuration.getType().getId());
|
||||
scope.putUserData(RUNNER_ID, env.getRunnerId());
|
||||
compilerManager.make(scope, callback);
|
||||
}
|
||||
else {
|
||||
done.up();
|
||||
}
|
||||
}
|
||||
});
|
||||
done.waitFor();
|
||||
}
|
||||
catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return result.get();
|
||||
}
|
||||
|
||||
public boolean isConfigurable() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static RunConfiguration getRunConfiguration(final CompileContext context) {
|
||||
return getRunConfiguration(context.getCompileScope());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static RunConfiguration getRunConfiguration(final CompileScope compileScope) {
|
||||
return compileScope.getUserData(RUN_CONFIGURATION);
|
||||
}
|
||||
|
||||
public static class MakeBeforeRunTask extends BeforeRunTask<MakeBeforeRunTask> {
|
||||
private MakeBeforeRunTask() {
|
||||
super(ID);
|
||||
setEnabled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 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.options;
|
||||
|
||||
import com.intellij.execution.BeforeRunTask;
|
||||
import com.intellij.execution.BeforeRunTaskProvider;
|
||||
import com.intellij.execution.ExecutionBundle;
|
||||
import com.intellij.execution.configurations.RunConfiguration;
|
||||
import com.intellij.execution.configurations.RunConfigurationBase;
|
||||
import com.intellij.execution.configurations.RunProfileWithCompileBeforeLaunchOption;
|
||||
import com.intellij.execution.remote.RemoteConfiguration;
|
||||
import com.intellij.execution.runners.ExecutionEnvironment;
|
||||
import com.intellij.icons.AllIcons;
|
||||
import com.intellij.openapi.actionSystem.DataContext;
|
||||
import com.intellij.openapi.compiler.CompileContext;
|
||||
import com.intellij.openapi.compiler.CompileScope;
|
||||
import com.intellij.openapi.compiler.CompileStatusNotification;
|
||||
import com.intellij.openapi.compiler.CompilerManager;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.module.Module;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.util.Key;
|
||||
import com.intellij.openapi.util.Ref;
|
||||
import com.intellij.util.concurrency.Semaphore;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @author spleaner
|
||||
*/
|
||||
public class CompileStepBeforeRun extends BeforeRunTaskProvider<CompileStepBeforeRun.MakeBeforeRunTask> {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.options.CompileStepBeforeRun");
|
||||
public static final Key<MakeBeforeRunTask> ID = Key.create("Make");
|
||||
private static final Key<RunConfiguration> RUN_CONFIGURATION = Key.create("RUN_CONFIGURATION");
|
||||
private static final Key<String> RUN_CONFIGURATION_TYPE_ID = Key.create("RUN_CONFIGURATION_TYPE_ID");
|
||||
private static final Key<String> RUNNER_ID = Key.create("RUNNER_ID");
|
||||
|
||||
@NonNls protected static final String MAKE_PROJECT_ON_RUN_KEY = "makeProjectOnRun";
|
||||
|
||||
private final Project myProject;
|
||||
|
||||
public CompileStepBeforeRun(@NotNull final Project project) {
|
||||
myProject = project;
|
||||
}
|
||||
|
||||
public Key<MakeBeforeRunTask> getId() {
|
||||
return ID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return ExecutionBundle.message("before.launch.compile.step");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription(MakeBeforeRunTask task) {
|
||||
return ExecutionBundle.message("before.launch.compile.step");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Icon getIcon() {
|
||||
return AllIcons.Actions.Compile;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Icon getTaskIcon(MakeBeforeRunTask task) {
|
||||
return AllIcons.Actions.Compile;
|
||||
}
|
||||
|
||||
public MakeBeforeRunTask createTask(RunConfiguration runConfiguration) {
|
||||
return !(runConfiguration instanceof RemoteConfiguration) && runConfiguration instanceof RunProfileWithCompileBeforeLaunchOption
|
||||
? new MakeBeforeRunTask()
|
||||
: null;
|
||||
}
|
||||
|
||||
public boolean configureTask(RunConfiguration runConfiguration, MakeBeforeRunTask task) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canExecuteTask(RunConfiguration configuration, MakeBeforeRunTask task) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean executeTask(DataContext context, final RunConfiguration configuration, final ExecutionEnvironment env, MakeBeforeRunTask task) {
|
||||
if (!(configuration instanceof RunProfileWithCompileBeforeLaunchOption)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (configuration instanceof RunConfigurationBase && ((RunConfigurationBase)configuration).excludeCompileBeforeLaunchOption()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
final RunProfileWithCompileBeforeLaunchOption runConfiguration = (RunProfileWithCompileBeforeLaunchOption)configuration;
|
||||
final Ref<Boolean> result = new Ref<Boolean>(Boolean.FALSE);
|
||||
try {
|
||||
|
||||
final Semaphore done = new Semaphore();
|
||||
done.down();
|
||||
final CompileStatusNotification callback = new CompileStatusNotification() {
|
||||
public void finished(final boolean aborted, final int errors, final int warnings, CompileContext compileContext) {
|
||||
if (errors == 0 && !aborted) {
|
||||
result.set(Boolean.TRUE);
|
||||
}
|
||||
done.up();
|
||||
}
|
||||
};
|
||||
|
||||
SwingUtilities.invokeAndWait(new Runnable() {
|
||||
public void run() {
|
||||
CompileScope scope;
|
||||
final CompilerManager compilerManager = CompilerManager.getInstance(myProject);
|
||||
if (Boolean.valueOf(System.getProperty(MAKE_PROJECT_ON_RUN_KEY, Boolean.FALSE.toString())).booleanValue()) {
|
||||
// user explicitly requested whole-project make
|
||||
scope = compilerManager.createProjectCompileScope(myProject);
|
||||
}
|
||||
else {
|
||||
final Module[] modules = runConfiguration.getModules();
|
||||
if (modules.length > 0) {
|
||||
for (Module module : modules) {
|
||||
if (module == null) {
|
||||
LOG.error("RunConfiguration should not return null modules. Configuration=" + runConfiguration.getName() + "; class=" +
|
||||
runConfiguration.getClass().getName());
|
||||
}
|
||||
}
|
||||
scope = compilerManager.createModulesCompileScope(modules, true);
|
||||
}
|
||||
else {
|
||||
scope = compilerManager.createProjectCompileScope(myProject);
|
||||
}
|
||||
}
|
||||
|
||||
if (!myProject.isDisposed()) {
|
||||
scope.putUserData(RUN_CONFIGURATION, configuration);
|
||||
scope.putUserData(RUN_CONFIGURATION_TYPE_ID, configuration.getType().getId());
|
||||
scope.putUserData(RUNNER_ID, env.getRunnerId());
|
||||
compilerManager.make(scope, callback);
|
||||
}
|
||||
else {
|
||||
done.up();
|
||||
}
|
||||
}
|
||||
});
|
||||
done.waitFor();
|
||||
}
|
||||
catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return result.get();
|
||||
}
|
||||
|
||||
public boolean isConfigurable() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static RunConfiguration getRunConfiguration(final CompileContext context) {
|
||||
return getRunConfiguration(context.getCompileScope());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static RunConfiguration getRunConfiguration(final CompileScope compileScope) {
|
||||
return compileScope.getUserData(RUN_CONFIGURATION);
|
||||
}
|
||||
|
||||
public static class MakeBeforeRunTask extends BeforeRunTask<MakeBeforeRunTask> {
|
||||
private MakeBeforeRunTask() {
|
||||
super(ID);
|
||||
setEnabled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+250
-250
@@ -1,250 +1,250 @@
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.codeInsight.ExpectedTypeInfo;
|
||||
import com.intellij.codeInsight.ExpectedTypesProvider;
|
||||
import com.intellij.codeInsight.generation.GenerateMembersUtil;
|
||||
import com.intellij.codeInsight.generation.OverrideImplementUtil;
|
||||
import com.intellij.codeInsight.generation.PsiGenerationInfo;
|
||||
import com.intellij.codeInsight.lookup.Lookup;
|
||||
import com.intellij.codeInsight.lookup.LookupElementDecorator;
|
||||
import com.intellij.codeInsight.lookup.LookupItem;
|
||||
import com.intellij.codeInsight.lookup.PsiTypeLookupItem;
|
||||
import com.intellij.featureStatistics.FeatureUsageTracker;
|
||||
import com.intellij.openapi.application.ApplicationManager;
|
||||
import com.intellij.openapi.command.CommandProcessor;
|
||||
import com.intellij.openapi.command.UndoConfirmationPolicy;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.editor.ScrollType;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.codeStyle.CodeStyleManager;
|
||||
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
|
||||
import com.intellij.psi.infos.CandidateInfo;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public class ConstructorInsertHandler implements InsertHandler<LookupElementDecorator<LookupItem>> {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.ConstructorInsertHandler");
|
||||
public static final ConstructorInsertHandler SMART_INSTANCE = new ConstructorInsertHandler(true);
|
||||
public static final ConstructorInsertHandler BASIC_INSTANCE = new ConstructorInsertHandler(false);
|
||||
static final OffsetKey PARAM_LIST_START = OffsetKey.create("paramListStart");
|
||||
static final OffsetKey PARAM_LIST_END = OffsetKey.create("paramListEnd");
|
||||
private final boolean mySmart;
|
||||
|
||||
private ConstructorInsertHandler(boolean smart) {
|
||||
mySmart = smart;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleInsert(InsertionContext context, LookupElementDecorator<LookupItem> item) {
|
||||
@SuppressWarnings({"unchecked"}) final LookupItem<PsiClass> delegate = item.getDelegate();
|
||||
|
||||
PsiClass psiClass = (PsiClass)item.getObject();
|
||||
|
||||
boolean isAbstract = psiClass.hasModifierProperty(PsiModifier.ABSTRACT);
|
||||
|
||||
if (Lookup.REPLACE_SELECT_CHAR == context.getCompletionChar()) {
|
||||
final int plStart = context.getOffset(PARAM_LIST_START);
|
||||
final int plEnd = context.getOffset(PARAM_LIST_END);
|
||||
if (plStart >= 0 && plEnd >= 0) {
|
||||
context.getDocument().deleteString(plStart, plEnd);
|
||||
}
|
||||
}
|
||||
|
||||
context.commitDocument();
|
||||
|
||||
OffsetKey insideRef = context.trackOffset(context.getTailOffset(), false);
|
||||
|
||||
final PsiElement position = SmartCompletionDecorator.getPosition(context, delegate);
|
||||
final PsiExpression enclosing = PsiTreeUtil.getContextOfType(position, PsiExpression.class, true);
|
||||
final PsiAnonymousClass anonymousClass = PsiTreeUtil.getParentOfType(position, PsiAnonymousClass.class);
|
||||
final boolean inAnonymous = anonymousClass != null && anonymousClass.getParent() == enclosing;
|
||||
boolean fillTypeArgs = false;
|
||||
if (delegate instanceof PsiTypeLookupItem) {
|
||||
fillTypeArgs = !isRawTypeExpected(context, (PsiTypeLookupItem)delegate) &&
|
||||
psiClass.getTypeParameters().length > 0 &&
|
||||
((PsiTypeLookupItem)delegate).calcGenerics(position, context).isEmpty() &&
|
||||
context.getCompletionChar() != '(';
|
||||
|
||||
if (context.getDocument().getTextLength() > context.getTailOffset() &&
|
||||
context.getDocument().getCharsSequence().charAt(context.getTailOffset()) == '<') {
|
||||
PsiJavaCodeReferenceElement ref = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getTailOffset(), PsiJavaCodeReferenceElement.class, false);
|
||||
if (ref != null) {
|
||||
PsiReferenceParameterList parameterList = ref.getParameterList();
|
||||
if (parameterList != null && context.getTailOffset() == parameterList.getTextRange().getStartOffset()) {
|
||||
context.getDocument().deleteString(parameterList.getTextRange().getStartOffset(), parameterList.getTextRange().getEndOffset());
|
||||
context.commitDocument();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
delegate.handleInsert(context);
|
||||
PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(context.getFile().getViewProvider());
|
||||
}
|
||||
|
||||
if (item.getDelegate() instanceof JavaPsiClassReferenceElement) {
|
||||
PsiTypeLookupItem.addImportForItem(context, psiClass);
|
||||
}
|
||||
|
||||
|
||||
insertParentheses(context, delegate, psiClass, !inAnonymous && isAbstract);
|
||||
|
||||
if (inAnonymous) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (mySmart) {
|
||||
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.AFTER_NEW);
|
||||
}
|
||||
if (isAbstract) {
|
||||
PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(context.getFile().getViewProvider());
|
||||
|
||||
final Editor editor = context.getEditor();
|
||||
final int offset = context.getTailOffset();
|
||||
editor.getDocument().insertString(offset, " {}");
|
||||
editor.getCaretModel().moveToOffset(offset + 2);
|
||||
|
||||
if (fillTypeArgs && JavaCompletionUtil.promptTypeArgs(context, context.getOffset(insideRef))) return;
|
||||
|
||||
context.setLaterRunnable(generateAnonymousBody(editor, context.getFile()));
|
||||
}
|
||||
else {
|
||||
PsiDocumentManager.getInstance(context.getProject()).commitAllDocuments();
|
||||
final PsiNewExpression newExpression =
|
||||
PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiNewExpression.class, false);
|
||||
if (newExpression != null) {
|
||||
final PsiJavaCodeReferenceElement classReference = newExpression.getClassOrAnonymousClassReference();
|
||||
if (classReference != null) {
|
||||
CodeStyleManager.getInstance(context.getProject()).reformat(classReference);
|
||||
}
|
||||
}
|
||||
if (mySmart) {
|
||||
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.AFTER_NEW);
|
||||
}
|
||||
if (fillTypeArgs && JavaCompletionUtil.promptTypeArgs(context, context.getOffset(insideRef))) return;
|
||||
}
|
||||
}
|
||||
|
||||
static boolean isRawTypeExpected(InsertionContext context, PsiTypeLookupItem delegate) {
|
||||
PsiNewExpression newExpr =
|
||||
PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiNewExpression.class, false);
|
||||
if (newExpr != null) {
|
||||
for (ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes(newExpr, true)) {
|
||||
PsiType expected = info.getDefaultType();
|
||||
if (expected.isAssignableFrom(delegate.getPsiType())) {
|
||||
if (expected instanceof PsiClassType && ((PsiClassType)expected).isRaw()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean insertParentheses(InsertionContext context,
|
||||
LookupItem delegate,
|
||||
final PsiClass psiClass,
|
||||
final boolean forAnonymous) {
|
||||
if (context.getCompletionChar() == '[') {
|
||||
return false;
|
||||
}
|
||||
|
||||
final PsiElement place = context.getFile().findElementAt(context.getStartOffset());
|
||||
assert place != null;
|
||||
boolean hasParams = hasConstructorParameters(psiClass, place);
|
||||
|
||||
JavaCompletionUtil.insertParentheses(context, delegate, false, hasParams, forAnonymous);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static boolean hasConstructorParameters(PsiClass psiClass, @NotNull PsiElement place) {
|
||||
final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(place.getProject()).getResolveHelper();
|
||||
boolean hasParams = false;
|
||||
for (PsiMethod constructor : psiClass.getConstructors()) {
|
||||
if (!resolveHelper.isAccessible(constructor, place, null)) continue;
|
||||
if (constructor.getParameterList().getParametersCount() > 0) {
|
||||
hasParams = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return hasParams;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static Runnable generateAnonymousBody(final Editor editor, final PsiFile file) {
|
||||
final Project project = file.getProject();
|
||||
PsiDocumentManager.getInstance(project).commitAllDocuments();
|
||||
|
||||
int offset = editor.getCaretModel().getOffset();
|
||||
PsiElement element = file.findElementAt(offset);
|
||||
if (element == null) return null;
|
||||
|
||||
PsiElement parent = element.getParent();
|
||||
if (!(parent instanceof PsiAnonymousClass)) return null;
|
||||
|
||||
return genAnonymousBodyFor((PsiAnonymousClass)parent, editor, file, project);
|
||||
}
|
||||
|
||||
public static Runnable genAnonymousBodyFor(PsiAnonymousClass parent,
|
||||
final Editor editor,
|
||||
final PsiFile file,
|
||||
final Project project) {
|
||||
try {
|
||||
CodeStyleManager.getInstance(project).reformat(parent);
|
||||
}
|
||||
catch (IncorrectOperationException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
int offset = parent.getTextRange().getEndOffset() - 1;
|
||||
editor.getCaretModel().moveToOffset(offset);
|
||||
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
|
||||
editor.getSelectionModel().removeSelection();
|
||||
|
||||
return new Runnable() {
|
||||
@Override
|
||||
public void run(){
|
||||
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
|
||||
final PsiAnonymousClass aClass = PsiTreeUtil.findElementOfClassAtOffset(file, editor.getCaretModel().getOffset(), PsiAnonymousClass.class, false);
|
||||
if (aClass == null) return;
|
||||
|
||||
final Collection<CandidateInfo> candidatesToImplement = OverrideImplementUtil.getMethodsToOverrideImplement(aClass, true);
|
||||
boolean invokeOverride = candidatesToImplement.isEmpty();
|
||||
if (invokeOverride){
|
||||
OverrideImplementUtil.chooseAndOverrideOrImplementMethods(project, editor, aClass, false);
|
||||
}
|
||||
else{
|
||||
ApplicationManager.getApplication().runWriteAction(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try{
|
||||
List<PsiMethod> methods = OverrideImplementUtil.overrideOrImplementMethodCandidates(aClass, candidatesToImplement, false);
|
||||
List<PsiGenerationInfo<PsiMethod>> prototypes = OverrideImplementUtil.convert2GenerationInfos(methods);
|
||||
List<PsiGenerationInfo<PsiMethod>> resultMembers = GenerateMembersUtil.insertMembersBeforeAnchor(aClass, null, prototypes);
|
||||
resultMembers.get(0).positionCaret(editor, true);
|
||||
}
|
||||
catch(IncorrectOperationException ioe){
|
||||
LOG.error(ioe);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}, CompletionBundle.message("completion.smart.type.generate.anonymous.body"), null, UndoConfirmationPolicy.DEFAULT, editor.getDocument());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.codeInsight.ExpectedTypeInfo;
|
||||
import com.intellij.codeInsight.ExpectedTypesProvider;
|
||||
import com.intellij.codeInsight.generation.GenerateMembersUtil;
|
||||
import com.intellij.codeInsight.generation.OverrideImplementUtil;
|
||||
import com.intellij.codeInsight.generation.PsiGenerationInfo;
|
||||
import com.intellij.codeInsight.lookup.Lookup;
|
||||
import com.intellij.codeInsight.lookup.LookupElementDecorator;
|
||||
import com.intellij.codeInsight.lookup.LookupItem;
|
||||
import com.intellij.codeInsight.lookup.PsiTypeLookupItem;
|
||||
import com.intellij.featureStatistics.FeatureUsageTracker;
|
||||
import com.intellij.openapi.application.ApplicationManager;
|
||||
import com.intellij.openapi.command.CommandProcessor;
|
||||
import com.intellij.openapi.command.UndoConfirmationPolicy;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.editor.ScrollType;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.codeStyle.CodeStyleManager;
|
||||
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
|
||||
import com.intellij.psi.infos.CandidateInfo;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public class ConstructorInsertHandler implements InsertHandler<LookupElementDecorator<LookupItem>> {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.ConstructorInsertHandler");
|
||||
public static final ConstructorInsertHandler SMART_INSTANCE = new ConstructorInsertHandler(true);
|
||||
public static final ConstructorInsertHandler BASIC_INSTANCE = new ConstructorInsertHandler(false);
|
||||
static final OffsetKey PARAM_LIST_START = OffsetKey.create("paramListStart");
|
||||
static final OffsetKey PARAM_LIST_END = OffsetKey.create("paramListEnd");
|
||||
private final boolean mySmart;
|
||||
|
||||
private ConstructorInsertHandler(boolean smart) {
|
||||
mySmart = smart;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleInsert(InsertionContext context, LookupElementDecorator<LookupItem> item) {
|
||||
@SuppressWarnings({"unchecked"}) final LookupItem<PsiClass> delegate = item.getDelegate();
|
||||
|
||||
PsiClass psiClass = (PsiClass)item.getObject();
|
||||
|
||||
boolean isAbstract = psiClass.hasModifierProperty(PsiModifier.ABSTRACT);
|
||||
|
||||
if (Lookup.REPLACE_SELECT_CHAR == context.getCompletionChar()) {
|
||||
final int plStart = context.getOffset(PARAM_LIST_START);
|
||||
final int plEnd = context.getOffset(PARAM_LIST_END);
|
||||
if (plStart >= 0 && plEnd >= 0) {
|
||||
context.getDocument().deleteString(plStart, plEnd);
|
||||
}
|
||||
}
|
||||
|
||||
context.commitDocument();
|
||||
|
||||
OffsetKey insideRef = context.trackOffset(context.getTailOffset(), false);
|
||||
|
||||
final PsiElement position = SmartCompletionDecorator.getPosition(context, delegate);
|
||||
final PsiExpression enclosing = PsiTreeUtil.getContextOfType(position, PsiExpression.class, true);
|
||||
final PsiAnonymousClass anonymousClass = PsiTreeUtil.getParentOfType(position, PsiAnonymousClass.class);
|
||||
final boolean inAnonymous = anonymousClass != null && anonymousClass.getParent() == enclosing;
|
||||
boolean fillTypeArgs = false;
|
||||
if (delegate instanceof PsiTypeLookupItem) {
|
||||
fillTypeArgs = !isRawTypeExpected(context, (PsiTypeLookupItem)delegate) &&
|
||||
psiClass.getTypeParameters().length > 0 &&
|
||||
((PsiTypeLookupItem)delegate).calcGenerics(position, context).isEmpty() &&
|
||||
context.getCompletionChar() != '(';
|
||||
|
||||
if (context.getDocument().getTextLength() > context.getTailOffset() &&
|
||||
context.getDocument().getCharsSequence().charAt(context.getTailOffset()) == '<') {
|
||||
PsiJavaCodeReferenceElement ref = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getTailOffset(), PsiJavaCodeReferenceElement.class, false);
|
||||
if (ref != null) {
|
||||
PsiReferenceParameterList parameterList = ref.getParameterList();
|
||||
if (parameterList != null && context.getTailOffset() == parameterList.getTextRange().getStartOffset()) {
|
||||
context.getDocument().deleteString(parameterList.getTextRange().getStartOffset(), parameterList.getTextRange().getEndOffset());
|
||||
context.commitDocument();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
delegate.handleInsert(context);
|
||||
PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(context.getFile().getViewProvider());
|
||||
}
|
||||
|
||||
if (item.getDelegate() instanceof JavaPsiClassReferenceElement) {
|
||||
PsiTypeLookupItem.addImportForItem(context, psiClass);
|
||||
}
|
||||
|
||||
|
||||
insertParentheses(context, delegate, psiClass, !inAnonymous && isAbstract);
|
||||
|
||||
if (inAnonymous) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (mySmart) {
|
||||
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.AFTER_NEW);
|
||||
}
|
||||
if (isAbstract) {
|
||||
PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(context.getFile().getViewProvider());
|
||||
|
||||
final Editor editor = context.getEditor();
|
||||
final int offset = context.getTailOffset();
|
||||
editor.getDocument().insertString(offset, " {}");
|
||||
editor.getCaretModel().moveToOffset(offset + 2);
|
||||
|
||||
if (fillTypeArgs && JavaCompletionUtil.promptTypeArgs(context, context.getOffset(insideRef))) return;
|
||||
|
||||
context.setLaterRunnable(generateAnonymousBody(editor, context.getFile()));
|
||||
}
|
||||
else {
|
||||
PsiDocumentManager.getInstance(context.getProject()).commitAllDocuments();
|
||||
final PsiNewExpression newExpression =
|
||||
PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiNewExpression.class, false);
|
||||
if (newExpression != null) {
|
||||
final PsiJavaCodeReferenceElement classReference = newExpression.getClassOrAnonymousClassReference();
|
||||
if (classReference != null) {
|
||||
CodeStyleManager.getInstance(context.getProject()).reformat(classReference);
|
||||
}
|
||||
}
|
||||
if (mySmart) {
|
||||
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.AFTER_NEW);
|
||||
}
|
||||
if (fillTypeArgs && JavaCompletionUtil.promptTypeArgs(context, context.getOffset(insideRef))) return;
|
||||
}
|
||||
}
|
||||
|
||||
static boolean isRawTypeExpected(InsertionContext context, PsiTypeLookupItem delegate) {
|
||||
PsiNewExpression newExpr =
|
||||
PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiNewExpression.class, false);
|
||||
if (newExpr != null) {
|
||||
for (ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes(newExpr, true)) {
|
||||
PsiType expected = info.getDefaultType();
|
||||
if (expected.isAssignableFrom(delegate.getPsiType())) {
|
||||
if (expected instanceof PsiClassType && ((PsiClassType)expected).isRaw()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean insertParentheses(InsertionContext context,
|
||||
LookupItem delegate,
|
||||
final PsiClass psiClass,
|
||||
final boolean forAnonymous) {
|
||||
if (context.getCompletionChar() == '[') {
|
||||
return false;
|
||||
}
|
||||
|
||||
final PsiElement place = context.getFile().findElementAt(context.getStartOffset());
|
||||
assert place != null;
|
||||
boolean hasParams = hasConstructorParameters(psiClass, place);
|
||||
|
||||
JavaCompletionUtil.insertParentheses(context, delegate, false, hasParams, forAnonymous);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static boolean hasConstructorParameters(PsiClass psiClass, @NotNull PsiElement place) {
|
||||
final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(place.getProject()).getResolveHelper();
|
||||
boolean hasParams = false;
|
||||
for (PsiMethod constructor : psiClass.getConstructors()) {
|
||||
if (!resolveHelper.isAccessible(constructor, place, null)) continue;
|
||||
if (constructor.getParameterList().getParametersCount() > 0) {
|
||||
hasParams = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return hasParams;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static Runnable generateAnonymousBody(final Editor editor, final PsiFile file) {
|
||||
final Project project = file.getProject();
|
||||
PsiDocumentManager.getInstance(project).commitAllDocuments();
|
||||
|
||||
int offset = editor.getCaretModel().getOffset();
|
||||
PsiElement element = file.findElementAt(offset);
|
||||
if (element == null) return null;
|
||||
|
||||
PsiElement parent = element.getParent();
|
||||
if (!(parent instanceof PsiAnonymousClass)) return null;
|
||||
|
||||
return genAnonymousBodyFor((PsiAnonymousClass)parent, editor, file, project);
|
||||
}
|
||||
|
||||
public static Runnable genAnonymousBodyFor(PsiAnonymousClass parent,
|
||||
final Editor editor,
|
||||
final PsiFile file,
|
||||
final Project project) {
|
||||
try {
|
||||
CodeStyleManager.getInstance(project).reformat(parent);
|
||||
}
|
||||
catch (IncorrectOperationException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
int offset = parent.getTextRange().getEndOffset() - 1;
|
||||
editor.getCaretModel().moveToOffset(offset);
|
||||
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
|
||||
editor.getSelectionModel().removeSelection();
|
||||
|
||||
return new Runnable() {
|
||||
@Override
|
||||
public void run(){
|
||||
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
|
||||
final PsiAnonymousClass aClass = PsiTreeUtil.findElementOfClassAtOffset(file, editor.getCaretModel().getOffset(), PsiAnonymousClass.class, false);
|
||||
if (aClass == null) return;
|
||||
|
||||
final Collection<CandidateInfo> candidatesToImplement = OverrideImplementUtil.getMethodsToOverrideImplement(aClass, true);
|
||||
boolean invokeOverride = candidatesToImplement.isEmpty();
|
||||
if (invokeOverride){
|
||||
OverrideImplementUtil.chooseAndOverrideOrImplementMethods(project, editor, aClass, false);
|
||||
}
|
||||
else{
|
||||
ApplicationManager.getApplication().runWriteAction(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try{
|
||||
List<PsiMethod> methods = OverrideImplementUtil.overrideOrImplementMethodCandidates(aClass, candidatesToImplement, false);
|
||||
List<PsiGenerationInfo<PsiMethod>> prototypes = OverrideImplementUtil.convert2GenerationInfos(methods);
|
||||
List<PsiGenerationInfo<PsiMethod>> resultMembers = GenerateMembersUtil.insertMembersBeforeAnchor(aClass, null, prototypes);
|
||||
resultMembers.get(0).positionCaret(editor, true);
|
||||
}
|
||||
catch(IncorrectOperationException ioe){
|
||||
LOG.error(ioe);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}, CompletionBundle.message("completion.smart.type.generate.anonymous.body"), null, UndoConfirmationPolicy.DEFAULT, editor.getDocument());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+183
-183
@@ -1,183 +1,183 @@
|
||||
/*
|
||||
* Copyright 2000-2009 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.completion;
|
||||
|
||||
import com.intellij.codeInsight.ExpectedTypeInfo;
|
||||
import com.intellij.codeInsight.ExpectedTypesProvider;
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
import com.intellij.lang.LangBundle;
|
||||
import com.intellij.lang.java.JavaLanguage;
|
||||
import com.intellij.openapi.actionSystem.IdeActions;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.fileTypes.impl.CustomSyntaxTableFileType;
|
||||
import com.intellij.openapi.util.Condition;
|
||||
import com.intellij.openapi.util.text.StringUtil;
|
||||
import com.intellij.patterns.PsiJavaElementPattern;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.filters.ClassFilter;
|
||||
import com.intellij.psi.filters.ElementFilter;
|
||||
import com.intellij.psi.filters.TrueFilter;
|
||||
import com.intellij.psi.filters.element.ExcludeDeclaredFilter;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.psi.util.PsiUtil;
|
||||
import com.intellij.util.Consumer;
|
||||
import com.intellij.util.SmartList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static com.intellij.patterns.PsiJavaPatterns.psiElement;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public class JavaClassNameCompletionContributor extends CompletionContributor {
|
||||
public static final PsiJavaElementPattern.Capture<PsiElement> AFTER_NEW = psiElement().afterLeaf(PsiKeyword.NEW);
|
||||
private static final PsiJavaElementPattern.Capture<PsiElement> IN_TYPE_PARAMETER =
|
||||
psiElement().afterLeaf(PsiKeyword.EXTENDS, PsiKeyword.SUPER, "&").withParent(
|
||||
psiElement(PsiReferenceList.class).withParent(PsiTypeParameter.class));
|
||||
|
||||
@Override
|
||||
public void fillCompletionVariants(CompletionParameters parameters, final CompletionResultSet _result) {
|
||||
if (parameters.getCompletionType() == CompletionType.CLASS_NAME ||
|
||||
parameters.isExtendedCompletion() && mayContainClassName(parameters)) {
|
||||
addAllClasses(parameters, _result);
|
||||
}
|
||||
}
|
||||
|
||||
static void addAllClasses(CompletionParameters parameters, final CompletionResultSet _result) {
|
||||
CompletionResultSet result = _result.withPrefixMatcher(CompletionUtil.findReferenceOrAlphanumericPrefix(parameters));
|
||||
addAllClasses(parameters, parameters.getInvocationCount() <= 1, result.getPrefixMatcher(), _result);
|
||||
}
|
||||
|
||||
private static boolean mayContainClassName(CompletionParameters parameters) {
|
||||
PsiElement position = parameters.getPosition();
|
||||
PsiFile file = position.getContainingFile();
|
||||
if (file instanceof PsiPlainTextFile || file.getFileType() instanceof CustomSyntaxTableFileType) {
|
||||
return true;
|
||||
}
|
||||
if (SkipAutopopupInStrings.isInStringLiteral(position)) {
|
||||
return true;
|
||||
}
|
||||
if (PsiTreeUtil.getParentOfType(position, PsiComment.class, false) != null) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void addAllClasses(CompletionParameters parameters,
|
||||
final boolean filterByScope,
|
||||
@NotNull final PrefixMatcher matcher,
|
||||
@NotNull final Consumer<LookupElement> consumer) {
|
||||
final PsiElement insertedElement = parameters.getPosition();
|
||||
|
||||
final ElementFilter filter =
|
||||
IN_TYPE_PARAMETER.accepts(insertedElement) ? new ExcludeDeclaredFilter(new ClassFilter(PsiTypeParameter.class)) : TrueFilter.INSTANCE;
|
||||
|
||||
final boolean inJavaContext = parameters.getPosition() instanceof PsiIdentifier;
|
||||
final boolean afterNew = AFTER_NEW.accepts(insertedElement);
|
||||
if (afterNew) {
|
||||
final PsiExpression expr = PsiTreeUtil.getContextOfType(insertedElement, PsiExpression.class, true);
|
||||
for (final ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes(expr, true)) {
|
||||
final PsiType type = info.getType();
|
||||
final PsiClass psiClass = PsiUtil.resolveClassInType(type);
|
||||
if (psiClass != null) {
|
||||
consumer.consume(createClassLookupItem(psiClass, inJavaContext));
|
||||
}
|
||||
final PsiType defaultType = info.getDefaultType();
|
||||
if (!defaultType.equals(type)) {
|
||||
final PsiClass defClass = PsiUtil.resolveClassInType(defaultType);
|
||||
if (defClass != null) {
|
||||
consumer.consume(createClassLookupItem(defClass, true));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final boolean pkgContext = JavaCompletionUtil.inSomePackage(insertedElement);
|
||||
AllClassesGetter.processJavaClasses(parameters, matcher, filterByScope, new Consumer<PsiClass>() {
|
||||
@Override
|
||||
public void consume(PsiClass psiClass) {
|
||||
if (filter.isAcceptable(psiClass, insertedElement)) {
|
||||
if (!inJavaContext) {
|
||||
consumer.consume(AllClassesGetter.createLookupItem(psiClass, AllClassesGetter.TRY_SHORTENING));
|
||||
} else {
|
||||
for (JavaPsiClassReferenceElement element : createClassLookupItems(psiClass, afterNew,
|
||||
JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER, new Condition<PsiClass>() {
|
||||
@Override
|
||||
public boolean value(PsiClass psiClass) {
|
||||
return filter.isAcceptable(psiClass, insertedElement) &&
|
||||
AllClassesGetter.isAcceptableInContext(insertedElement, psiClass, filterByScope, pkgContext);
|
||||
}
|
||||
})) {
|
||||
consumer.consume(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static JavaPsiClassReferenceElement createClassLookupItem(final PsiClass psiClass, final boolean inJavaContext) {
|
||||
return AllClassesGetter.createLookupItem(psiClass, inJavaContext ? JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER
|
||||
: AllClassesGetter.TRY_SHORTENING);
|
||||
}
|
||||
|
||||
public static List<JavaPsiClassReferenceElement> createClassLookupItems(final PsiClass psiClass,
|
||||
boolean withInners,
|
||||
InsertHandler<JavaPsiClassReferenceElement> insertHandler,
|
||||
Condition<PsiClass> condition) {
|
||||
List<JavaPsiClassReferenceElement> result = new SmartList<JavaPsiClassReferenceElement>();
|
||||
if (condition.value(psiClass)) {
|
||||
result.add(AllClassesGetter.createLookupItem(psiClass, insertHandler));
|
||||
}
|
||||
String name = psiClass.getName();
|
||||
if (withInners && name != null) {
|
||||
for (PsiClass inner : psiClass.getInnerClasses()) {
|
||||
if (inner.hasModifierProperty(PsiModifier.STATIC)) {
|
||||
for (JavaPsiClassReferenceElement lookupInner : createClassLookupItems(inner, withInners, insertHandler, condition)) {
|
||||
String forced = lookupInner.getForcedPresentableName();
|
||||
lookupInner.setForcedPresentableName(name + "." + (forced != null ? forced : inner.getName()));
|
||||
result.add(lookupInner);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public String handleEmptyLookup(@NotNull final CompletionParameters parameters, final Editor editor) {
|
||||
if (!(parameters.getOriginalFile() instanceof PsiJavaFile)) return null;
|
||||
|
||||
if (shouldShowSecondSmartCompletionHint(parameters)) {
|
||||
return LangBundle.message("completion.no.suggestions") +
|
||||
"; " +
|
||||
StringUtil.decapitalize(
|
||||
CompletionBundle.message("completion.class.name.hint.2", getActionShortcut(IdeActions.ACTION_CODE_COMPLETION)));
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean shouldShowSecondSmartCompletionHint(final CompletionParameters parameters) {
|
||||
return parameters.getCompletionType() == CompletionType.BASIC &&
|
||||
parameters.getInvocationCount() == 2 &&
|
||||
parameters.getOriginalFile().getLanguage().isKindOf(JavaLanguage.INSTANCE);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 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.completion;
|
||||
|
||||
import com.intellij.codeInsight.ExpectedTypeInfo;
|
||||
import com.intellij.codeInsight.ExpectedTypesProvider;
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
import com.intellij.lang.LangBundle;
|
||||
import com.intellij.lang.java.JavaLanguage;
|
||||
import com.intellij.openapi.actionSystem.IdeActions;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.fileTypes.impl.CustomSyntaxTableFileType;
|
||||
import com.intellij.openapi.util.Condition;
|
||||
import com.intellij.openapi.util.text.StringUtil;
|
||||
import com.intellij.patterns.PsiJavaElementPattern;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.filters.ClassFilter;
|
||||
import com.intellij.psi.filters.ElementFilter;
|
||||
import com.intellij.psi.filters.TrueFilter;
|
||||
import com.intellij.psi.filters.element.ExcludeDeclaredFilter;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.psi.util.PsiUtil;
|
||||
import com.intellij.util.Consumer;
|
||||
import com.intellij.util.SmartList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static com.intellij.patterns.PsiJavaPatterns.psiElement;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public class JavaClassNameCompletionContributor extends CompletionContributor {
|
||||
public static final PsiJavaElementPattern.Capture<PsiElement> AFTER_NEW = psiElement().afterLeaf(PsiKeyword.NEW);
|
||||
private static final PsiJavaElementPattern.Capture<PsiElement> IN_TYPE_PARAMETER =
|
||||
psiElement().afterLeaf(PsiKeyword.EXTENDS, PsiKeyword.SUPER, "&").withParent(
|
||||
psiElement(PsiReferenceList.class).withParent(PsiTypeParameter.class));
|
||||
|
||||
@Override
|
||||
public void fillCompletionVariants(CompletionParameters parameters, final CompletionResultSet _result) {
|
||||
if (parameters.getCompletionType() == CompletionType.CLASS_NAME ||
|
||||
parameters.isExtendedCompletion() && mayContainClassName(parameters)) {
|
||||
addAllClasses(parameters, _result);
|
||||
}
|
||||
}
|
||||
|
||||
static void addAllClasses(CompletionParameters parameters, final CompletionResultSet _result) {
|
||||
CompletionResultSet result = _result.withPrefixMatcher(CompletionUtil.findReferenceOrAlphanumericPrefix(parameters));
|
||||
addAllClasses(parameters, parameters.getInvocationCount() <= 1, result.getPrefixMatcher(), _result);
|
||||
}
|
||||
|
||||
private static boolean mayContainClassName(CompletionParameters parameters) {
|
||||
PsiElement position = parameters.getPosition();
|
||||
PsiFile file = position.getContainingFile();
|
||||
if (file instanceof PsiPlainTextFile || file.getFileType() instanceof CustomSyntaxTableFileType) {
|
||||
return true;
|
||||
}
|
||||
if (SkipAutopopupInStrings.isInStringLiteral(position)) {
|
||||
return true;
|
||||
}
|
||||
if (PsiTreeUtil.getParentOfType(position, PsiComment.class, false) != null) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void addAllClasses(CompletionParameters parameters,
|
||||
final boolean filterByScope,
|
||||
@NotNull final PrefixMatcher matcher,
|
||||
@NotNull final Consumer<LookupElement> consumer) {
|
||||
final PsiElement insertedElement = parameters.getPosition();
|
||||
|
||||
final ElementFilter filter =
|
||||
IN_TYPE_PARAMETER.accepts(insertedElement) ? new ExcludeDeclaredFilter(new ClassFilter(PsiTypeParameter.class)) : TrueFilter.INSTANCE;
|
||||
|
||||
final boolean inJavaContext = parameters.getPosition() instanceof PsiIdentifier;
|
||||
final boolean afterNew = AFTER_NEW.accepts(insertedElement);
|
||||
if (afterNew) {
|
||||
final PsiExpression expr = PsiTreeUtil.getContextOfType(insertedElement, PsiExpression.class, true);
|
||||
for (final ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes(expr, true)) {
|
||||
final PsiType type = info.getType();
|
||||
final PsiClass psiClass = PsiUtil.resolveClassInType(type);
|
||||
if (psiClass != null) {
|
||||
consumer.consume(createClassLookupItem(psiClass, inJavaContext));
|
||||
}
|
||||
final PsiType defaultType = info.getDefaultType();
|
||||
if (!defaultType.equals(type)) {
|
||||
final PsiClass defClass = PsiUtil.resolveClassInType(defaultType);
|
||||
if (defClass != null) {
|
||||
consumer.consume(createClassLookupItem(defClass, true));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final boolean pkgContext = JavaCompletionUtil.inSomePackage(insertedElement);
|
||||
AllClassesGetter.processJavaClasses(parameters, matcher, filterByScope, new Consumer<PsiClass>() {
|
||||
@Override
|
||||
public void consume(PsiClass psiClass) {
|
||||
if (filter.isAcceptable(psiClass, insertedElement)) {
|
||||
if (!inJavaContext) {
|
||||
consumer.consume(AllClassesGetter.createLookupItem(psiClass, AllClassesGetter.TRY_SHORTENING));
|
||||
} else {
|
||||
for (JavaPsiClassReferenceElement element : createClassLookupItems(psiClass, afterNew,
|
||||
JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER, new Condition<PsiClass>() {
|
||||
@Override
|
||||
public boolean value(PsiClass psiClass) {
|
||||
return filter.isAcceptable(psiClass, insertedElement) &&
|
||||
AllClassesGetter.isAcceptableInContext(insertedElement, psiClass, filterByScope, pkgContext);
|
||||
}
|
||||
})) {
|
||||
consumer.consume(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static JavaPsiClassReferenceElement createClassLookupItem(final PsiClass psiClass, final boolean inJavaContext) {
|
||||
return AllClassesGetter.createLookupItem(psiClass, inJavaContext ? JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER
|
||||
: AllClassesGetter.TRY_SHORTENING);
|
||||
}
|
||||
|
||||
public static List<JavaPsiClassReferenceElement> createClassLookupItems(final PsiClass psiClass,
|
||||
boolean withInners,
|
||||
InsertHandler<JavaPsiClassReferenceElement> insertHandler,
|
||||
Condition<PsiClass> condition) {
|
||||
List<JavaPsiClassReferenceElement> result = new SmartList<JavaPsiClassReferenceElement>();
|
||||
if (condition.value(psiClass)) {
|
||||
result.add(AllClassesGetter.createLookupItem(psiClass, insertHandler));
|
||||
}
|
||||
String name = psiClass.getName();
|
||||
if (withInners && name != null) {
|
||||
for (PsiClass inner : psiClass.getInnerClasses()) {
|
||||
if (inner.hasModifierProperty(PsiModifier.STATIC)) {
|
||||
for (JavaPsiClassReferenceElement lookupInner : createClassLookupItems(inner, withInners, insertHandler, condition)) {
|
||||
String forced = lookupInner.getForcedPresentableName();
|
||||
lookupInner.setForcedPresentableName(name + "." + (forced != null ? forced : inner.getName()));
|
||||
result.add(lookupInner);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public String handleEmptyLookup(@NotNull final CompletionParameters parameters, final Editor editor) {
|
||||
if (!(parameters.getOriginalFile() instanceof PsiJavaFile)) return null;
|
||||
|
||||
if (shouldShowSecondSmartCompletionHint(parameters)) {
|
||||
return LangBundle.message("completion.no.suggestions") +
|
||||
"; " +
|
||||
StringUtil.decapitalize(
|
||||
CompletionBundle.message("completion.class.name.hint.2", getActionShortcut(IdeActions.ACTION_CODE_COMPLETION)));
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean shouldShowSecondSmartCompletionHint(final CompletionParameters parameters) {
|
||||
return parameters.getCompletionType() == CompletionType.BASIC &&
|
||||
parameters.getInvocationCount() == 2 &&
|
||||
parameters.getOriginalFile().getLanguage().isKindOf(JavaLanguage.INSTANCE);
|
||||
}
|
||||
}
|
||||
|
||||
+30
-30
@@ -1,30 +1,30 @@
|
||||
/*
|
||||
* Copyright 2000-2009 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.completion;
|
||||
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public interface JavaCompletionFeatures {
|
||||
@NonNls String SECOND_SMART_COMPLETION_CHAIN = "editing.completion.second.smarttype.chain";
|
||||
@NonNls String SECOND_SMART_COMPLETION_TOAR = "editing.completion.second.smarttype.toar";
|
||||
@NonNls String SECOND_SMART_COMPLETION_ASLIST = "editing.completion.second.smarttype.aslist";
|
||||
@NonNls String SECOND_SMART_COMPLETION_ARRAY_MEMBER = "editing.completion.second.smarttype.array.member";
|
||||
@NonNls String GLOBAL_MEMBER_NAME = "editing.completion.global.member.name";
|
||||
@NonNls String AFTER_NEW = "editing.completion.smarttype.afternew";
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 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.completion;
|
||||
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public interface JavaCompletionFeatures {
|
||||
@NonNls String SECOND_SMART_COMPLETION_CHAIN = "editing.completion.second.smarttype.chain";
|
||||
@NonNls String SECOND_SMART_COMPLETION_TOAR = "editing.completion.second.smarttype.toar";
|
||||
@NonNls String SECOND_SMART_COMPLETION_ASLIST = "editing.completion.second.smarttype.aslist";
|
||||
@NonNls String SECOND_SMART_COMPLETION_ARRAY_MEMBER = "editing.completion.second.smarttype.array.member";
|
||||
@NonNls String GLOBAL_MEMBER_NAME = "editing.completion.global.member.name";
|
||||
@NonNls String AFTER_NEW = "editing.completion.smarttype.afternew";
|
||||
}
|
||||
|
||||
+90
-90
@@ -1,90 +1,90 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.codeInsight.lookup.AutoCompletionPolicy;
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
import com.intellij.codeInsight.lookup.VariableLookupItem;
|
||||
import com.intellij.featureStatistics.FeatureUsageTracker;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public class JavaStaticMemberProcessor extends StaticMemberProcessor {
|
||||
private final PsiElement myOriginalPosition;
|
||||
|
||||
public JavaStaticMemberProcessor(CompletionParameters parameters) {
|
||||
super(parameters.getPosition());
|
||||
myOriginalPosition = parameters.getOriginalPosition();
|
||||
|
||||
final PsiFile file = parameters.getPosition().getContainingFile();
|
||||
if (file instanceof PsiJavaFile) {
|
||||
final PsiImportList importList = ((PsiJavaFile)file).getImportList();
|
||||
if (importList != null) {
|
||||
for (PsiImportStaticStatement statement : importList.getImportStaticStatements()) {
|
||||
importMembersOf(statement.resolveTargetClass());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
protected LookupElement createLookupElement(@NotNull PsiMember member, @NotNull final PsiClass containingClass, boolean shouldImport) {
|
||||
shouldImport |= myOriginalPosition != null && PsiTreeUtil.isAncestor(containingClass, myOriginalPosition, false);
|
||||
|
||||
if (member instanceof PsiMethod) {
|
||||
return AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(new GlobalMethodCallElement((PsiMethod)member, shouldImport, false));
|
||||
}
|
||||
return AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(new VariableLookupItem((PsiField)member, shouldImport) {
|
||||
@Override
|
||||
public void handleInsert(InsertionContext context) {
|
||||
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.GLOBAL_MEMBER_NAME);
|
||||
|
||||
super.handleInsert(context);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
protected LookupElement createLookupElement(@NotNull List<PsiMethod> overloads,
|
||||
@NotNull PsiClass containingClass,
|
||||
boolean shouldImport) {
|
||||
shouldImport |= myOriginalPosition != null && PsiTreeUtil.isAncestor(containingClass, myOriginalPosition, false);
|
||||
|
||||
final JavaMethodCallElement element = new GlobalMethodCallElement(overloads.get(0), shouldImport, true);
|
||||
element.putUserData(JavaCompletionUtil.ALL_METHODS_ATTRIBUTE, overloads);
|
||||
return element;
|
||||
}
|
||||
|
||||
private static class GlobalMethodCallElement extends JavaMethodCallElement {
|
||||
public GlobalMethodCallElement(PsiMethod member, boolean shouldImport, boolean mergedOverloads) {
|
||||
super(member, shouldImport, mergedOverloads);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleInsert(InsertionContext context) {
|
||||
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.GLOBAL_MEMBER_NAME);
|
||||
|
||||
super.handleInsert(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.codeInsight.lookup.AutoCompletionPolicy;
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
import com.intellij.codeInsight.lookup.VariableLookupItem;
|
||||
import com.intellij.featureStatistics.FeatureUsageTracker;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public class JavaStaticMemberProcessor extends StaticMemberProcessor {
|
||||
private final PsiElement myOriginalPosition;
|
||||
|
||||
public JavaStaticMemberProcessor(CompletionParameters parameters) {
|
||||
super(parameters.getPosition());
|
||||
myOriginalPosition = parameters.getOriginalPosition();
|
||||
|
||||
final PsiFile file = parameters.getPosition().getContainingFile();
|
||||
if (file instanceof PsiJavaFile) {
|
||||
final PsiImportList importList = ((PsiJavaFile)file).getImportList();
|
||||
if (importList != null) {
|
||||
for (PsiImportStaticStatement statement : importList.getImportStaticStatements()) {
|
||||
importMembersOf(statement.resolveTargetClass());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
protected LookupElement createLookupElement(@NotNull PsiMember member, @NotNull final PsiClass containingClass, boolean shouldImport) {
|
||||
shouldImport |= myOriginalPosition != null && PsiTreeUtil.isAncestor(containingClass, myOriginalPosition, false);
|
||||
|
||||
if (member instanceof PsiMethod) {
|
||||
return AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(new GlobalMethodCallElement((PsiMethod)member, shouldImport, false));
|
||||
}
|
||||
return AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(new VariableLookupItem((PsiField)member, shouldImport) {
|
||||
@Override
|
||||
public void handleInsert(InsertionContext context) {
|
||||
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.GLOBAL_MEMBER_NAME);
|
||||
|
||||
super.handleInsert(context);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
protected LookupElement createLookupElement(@NotNull List<PsiMethod> overloads,
|
||||
@NotNull PsiClass containingClass,
|
||||
boolean shouldImport) {
|
||||
shouldImport |= myOriginalPosition != null && PsiTreeUtil.isAncestor(containingClass, myOriginalPosition, false);
|
||||
|
||||
final JavaMethodCallElement element = new GlobalMethodCallElement(overloads.get(0), shouldImport, true);
|
||||
element.putUserData(JavaCompletionUtil.ALL_METHODS_ATTRIBUTE, overloads);
|
||||
return element;
|
||||
}
|
||||
|
||||
private static class GlobalMethodCallElement extends JavaMethodCallElement {
|
||||
public GlobalMethodCallElement(PsiMethod member, boolean shouldImport, boolean mergedOverloads) {
|
||||
super(member, shouldImport, mergedOverloads);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleInsert(InsertionContext context) {
|
||||
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.GLOBAL_MEMBER_NAME);
|
||||
|
||||
super.handleInsert(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+128
-128
@@ -1,129 +1,129 @@
|
||||
/*
|
||||
* Copyright 2000-2011 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.daemon.impl.quickfix;
|
||||
|
||||
import com.intellij.codeInsight.daemon.QuickFixActionRegistrar;
|
||||
import com.intellij.codeInsight.daemon.impl.analysis.HighlightMethodUtil;
|
||||
import com.intellij.codeInsight.intention.IntentionAction;
|
||||
import com.intellij.codeInsight.intention.impl.PriorityIntentionActionWrapper;
|
||||
import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixProvider;
|
||||
import com.intellij.openapi.util.TextRange;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
|
||||
import com.intellij.psi.codeStyle.VariableKind;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.psi.util.PsiUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class DefaultQuickFixProvider extends UnresolvedReferenceQuickFixProvider<PsiJavaCodeReferenceElement> {
|
||||
@Override
|
||||
public void registerFixes(PsiJavaCodeReferenceElement ref, QuickFixActionRegistrar registrar) {
|
||||
registrar.register(new ImportClassFix(ref));
|
||||
registrar.register(SetupJDKFix.getInstance());
|
||||
OrderEntryFix.registerFixes(registrar, ref);
|
||||
MoveClassToModuleFix.registerFixes(registrar, ref);
|
||||
|
||||
if (ref instanceof PsiReferenceExpression) {
|
||||
TextRange fixRange = HighlightMethodUtil.getFixRange(ref);
|
||||
PsiReferenceExpression refExpr = (PsiReferenceExpression)ref;
|
||||
|
||||
registrar.register(fixRange, new CreateEnumConstantFromUsageFix(refExpr), null);
|
||||
registrar.register(new RenameWrongRefFix(refExpr));
|
||||
|
||||
if (!ref.isQualified()) {
|
||||
registrar.register(fixRange, new BringVariableIntoScopeFix(refExpr), null);
|
||||
}
|
||||
|
||||
registerPriorityActions(registrar,fixRange,refExpr);
|
||||
}
|
||||
|
||||
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.INTERFACE));
|
||||
if (PsiUtil.isLanguageLevel5OrHigher(ref)) {
|
||||
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.ENUM));
|
||||
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.ANNOTATION));
|
||||
}
|
||||
PsiElement parent = PsiTreeUtil.getParentOfType(ref, PsiNewExpression.class, PsiMethod.class);
|
||||
final PsiExpressionList expressionList = PsiTreeUtil.getParentOfType(ref, PsiExpressionList.class);
|
||||
if (parent instanceof PsiNewExpression && !(ref.getParent() instanceof PsiTypeElement) && (expressionList == null || !PsiTreeUtil.isAncestor(parent, expressionList, false))) {
|
||||
registrar.register(new CreateClassFromNewFix((PsiNewExpression)parent));
|
||||
registrar.register(new CreateInnerClassFromNewFix((PsiNewExpression)parent));
|
||||
}
|
||||
else {
|
||||
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.CLASS));
|
||||
registrar.register(new CreateInnerClassFromUsageFix(ref, CreateClassKind.CLASS));
|
||||
}
|
||||
}
|
||||
|
||||
private static void registerPriorityActions(@NotNull final QuickFixActionRegistrar registrar,
|
||||
@NotNull final TextRange fixRange,
|
||||
@NotNull final PsiReferenceExpression refExpr) {
|
||||
final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(refExpr.getProject());
|
||||
|
||||
final Map<VariableKind, IntentionAction> map = new HashMap<VariableKind, IntentionAction>() {
|
||||
{
|
||||
put(VariableKind.FIELD, new CreateFieldFromUsageFix(refExpr));
|
||||
put(VariableKind.STATIC_FINAL_FIELD, new CreateConstantFieldFromUsageFix(refExpr));
|
||||
if (!refExpr.isQualified()) {
|
||||
put(VariableKind.LOCAL_VARIABLE, new CreateLocalFromUsageFix(refExpr));
|
||||
put(VariableKind.PARAMETER, new CreateParameterFromUsageFix(refExpr));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
final VariableKind kind = getKind(styleManager, refExpr);
|
||||
if (map.containsKey(kind)){
|
||||
map.put(kind, PriorityIntentionActionWrapper.highPriority(map.get(kind)));
|
||||
}
|
||||
|
||||
for (IntentionAction action : map.values()){
|
||||
registrar.register(fixRange, action, null);
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private static VariableKind getKind(@NotNull JavaCodeStyleManager styleManager,
|
||||
@NotNull PsiReferenceExpression refExpr) {
|
||||
final String reference = refExpr.getText();
|
||||
|
||||
if (reference.toUpperCase().equals(reference)){
|
||||
return VariableKind.STATIC_FINAL_FIELD;
|
||||
}
|
||||
|
||||
for (VariableKind kind : VariableKind.values()) {
|
||||
final String prefix = styleManager.getPrefixByVariableKind(kind);
|
||||
final String suffix = styleManager.getSuffixByVariableKind(kind);
|
||||
|
||||
if (prefix.isEmpty() && suffix.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (reference.startsWith(prefix) && reference.endsWith(suffix)) {
|
||||
return kind;
|
||||
}
|
||||
}
|
||||
|
||||
return VariableKind.LOCAL_VARIABLE;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Class<PsiJavaCodeReferenceElement> getReferenceClass() {
|
||||
return PsiJavaCodeReferenceElement.class;
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2011 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.daemon.impl.quickfix;
|
||||
|
||||
import com.intellij.codeInsight.daemon.QuickFixActionRegistrar;
|
||||
import com.intellij.codeInsight.daemon.impl.analysis.HighlightMethodUtil;
|
||||
import com.intellij.codeInsight.intention.IntentionAction;
|
||||
import com.intellij.codeInsight.intention.impl.PriorityIntentionActionWrapper;
|
||||
import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixProvider;
|
||||
import com.intellij.openapi.util.TextRange;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
|
||||
import com.intellij.psi.codeStyle.VariableKind;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.psi.util.PsiUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class DefaultQuickFixProvider extends UnresolvedReferenceQuickFixProvider<PsiJavaCodeReferenceElement> {
|
||||
@Override
|
||||
public void registerFixes(PsiJavaCodeReferenceElement ref, QuickFixActionRegistrar registrar) {
|
||||
registrar.register(new ImportClassFix(ref));
|
||||
registrar.register(SetupJDKFix.getInstance());
|
||||
OrderEntryFix.registerFixes(registrar, ref);
|
||||
MoveClassToModuleFix.registerFixes(registrar, ref);
|
||||
|
||||
if (ref instanceof PsiReferenceExpression) {
|
||||
TextRange fixRange = HighlightMethodUtil.getFixRange(ref);
|
||||
PsiReferenceExpression refExpr = (PsiReferenceExpression)ref;
|
||||
|
||||
registrar.register(fixRange, new CreateEnumConstantFromUsageFix(refExpr), null);
|
||||
registrar.register(new RenameWrongRefFix(refExpr));
|
||||
|
||||
if (!ref.isQualified()) {
|
||||
registrar.register(fixRange, new BringVariableIntoScopeFix(refExpr), null);
|
||||
}
|
||||
|
||||
registerPriorityActions(registrar,fixRange,refExpr);
|
||||
}
|
||||
|
||||
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.INTERFACE));
|
||||
if (PsiUtil.isLanguageLevel5OrHigher(ref)) {
|
||||
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.ENUM));
|
||||
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.ANNOTATION));
|
||||
}
|
||||
PsiElement parent = PsiTreeUtil.getParentOfType(ref, PsiNewExpression.class, PsiMethod.class);
|
||||
final PsiExpressionList expressionList = PsiTreeUtil.getParentOfType(ref, PsiExpressionList.class);
|
||||
if (parent instanceof PsiNewExpression && !(ref.getParent() instanceof PsiTypeElement) && (expressionList == null || !PsiTreeUtil.isAncestor(parent, expressionList, false))) {
|
||||
registrar.register(new CreateClassFromNewFix((PsiNewExpression)parent));
|
||||
registrar.register(new CreateInnerClassFromNewFix((PsiNewExpression)parent));
|
||||
}
|
||||
else {
|
||||
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.CLASS));
|
||||
registrar.register(new CreateInnerClassFromUsageFix(ref, CreateClassKind.CLASS));
|
||||
}
|
||||
}
|
||||
|
||||
private static void registerPriorityActions(@NotNull final QuickFixActionRegistrar registrar,
|
||||
@NotNull final TextRange fixRange,
|
||||
@NotNull final PsiReferenceExpression refExpr) {
|
||||
final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(refExpr.getProject());
|
||||
|
||||
final Map<VariableKind, IntentionAction> map = new HashMap<VariableKind, IntentionAction>() {
|
||||
{
|
||||
put(VariableKind.FIELD, new CreateFieldFromUsageFix(refExpr));
|
||||
put(VariableKind.STATIC_FINAL_FIELD, new CreateConstantFieldFromUsageFix(refExpr));
|
||||
if (!refExpr.isQualified()) {
|
||||
put(VariableKind.LOCAL_VARIABLE, new CreateLocalFromUsageFix(refExpr));
|
||||
put(VariableKind.PARAMETER, new CreateParameterFromUsageFix(refExpr));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
final VariableKind kind = getKind(styleManager, refExpr);
|
||||
if (map.containsKey(kind)){
|
||||
map.put(kind, PriorityIntentionActionWrapper.highPriority(map.get(kind)));
|
||||
}
|
||||
|
||||
for (IntentionAction action : map.values()){
|
||||
registrar.register(fixRange, action, null);
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private static VariableKind getKind(@NotNull JavaCodeStyleManager styleManager,
|
||||
@NotNull PsiReferenceExpression refExpr) {
|
||||
final String reference = refExpr.getText();
|
||||
|
||||
if (reference.toUpperCase().equals(reference)){
|
||||
return VariableKind.STATIC_FINAL_FIELD;
|
||||
}
|
||||
|
||||
for (VariableKind kind : VariableKind.values()) {
|
||||
final String prefix = styleManager.getPrefixByVariableKind(kind);
|
||||
final String suffix = styleManager.getSuffixByVariableKind(kind);
|
||||
|
||||
if (prefix.isEmpty() && suffix.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (reference.startsWith(prefix) && reference.endsWith(suffix)) {
|
||||
return kind;
|
||||
}
|
||||
}
|
||||
|
||||
return VariableKind.LOCAL_VARIABLE;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public Class<PsiJavaCodeReferenceElement> getReferenceClass() {
|
||||
return PsiJavaCodeReferenceElement.class;
|
||||
}
|
||||
}
|
||||
+109
-109
@@ -1,109 +1,109 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.intention.impl;
|
||||
|
||||
import com.intellij.codeInsight.CodeInsightBundle;
|
||||
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.util.Comparing;
|
||||
import com.intellij.openapi.util.text.StringUtil;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* @author Danila Ponomarenko
|
||||
*/
|
||||
public class BreakStringOnLineBreaksIntentionAction extends PsiElementBaseIntentionAction {
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
|
||||
if (!(element instanceof PsiJavaToken)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final PsiJavaToken token = (PsiJavaToken)element;
|
||||
|
||||
if (token.getTokenType() != JavaTokenType.STRING_LITERAL) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final String text = token.getText();
|
||||
if (text == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final int indexOfSlashN = text.indexOf("\\n");
|
||||
if (indexOfSlashN == -1 || Comparing.equal(text.substring(indexOfSlashN, text.length()), "\\n\"")){
|
||||
return false;
|
||||
}
|
||||
|
||||
final int indexOfSlashNSlashR = text.indexOf("\\n\\r");
|
||||
if (indexOfSlashNSlashR != -1 && Comparing.equal(text.substring(indexOfSlashNSlashR, text.length()), "\\n\\r\"")){
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
|
||||
if (!(element instanceof PsiJavaToken)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final PsiJavaToken token = (PsiJavaToken)element;
|
||||
|
||||
if (token.getTokenType() != JavaTokenType.STRING_LITERAL) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
final String text = token.getText();
|
||||
if (text == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
|
||||
token.replace(factory.createExpressionFromText(breakOnLineBreaks(text), element));
|
||||
}
|
||||
|
||||
|
||||
@NotNull
|
||||
private static String breakOnLineBreaks(@NotNull String string) {
|
||||
final String result = StringUtil.replace(
|
||||
string,
|
||||
new String[]{"\\n\\r", "\\n"},
|
||||
new String[]{"\\n\\r\" + \n\"", "\\n\" + \n\""}
|
||||
);
|
||||
|
||||
final String redundantSuffix = " + \n\"\"";
|
||||
|
||||
return result.endsWith(redundantSuffix) ? result.substring(0, result.length() - redundantSuffix.length()) : result;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getText() {
|
||||
return CodeInsightBundle.message("intention.break.string.on.line.breaks.text");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getFamilyName() {
|
||||
return getText();
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.intention.impl;
|
||||
|
||||
import com.intellij.codeInsight.CodeInsightBundle;
|
||||
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.util.Comparing;
|
||||
import com.intellij.openapi.util.text.StringUtil;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* @author Danila Ponomarenko
|
||||
*/
|
||||
public class BreakStringOnLineBreaksIntentionAction extends PsiElementBaseIntentionAction {
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
|
||||
if (!(element instanceof PsiJavaToken)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final PsiJavaToken token = (PsiJavaToken)element;
|
||||
|
||||
if (token.getTokenType() != JavaTokenType.STRING_LITERAL) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final String text = token.getText();
|
||||
if (text == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final int indexOfSlashN = text.indexOf("\\n");
|
||||
if (indexOfSlashN == -1 || Comparing.equal(text.substring(indexOfSlashN, text.length()), "\\n\"")){
|
||||
return false;
|
||||
}
|
||||
|
||||
final int indexOfSlashNSlashR = text.indexOf("\\n\\r");
|
||||
if (indexOfSlashNSlashR != -1 && Comparing.equal(text.substring(indexOfSlashNSlashR, text.length()), "\\n\\r\"")){
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
|
||||
if (!(element instanceof PsiJavaToken)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final PsiJavaToken token = (PsiJavaToken)element;
|
||||
|
||||
if (token.getTokenType() != JavaTokenType.STRING_LITERAL) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
final String text = token.getText();
|
||||
if (text == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
|
||||
token.replace(factory.createExpressionFromText(breakOnLineBreaks(text), element));
|
||||
}
|
||||
|
||||
|
||||
@NotNull
|
||||
private static String breakOnLineBreaks(@NotNull String string) {
|
||||
final String result = StringUtil.replace(
|
||||
string,
|
||||
new String[]{"\\n\\r", "\\n"},
|
||||
new String[]{"\\n\\r\" + \n\"", "\\n\" + \n\""}
|
||||
);
|
||||
|
||||
final String redundantSuffix = " + \n\"\"";
|
||||
|
||||
return result.endsWith(redundantSuffix) ? result.substring(0, result.length() - redundantSuffix.length()) : result;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getText() {
|
||||
return CodeInsightBundle.message("intention.break.string.on.line.breaks.text");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getFamilyName() {
|
||||
return getText();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,82 +1,82 @@
|
||||
/*
|
||||
* Copyright 2000-2009 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.navigation;
|
||||
|
||||
import com.intellij.codeInsight.CodeInsightActionHandler;
|
||||
import com.intellij.codeInsight.CodeInsightBundle;
|
||||
import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator;
|
||||
import com.intellij.codeInsight.navigation.actions.GotoSuperAction;
|
||||
import com.intellij.featureStatistics.FeatureUsageTracker;
|
||||
import com.intellij.ide.util.MethodCellRenderer;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.fileEditor.FileEditorManager;
|
||||
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.vfs.VirtualFile;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.impl.FindSuperElementsHelper;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.psi.util.PsiUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class JavaGotoSuperHandler implements CodeInsightActionHandler {
|
||||
@Override
|
||||
public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) {
|
||||
FeatureUsageTracker.getInstance().triggerFeatureUsed(GotoSuperAction.FEATURE_ID);
|
||||
|
||||
int offset = editor.getCaretModel().getOffset();
|
||||
PsiElement[] superElements = findSuperElements(file, offset);
|
||||
if (superElements == null || superElements.length == 0) return;
|
||||
if (superElements.length == 1) {
|
||||
PsiElement superElement = superElements[0].getNavigationElement();
|
||||
final PsiFile containingFile = superElement.getContainingFile();
|
||||
if (containingFile == null) return;
|
||||
final VirtualFile virtualFile = containingFile.getVirtualFile();
|
||||
if (virtualFile == null) return;
|
||||
OpenFileDescriptor descriptor = new OpenFileDescriptor(project, virtualFile, superElement.getTextOffset());
|
||||
FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
|
||||
} else {
|
||||
if (superElements[0] instanceof PsiMethod) {
|
||||
boolean showMethodNames = !PsiUtil.allMethodsHaveSameSignature((PsiMethod[])superElements);
|
||||
PsiElementListNavigator.openTargets(editor, (PsiMethod[])superElements,
|
||||
CodeInsightBundle.message("goto.super.method.chooser.title"),
|
||||
CodeInsightBundle.message("goto.super.method.findUsages.title", ((PsiMethod)superElements[0]).getName()),
|
||||
new MethodCellRenderer(showMethodNames));
|
||||
}
|
||||
else {
|
||||
NavigationUtil.getPsiElementPopup(superElements, CodeInsightBundle.message("goto.super.class.chooser.title")).showInBestPositionFor(editor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static PsiElement[] findSuperElements(PsiFile file, int offset) {
|
||||
PsiElement element = file.findElementAt(offset);
|
||||
if (element == null) return null;
|
||||
|
||||
PsiNameIdentifierOwner parent = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiClass.class);
|
||||
if (parent == null)
|
||||
return null;
|
||||
|
||||
return FindSuperElementsHelper.findSuperElements(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean startInWriteAction() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 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.navigation;
|
||||
|
||||
import com.intellij.codeInsight.CodeInsightActionHandler;
|
||||
import com.intellij.codeInsight.CodeInsightBundle;
|
||||
import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator;
|
||||
import com.intellij.codeInsight.navigation.actions.GotoSuperAction;
|
||||
import com.intellij.featureStatistics.FeatureUsageTracker;
|
||||
import com.intellij.ide.util.MethodCellRenderer;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.fileEditor.FileEditorManager;
|
||||
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.vfs.VirtualFile;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.impl.FindSuperElementsHelper;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.psi.util.PsiUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class JavaGotoSuperHandler implements CodeInsightActionHandler {
|
||||
@Override
|
||||
public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) {
|
||||
FeatureUsageTracker.getInstance().triggerFeatureUsed(GotoSuperAction.FEATURE_ID);
|
||||
|
||||
int offset = editor.getCaretModel().getOffset();
|
||||
PsiElement[] superElements = findSuperElements(file, offset);
|
||||
if (superElements == null || superElements.length == 0) return;
|
||||
if (superElements.length == 1) {
|
||||
PsiElement superElement = superElements[0].getNavigationElement();
|
||||
final PsiFile containingFile = superElement.getContainingFile();
|
||||
if (containingFile == null) return;
|
||||
final VirtualFile virtualFile = containingFile.getVirtualFile();
|
||||
if (virtualFile == null) return;
|
||||
OpenFileDescriptor descriptor = new OpenFileDescriptor(project, virtualFile, superElement.getTextOffset());
|
||||
FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
|
||||
} else {
|
||||
if (superElements[0] instanceof PsiMethod) {
|
||||
boolean showMethodNames = !PsiUtil.allMethodsHaveSameSignature((PsiMethod[])superElements);
|
||||
PsiElementListNavigator.openTargets(editor, (PsiMethod[])superElements,
|
||||
CodeInsightBundle.message("goto.super.method.chooser.title"),
|
||||
CodeInsightBundle.message("goto.super.method.findUsages.title", ((PsiMethod)superElements[0]).getName()),
|
||||
new MethodCellRenderer(showMethodNames));
|
||||
}
|
||||
else {
|
||||
NavigationUtil.getPsiElementPopup(superElements, CodeInsightBundle.message("goto.super.class.chooser.title")).showInBestPositionFor(editor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static PsiElement[] findSuperElements(PsiFile file, int offset) {
|
||||
PsiElement element = file.findElementAt(offset);
|
||||
if (element == null) return null;
|
||||
|
||||
PsiNameIdentifierOwner parent = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiClass.class);
|
||||
if (parent == null)
|
||||
return null;
|
||||
|
||||
return FindSuperElementsHelper.findSuperElements(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean startInWriteAction() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
+194
-194
@@ -1,194 +1,194 @@
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInspection.defaultFileTemplateUsage;
|
||||
|
||||
import com.intellij.codeInsight.CodeInsightUtil;
|
||||
import com.intellij.codeInspection.*;
|
||||
import com.intellij.ide.fileTemplates.FileTemplate;
|
||||
import com.intellij.ide.fileTemplates.FileTemplateManager;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.editor.Document;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.util.Ref;
|
||||
import com.intellij.openapi.util.TextRange;
|
||||
import com.intellij.openapi.util.text.StringUtil;
|
||||
import com.intellij.psi.JavaRecursiveElementWalkingVisitor;
|
||||
import com.intellij.psi.PsiDocumentManager;
|
||||
import com.intellij.psi.PsiElement;
|
||||
import com.intellij.psi.PsiFile;
|
||||
import com.intellij.psi.javadoc.PsiDocComment;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import gnu.trove.TIntObjectHashMap;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Properties;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* @author Alexey
|
||||
*/
|
||||
public class FileHeaderChecker {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.defaultFileTemplateUsage.FileHeaderChecker");
|
||||
|
||||
static ProblemDescriptor checkFileHeader(@NotNull final PsiFile file, final InspectionManager manager, boolean onTheFly) {
|
||||
FileTemplate template = FileTemplateManager.getInstance().getDefaultTemplate(FileTemplateManager.FILE_HEADER_TEMPLATE_NAME);
|
||||
TIntObjectHashMap<String> offsetToProperty = new TIntObjectHashMap<String>();
|
||||
String templateText = template.getText().trim();
|
||||
String regex = templateToRegex(templateText, offsetToProperty, file.getProject());
|
||||
regex = StringUtil.replace(regex, "with", "(?:with|by)");
|
||||
regex = ".*("+regex+").*";
|
||||
String fileText = file.getText();
|
||||
Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
|
||||
Matcher matcher = pattern.matcher(fileText);
|
||||
if (matcher.matches()) {
|
||||
final int startOffset = matcher.start(1);
|
||||
final int endOffset = matcher.end(1);
|
||||
final Ref<PsiDocComment> docComment = new Ref<PsiDocComment>();
|
||||
file.accept(new JavaRecursiveElementWalkingVisitor(){
|
||||
@Override public void visitElement(PsiElement element) {
|
||||
if (docComment.get() != null) return;
|
||||
TextRange range = element.getTextRange();
|
||||
if (!range.contains(startOffset) && !range.contains(endOffset)) return;
|
||||
super.visitElement(element);
|
||||
}
|
||||
@Override public void visitDocComment(PsiDocComment comment) {
|
||||
docComment.set(comment);
|
||||
}
|
||||
});
|
||||
PsiDocComment element = docComment.get();
|
||||
if (element == null) return null;
|
||||
LocalQuickFix[] quickFix = createQuickFix(matcher, offsetToProperty);
|
||||
final String description = InspectionsBundle.message("default.file.template.description");
|
||||
return manager.createProblemDescriptor(element, description, onTheFly, quickFix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Properties computeProperties(final Matcher matcher, final TIntObjectHashMap<String> offsetToProperty) {
|
||||
Properties properties = new Properties(FileTemplateManager.getInstance().getDefaultProperties());
|
||||
int[] offsets = offsetToProperty.keys();
|
||||
Arrays.sort(offsets);
|
||||
|
||||
for (int i = 0; i < offsets.length; i++) {
|
||||
final int offset = offsets[i];
|
||||
String propName = offsetToProperty.get(offset);
|
||||
int groupNum = i + 2; // first group is whole doc comment
|
||||
String propValue = matcher.group(groupNum);
|
||||
properties.put(propName, propValue);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
|
||||
private static LocalQuickFix[] createQuickFix(final Matcher matcher,
|
||||
final TIntObjectHashMap<String> offsetToProperty) {
|
||||
final FileTemplate template = FileTemplateManager.getInstance().getPattern(FileTemplateManager.FILE_HEADER_TEMPLATE_NAME);
|
||||
|
||||
final ReplaceWithFileTemplateFix replaceTemplateFix = new ReplaceWithFileTemplateFix() {
|
||||
public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
|
||||
PsiElement element = descriptor.getPsiElement();
|
||||
if (element == null || !element.isValid()) return;
|
||||
if (!CodeInsightUtil.preparePsiElementsForWrite(element)) return;
|
||||
String newText;
|
||||
try {
|
||||
newText = template.getText(computeProperties(matcher, offsetToProperty));
|
||||
}
|
||||
catch (IOException e) {
|
||||
LOG.error(e);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
int offset = element.getTextRange().getStartOffset();
|
||||
PsiFile psiFile = element.getContainingFile();
|
||||
if (psiFile == null) return;
|
||||
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(psiFile.getProject());
|
||||
Document document = documentManager.getDocument(psiFile);
|
||||
if (document == null) return;
|
||||
|
||||
element.delete();
|
||||
documentManager.doPostponedOperationsAndUnblockDocument(document);
|
||||
documentManager.commitDocument(document);
|
||||
|
||||
document.insertString(offset, newText);
|
||||
}
|
||||
catch (IncorrectOperationException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
catch (IllegalStateException e) {
|
||||
LOG.error("Cannot create doc comment from text: '" + newText + "'", e);
|
||||
}
|
||||
}
|
||||
};
|
||||
final LocalQuickFix editFileTemplateFix = DefaultFileTemplateUsageInspection.createEditFileTemplateFix(template, replaceTemplateFix);
|
||||
if (template.isDefault()) {
|
||||
return new LocalQuickFix[]{editFileTemplateFix};
|
||||
}
|
||||
return new LocalQuickFix[]{replaceTemplateFix,editFileTemplateFix};
|
||||
}
|
||||
|
||||
private static String templateToRegex(final String text, TIntObjectHashMap<String> offsetToProperty, Project project) {
|
||||
String regex = text;
|
||||
@NonNls Collection<String> properties = new ArrayList<String>((Collection)FileTemplateManager.getInstance().getDefaultProperties(project).keySet());
|
||||
properties.add("PACKAGE_NAME");
|
||||
|
||||
regex = escapeRegexChars(regex);
|
||||
// first group is a whole file header
|
||||
int groupNumber = 1;
|
||||
for (String name : properties) {
|
||||
String escaped = escapeRegexChars("${"+name+"}");
|
||||
boolean first = true;
|
||||
for (int i = regex.indexOf(escaped); i!=-1 && i<regex.length(); i = regex.indexOf(escaped,i+1)) {
|
||||
String replacement = first ? "(.*)" : "\\" + groupNumber;
|
||||
final int delta = escaped.length() - replacement.length();
|
||||
int[] offs = offsetToProperty.keys();
|
||||
for (int off : offs) {
|
||||
if (off > i) {
|
||||
String prop = offsetToProperty.remove(off);
|
||||
offsetToProperty.put(off - delta, prop);
|
||||
}
|
||||
}
|
||||
offsetToProperty.put(i, name);
|
||||
regex = regex.substring(0,i) + replacement + regex.substring(i+escaped.length());
|
||||
if (first) {
|
||||
groupNumber++;
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return regex;
|
||||
}
|
||||
|
||||
private static String escapeRegexChars(String regex) {
|
||||
regex = StringUtil.replace(regex,"|", "\\|");
|
||||
regex = StringUtil.replace(regex,".", "\\.");
|
||||
regex = StringUtil.replace(regex,"*", "\\*");
|
||||
regex = StringUtil.replace(regex,"+", "\\+");
|
||||
regex = StringUtil.replace(regex,"?", "\\?");
|
||||
regex = StringUtil.replace(regex,"$", "\\$");
|
||||
regex = StringUtil.replace(regex,"(", "\\(");
|
||||
regex = StringUtil.replace(regex,")", "\\)");
|
||||
regex = StringUtil.replace(regex,"[", "\\[");
|
||||
regex = StringUtil.replace(regex,"]", "\\]");
|
||||
regex = StringUtil.replace(regex,"{", "\\{");
|
||||
regex = StringUtil.replace(regex,"}", "\\}");
|
||||
return regex;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInspection.defaultFileTemplateUsage;
|
||||
|
||||
import com.intellij.codeInsight.CodeInsightUtil;
|
||||
import com.intellij.codeInspection.*;
|
||||
import com.intellij.ide.fileTemplates.FileTemplate;
|
||||
import com.intellij.ide.fileTemplates.FileTemplateManager;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.editor.Document;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.util.Ref;
|
||||
import com.intellij.openapi.util.TextRange;
|
||||
import com.intellij.openapi.util.text.StringUtil;
|
||||
import com.intellij.psi.JavaRecursiveElementWalkingVisitor;
|
||||
import com.intellij.psi.PsiDocumentManager;
|
||||
import com.intellij.psi.PsiElement;
|
||||
import com.intellij.psi.PsiFile;
|
||||
import com.intellij.psi.javadoc.PsiDocComment;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import gnu.trove.TIntObjectHashMap;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Properties;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* @author Alexey
|
||||
*/
|
||||
public class FileHeaderChecker {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.defaultFileTemplateUsage.FileHeaderChecker");
|
||||
|
||||
static ProblemDescriptor checkFileHeader(@NotNull final PsiFile file, final InspectionManager manager, boolean onTheFly) {
|
||||
FileTemplate template = FileTemplateManager.getInstance().getDefaultTemplate(FileTemplateManager.FILE_HEADER_TEMPLATE_NAME);
|
||||
TIntObjectHashMap<String> offsetToProperty = new TIntObjectHashMap<String>();
|
||||
String templateText = template.getText().trim();
|
||||
String regex = templateToRegex(templateText, offsetToProperty, file.getProject());
|
||||
regex = StringUtil.replace(regex, "with", "(?:with|by)");
|
||||
regex = ".*("+regex+").*";
|
||||
String fileText = file.getText();
|
||||
Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
|
||||
Matcher matcher = pattern.matcher(fileText);
|
||||
if (matcher.matches()) {
|
||||
final int startOffset = matcher.start(1);
|
||||
final int endOffset = matcher.end(1);
|
||||
final Ref<PsiDocComment> docComment = new Ref<PsiDocComment>();
|
||||
file.accept(new JavaRecursiveElementWalkingVisitor(){
|
||||
@Override public void visitElement(PsiElement element) {
|
||||
if (docComment.get() != null) return;
|
||||
TextRange range = element.getTextRange();
|
||||
if (!range.contains(startOffset) && !range.contains(endOffset)) return;
|
||||
super.visitElement(element);
|
||||
}
|
||||
@Override public void visitDocComment(PsiDocComment comment) {
|
||||
docComment.set(comment);
|
||||
}
|
||||
});
|
||||
PsiDocComment element = docComment.get();
|
||||
if (element == null) return null;
|
||||
LocalQuickFix[] quickFix = createQuickFix(matcher, offsetToProperty);
|
||||
final String description = InspectionsBundle.message("default.file.template.description");
|
||||
return manager.createProblemDescriptor(element, description, onTheFly, quickFix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Properties computeProperties(final Matcher matcher, final TIntObjectHashMap<String> offsetToProperty) {
|
||||
Properties properties = new Properties(FileTemplateManager.getInstance().getDefaultProperties());
|
||||
int[] offsets = offsetToProperty.keys();
|
||||
Arrays.sort(offsets);
|
||||
|
||||
for (int i = 0; i < offsets.length; i++) {
|
||||
final int offset = offsets[i];
|
||||
String propName = offsetToProperty.get(offset);
|
||||
int groupNum = i + 2; // first group is whole doc comment
|
||||
String propValue = matcher.group(groupNum);
|
||||
properties.put(propName, propValue);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
|
||||
private static LocalQuickFix[] createQuickFix(final Matcher matcher,
|
||||
final TIntObjectHashMap<String> offsetToProperty) {
|
||||
final FileTemplate template = FileTemplateManager.getInstance().getPattern(FileTemplateManager.FILE_HEADER_TEMPLATE_NAME);
|
||||
|
||||
final ReplaceWithFileTemplateFix replaceTemplateFix = new ReplaceWithFileTemplateFix() {
|
||||
public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
|
||||
PsiElement element = descriptor.getPsiElement();
|
||||
if (element == null || !element.isValid()) return;
|
||||
if (!CodeInsightUtil.preparePsiElementsForWrite(element)) return;
|
||||
String newText;
|
||||
try {
|
||||
newText = template.getText(computeProperties(matcher, offsetToProperty));
|
||||
}
|
||||
catch (IOException e) {
|
||||
LOG.error(e);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
int offset = element.getTextRange().getStartOffset();
|
||||
PsiFile psiFile = element.getContainingFile();
|
||||
if (psiFile == null) return;
|
||||
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(psiFile.getProject());
|
||||
Document document = documentManager.getDocument(psiFile);
|
||||
if (document == null) return;
|
||||
|
||||
element.delete();
|
||||
documentManager.doPostponedOperationsAndUnblockDocument(document);
|
||||
documentManager.commitDocument(document);
|
||||
|
||||
document.insertString(offset, newText);
|
||||
}
|
||||
catch (IncorrectOperationException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
catch (IllegalStateException e) {
|
||||
LOG.error("Cannot create doc comment from text: '" + newText + "'", e);
|
||||
}
|
||||
}
|
||||
};
|
||||
final LocalQuickFix editFileTemplateFix = DefaultFileTemplateUsageInspection.createEditFileTemplateFix(template, replaceTemplateFix);
|
||||
if (template.isDefault()) {
|
||||
return new LocalQuickFix[]{editFileTemplateFix};
|
||||
}
|
||||
return new LocalQuickFix[]{replaceTemplateFix,editFileTemplateFix};
|
||||
}
|
||||
|
||||
private static String templateToRegex(final String text, TIntObjectHashMap<String> offsetToProperty, Project project) {
|
||||
String regex = text;
|
||||
@NonNls Collection<String> properties = new ArrayList<String>((Collection)FileTemplateManager.getInstance().getDefaultProperties(project).keySet());
|
||||
properties.add("PACKAGE_NAME");
|
||||
|
||||
regex = escapeRegexChars(regex);
|
||||
// first group is a whole file header
|
||||
int groupNumber = 1;
|
||||
for (String name : properties) {
|
||||
String escaped = escapeRegexChars("${"+name+"}");
|
||||
boolean first = true;
|
||||
for (int i = regex.indexOf(escaped); i!=-1 && i<regex.length(); i = regex.indexOf(escaped,i+1)) {
|
||||
String replacement = first ? "(.*)" : "\\" + groupNumber;
|
||||
final int delta = escaped.length() - replacement.length();
|
||||
int[] offs = offsetToProperty.keys();
|
||||
for (int off : offs) {
|
||||
if (off > i) {
|
||||
String prop = offsetToProperty.remove(off);
|
||||
offsetToProperty.put(off - delta, prop);
|
||||
}
|
||||
}
|
||||
offsetToProperty.put(i, name);
|
||||
regex = regex.substring(0,i) + replacement + regex.substring(i+escaped.length());
|
||||
if (first) {
|
||||
groupNumber++;
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return regex;
|
||||
}
|
||||
|
||||
private static String escapeRegexChars(String regex) {
|
||||
regex = StringUtil.replace(regex,"|", "\\|");
|
||||
regex = StringUtil.replace(regex,".", "\\.");
|
||||
regex = StringUtil.replace(regex,"*", "\\*");
|
||||
regex = StringUtil.replace(regex,"+", "\\+");
|
||||
regex = StringUtil.replace(regex,"?", "\\?");
|
||||
regex = StringUtil.replace(regex,"$", "\\$");
|
||||
regex = StringUtil.replace(regex,"(", "\\(");
|
||||
regex = StringUtil.replace(regex,")", "\\)");
|
||||
regex = StringUtil.replace(regex,"[", "\\[");
|
||||
regex = StringUtil.replace(regex,"]", "\\]");
|
||||
regex = StringUtil.replace(regex,"{", "\\{");
|
||||
regex = StringUtil.replace(regex,"}", "\\}");
|
||||
return regex;
|
||||
}
|
||||
}
|
||||
|
||||
+50
-50
@@ -1,50 +1,50 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInspection.internal;
|
||||
|
||||
import com.intellij.codeInspection.ProblemHighlightType;
|
||||
import com.intellij.codeInspection.ProblemsHolder;
|
||||
import com.intellij.psi.*;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class FileEqualsUsageInspection extends InternalInspection {
|
||||
private static final String MESSAGE =
|
||||
"Do not use File.equals/hashCode/compareTo as they don't honor case-sensitivity on MacOS. " +
|
||||
"Please use FileUtil.filesEquals/fileHashCode/compareFiles instead";
|
||||
|
||||
@NotNull
|
||||
public PsiElementVisitor buildInternalVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
|
||||
return new JavaElementVisitor() {
|
||||
@Override
|
||||
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
|
||||
PsiReferenceExpression methodExpression = expression.getMethodExpression();
|
||||
PsiElement resolved = methodExpression.resolve();
|
||||
if (!(resolved instanceof PsiMethod)) return;
|
||||
|
||||
PsiMethod method = (PsiMethod)resolved;
|
||||
|
||||
PsiClass clazz = method.getContainingClass();
|
||||
if (clazz == null) return;
|
||||
|
||||
String methodName = method.getName();
|
||||
if (CommonClassNames.JAVA_IO_FILE.equals(clazz.getQualifiedName()) &&
|
||||
("equals".equals(methodName) || "compareTo".equals(methodName) || "hashCode".equals(methodName))) {
|
||||
holder.registerProblem(methodExpression, MESSAGE, ProblemHighlightType.LIKE_DEPRECATED);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInspection.internal;
|
||||
|
||||
import com.intellij.codeInspection.ProblemHighlightType;
|
||||
import com.intellij.codeInspection.ProblemsHolder;
|
||||
import com.intellij.psi.*;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class FileEqualsUsageInspection extends InternalInspection {
|
||||
private static final String MESSAGE =
|
||||
"Do not use File.equals/hashCode/compareTo as they don't honor case-sensitivity on MacOS. " +
|
||||
"Please use FileUtil.filesEquals/fileHashCode/compareFiles instead";
|
||||
|
||||
@NotNull
|
||||
public PsiElementVisitor buildInternalVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
|
||||
return new JavaElementVisitor() {
|
||||
@Override
|
||||
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
|
||||
PsiReferenceExpression methodExpression = expression.getMethodExpression();
|
||||
PsiElement resolved = methodExpression.resolve();
|
||||
if (!(resolved instanceof PsiMethod)) return;
|
||||
|
||||
PsiMethod method = (PsiMethod)resolved;
|
||||
|
||||
PsiClass clazz = method.getContainingClass();
|
||||
if (clazz == null) return;
|
||||
|
||||
String methodName = method.getName();
|
||||
if (CommonClassNames.JAVA_IO_FILE.equals(clazz.getQualifiedName()) &&
|
||||
("equals".equals(methodName) || "compareTo".equals(methodName) || "hashCode".equals(methodName))) {
|
||||
holder.registerProblem(methodExpression, MESSAGE, ProblemHighlightType.LIKE_DEPRECATED);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,156 +1,156 @@
|
||||
/*
|
||||
* Copyright 2000-2011 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.filters.getters;
|
||||
|
||||
import com.intellij.codeInsight.TailType;
|
||||
import com.intellij.codeInsight.completion.*;
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
import com.intellij.codeInsight.lookup.TailTypeDecorator;
|
||||
import com.intellij.codeInsight.lookup.VariableLookupItem;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.tree.IElementType;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.psi.util.PsiUtil;
|
||||
import com.intellij.util.Consumer;
|
||||
import com.intellij.util.containers.ContainerUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public class JavaMembersGetter extends MembersGetter {
|
||||
private final PsiType myExpectedType;
|
||||
|
||||
public JavaMembersGetter(@NotNull PsiType expectedType, CompletionParameters parameters) {
|
||||
super(new JavaStaticMemberProcessor(parameters), parameters.getPosition());
|
||||
myExpectedType = JavaCompletionUtil.originalize(expectedType);
|
||||
}
|
||||
|
||||
public void addMembers(boolean searchInheritors, final Consumer<LookupElement> results) {
|
||||
if (myExpectedType instanceof PsiPrimitiveType && PsiType.DOUBLE.isAssignableFrom(myExpectedType)) {
|
||||
addConstantsFromTargetClass(results, searchInheritors);
|
||||
addConstantsFromReferencedClassesInSwitch(results);
|
||||
}
|
||||
|
||||
if (myPlace.getParent().getParent() instanceof PsiSwitchLabelStatement) {
|
||||
return; //non-enum values are processed above, enum values will be suggested by reference completion
|
||||
}
|
||||
|
||||
final PsiClass psiClass = PsiUtil.resolveClassInType(myExpectedType);
|
||||
processMembers(results, psiClass, PsiTreeUtil.getParentOfType(myPlace, PsiAnnotation.class) == null, searchInheritors);
|
||||
}
|
||||
|
||||
private void addConstantsFromReferencedClassesInSwitch(final Consumer<LookupElement> results) {
|
||||
final Set<PsiField> fields = ReferenceExpressionCompletionContributor.findConstantsUsedInSwitch(myPlace);
|
||||
final Set<PsiClass> classes = new HashSet<PsiClass>();
|
||||
for (PsiField field : fields) {
|
||||
ContainerUtil.addIfNotNull(classes, field.getContainingClass());
|
||||
}
|
||||
for (PsiClass aClass : classes) {
|
||||
processMembers(new Consumer<LookupElement>() {
|
||||
@Override
|
||||
public void consume(LookupElement element) {
|
||||
//noinspection SuspiciousMethodCalls
|
||||
if (!fields.contains(element.getObject())) {
|
||||
results.consume(TailTypeDecorator.withTail(element, TailType.CASE_COLON));
|
||||
}
|
||||
}
|
||||
}, aClass, true, false);
|
||||
}
|
||||
}
|
||||
|
||||
private void addConstantsFromTargetClass(Consumer<LookupElement> results, boolean searchInheritors) {
|
||||
PsiElement parent = myPlace.getParent();
|
||||
if (!(parent instanceof PsiReferenceExpression)) {
|
||||
return;
|
||||
}
|
||||
|
||||
PsiElement prev = parent;
|
||||
parent = parent.getParent();
|
||||
while (parent instanceof PsiBinaryExpression) {
|
||||
final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)parent;
|
||||
final IElementType op = binaryExpression.getOperationTokenType();
|
||||
if (JavaTokenType.EQEQ == op || JavaTokenType.NE == op) {
|
||||
if (prev == binaryExpression.getROperand()) {
|
||||
processMembers(results, getCalledClass(binaryExpression.getLOperand()), true, searchInheritors
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
prev = parent;
|
||||
parent = parent.getParent();
|
||||
}
|
||||
if (parent instanceof PsiExpressionList) {
|
||||
processMembers(results, getCalledClass(parent.getParent()), true, searchInheritors);
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static PsiClass getCalledClass(@Nullable PsiElement call) {
|
||||
if (call instanceof PsiMethodCallExpression) {
|
||||
for (final JavaResolveResult result : ((PsiMethodCallExpression)call).getMethodExpression().multiResolve(true)) {
|
||||
final PsiElement element = result.getElement();
|
||||
if (element instanceof PsiMethod) {
|
||||
final PsiClass aClass = ((PsiMethod)element).getContainingClass();
|
||||
if (aClass != null) {
|
||||
return aClass;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (call instanceof PsiNewExpression) {
|
||||
final PsiJavaCodeReferenceElement reference = ((PsiNewExpression)call).getClassReference();
|
||||
if (reference != null) {
|
||||
for (final JavaResolveResult result : reference.multiResolve(true)) {
|
||||
final PsiElement element = result.getElement();
|
||||
if (element instanceof PsiClass) {
|
||||
return (PsiClass)element;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
protected LookupElement createFieldElement(PsiField field) {
|
||||
if (!myExpectedType.isAssignableFrom(field.getType())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new VariableLookupItem(field, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
protected LookupElement createMethodElement(PsiMethod method) {
|
||||
PsiSubstitutor substitutor = SmartCompletionDecorator.calculateMethodReturnTypeSubstitutor(method, myExpectedType);
|
||||
PsiType type = substitutor.substitute(method.getReturnType());
|
||||
if (type == null || !myExpectedType.isAssignableFrom(type)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
JavaMethodCallElement item = new JavaMethodCallElement(method, false, false);
|
||||
item.setInferenceSubstitutor(substitutor, myPlace);
|
||||
return item;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2011 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.filters.getters;
|
||||
|
||||
import com.intellij.codeInsight.TailType;
|
||||
import com.intellij.codeInsight.completion.*;
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
import com.intellij.codeInsight.lookup.TailTypeDecorator;
|
||||
import com.intellij.codeInsight.lookup.VariableLookupItem;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.tree.IElementType;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.psi.util.PsiUtil;
|
||||
import com.intellij.util.Consumer;
|
||||
import com.intellij.util.containers.ContainerUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public class JavaMembersGetter extends MembersGetter {
|
||||
private final PsiType myExpectedType;
|
||||
|
||||
public JavaMembersGetter(@NotNull PsiType expectedType, CompletionParameters parameters) {
|
||||
super(new JavaStaticMemberProcessor(parameters), parameters.getPosition());
|
||||
myExpectedType = JavaCompletionUtil.originalize(expectedType);
|
||||
}
|
||||
|
||||
public void addMembers(boolean searchInheritors, final Consumer<LookupElement> results) {
|
||||
if (myExpectedType instanceof PsiPrimitiveType && PsiType.DOUBLE.isAssignableFrom(myExpectedType)) {
|
||||
addConstantsFromTargetClass(results, searchInheritors);
|
||||
addConstantsFromReferencedClassesInSwitch(results);
|
||||
}
|
||||
|
||||
if (myPlace.getParent().getParent() instanceof PsiSwitchLabelStatement) {
|
||||
return; //non-enum values are processed above, enum values will be suggested by reference completion
|
||||
}
|
||||
|
||||
final PsiClass psiClass = PsiUtil.resolveClassInType(myExpectedType);
|
||||
processMembers(results, psiClass, PsiTreeUtil.getParentOfType(myPlace, PsiAnnotation.class) == null, searchInheritors);
|
||||
}
|
||||
|
||||
private void addConstantsFromReferencedClassesInSwitch(final Consumer<LookupElement> results) {
|
||||
final Set<PsiField> fields = ReferenceExpressionCompletionContributor.findConstantsUsedInSwitch(myPlace);
|
||||
final Set<PsiClass> classes = new HashSet<PsiClass>();
|
||||
for (PsiField field : fields) {
|
||||
ContainerUtil.addIfNotNull(classes, field.getContainingClass());
|
||||
}
|
||||
for (PsiClass aClass : classes) {
|
||||
processMembers(new Consumer<LookupElement>() {
|
||||
@Override
|
||||
public void consume(LookupElement element) {
|
||||
//noinspection SuspiciousMethodCalls
|
||||
if (!fields.contains(element.getObject())) {
|
||||
results.consume(TailTypeDecorator.withTail(element, TailType.CASE_COLON));
|
||||
}
|
||||
}
|
||||
}, aClass, true, false);
|
||||
}
|
||||
}
|
||||
|
||||
private void addConstantsFromTargetClass(Consumer<LookupElement> results, boolean searchInheritors) {
|
||||
PsiElement parent = myPlace.getParent();
|
||||
if (!(parent instanceof PsiReferenceExpression)) {
|
||||
return;
|
||||
}
|
||||
|
||||
PsiElement prev = parent;
|
||||
parent = parent.getParent();
|
||||
while (parent instanceof PsiBinaryExpression) {
|
||||
final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)parent;
|
||||
final IElementType op = binaryExpression.getOperationTokenType();
|
||||
if (JavaTokenType.EQEQ == op || JavaTokenType.NE == op) {
|
||||
if (prev == binaryExpression.getROperand()) {
|
||||
processMembers(results, getCalledClass(binaryExpression.getLOperand()), true, searchInheritors
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
prev = parent;
|
||||
parent = parent.getParent();
|
||||
}
|
||||
if (parent instanceof PsiExpressionList) {
|
||||
processMembers(results, getCalledClass(parent.getParent()), true, searchInheritors);
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static PsiClass getCalledClass(@Nullable PsiElement call) {
|
||||
if (call instanceof PsiMethodCallExpression) {
|
||||
for (final JavaResolveResult result : ((PsiMethodCallExpression)call).getMethodExpression().multiResolve(true)) {
|
||||
final PsiElement element = result.getElement();
|
||||
if (element instanceof PsiMethod) {
|
||||
final PsiClass aClass = ((PsiMethod)element).getContainingClass();
|
||||
if (aClass != null) {
|
||||
return aClass;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (call instanceof PsiNewExpression) {
|
||||
final PsiJavaCodeReferenceElement reference = ((PsiNewExpression)call).getClassReference();
|
||||
if (reference != null) {
|
||||
for (final JavaResolveResult result : reference.multiResolve(true)) {
|
||||
final PsiElement element = result.getElement();
|
||||
if (element instanceof PsiClass) {
|
||||
return (PsiClass)element;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
protected LookupElement createFieldElement(PsiField field) {
|
||||
if (!myExpectedType.isAssignableFrom(field.getType())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new VariableLookupItem(field, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
protected LookupElement createMethodElement(PsiMethod method) {
|
||||
PsiSubstitutor substitutor = SmartCompletionDecorator.calculateMethodReturnTypeSubstitutor(method, myExpectedType);
|
||||
PsiType type = substitutor.substitute(method.getReturnType());
|
||||
if (type == null || !myExpectedType.isAssignableFrom(type)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
JavaMethodCallElement item = new JavaMethodCallElement(method, false, false);
|
||||
item.setInferenceSubstitutor(substitutor, myPlace);
|
||||
return item;
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,111 +1,111 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.formatter.java;
|
||||
|
||||
import com.intellij.formatting.*;
|
||||
import com.intellij.lang.ASTNode;
|
||||
import com.intellij.openapi.util.TextRange;
|
||||
import com.intellij.psi.impl.source.codeStyle.ShiftIndentInsideHelper;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class LeafBlock implements ASTBlock{
|
||||
private int myStartOffset = -1;
|
||||
private final ASTNode myNode;
|
||||
private final Wrap myWrap;
|
||||
private final Alignment myAlignment;
|
||||
|
||||
private static final ArrayList<Block> EMPTY_SUB_BLOCKS = new ArrayList<Block>();
|
||||
private final Indent myIndent;
|
||||
|
||||
public LeafBlock(final ASTNode node,
|
||||
final Wrap wrap,
|
||||
final Alignment alignment,
|
||||
Indent indent)
|
||||
{
|
||||
myNode = node;
|
||||
myWrap = wrap;
|
||||
myAlignment = alignment;
|
||||
myIndent = indent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ASTNode getNode() {
|
||||
return myNode;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public TextRange getTextRange() {
|
||||
if (myStartOffset != -1) {
|
||||
return new TextRange(myStartOffset, myStartOffset + myNode.getTextLength());
|
||||
}
|
||||
return myNode.getTextRange();
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public List<Block> getSubBlocks() {
|
||||
return EMPTY_SUB_BLOCKS;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Wrap getWrap() {
|
||||
return myWrap;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Indent getIndent() {
|
||||
return myIndent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Alignment getAlignment() {
|
||||
return myAlignment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Spacing getSpacing(Block child1, @NotNull Block child2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public ASTNode getTreeNode() {
|
||||
return myNode;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public ChildAttributes getChildAttributes(final int newChildIndex) {
|
||||
return new ChildAttributes(getIndent(), null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isIncomplete() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLeaf() {
|
||||
return ShiftIndentInsideHelper.mayShiftIndentInside(myNode);
|
||||
}
|
||||
|
||||
public void setStartOffset(final int startOffset) {
|
||||
myStartOffset = startOffset;
|
||||
// if (startOffset != -1) assert startOffset == myNode.getTextRange().getStartOffset();
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.formatter.java;
|
||||
|
||||
import com.intellij.formatting.*;
|
||||
import com.intellij.lang.ASTNode;
|
||||
import com.intellij.openapi.util.TextRange;
|
||||
import com.intellij.psi.impl.source.codeStyle.ShiftIndentInsideHelper;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class LeafBlock implements ASTBlock{
|
||||
private int myStartOffset = -1;
|
||||
private final ASTNode myNode;
|
||||
private final Wrap myWrap;
|
||||
private final Alignment myAlignment;
|
||||
|
||||
private static final ArrayList<Block> EMPTY_SUB_BLOCKS = new ArrayList<Block>();
|
||||
private final Indent myIndent;
|
||||
|
||||
public LeafBlock(final ASTNode node,
|
||||
final Wrap wrap,
|
||||
final Alignment alignment,
|
||||
Indent indent)
|
||||
{
|
||||
myNode = node;
|
||||
myWrap = wrap;
|
||||
myAlignment = alignment;
|
||||
myIndent = indent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ASTNode getNode() {
|
||||
return myNode;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public TextRange getTextRange() {
|
||||
if (myStartOffset != -1) {
|
||||
return new TextRange(myStartOffset, myStartOffset + myNode.getTextLength());
|
||||
}
|
||||
return myNode.getTextRange();
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public List<Block> getSubBlocks() {
|
||||
return EMPTY_SUB_BLOCKS;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Wrap getWrap() {
|
||||
return myWrap;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Indent getIndent() {
|
||||
return myIndent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Alignment getAlignment() {
|
||||
return myAlignment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Spacing getSpacing(Block child1, @NotNull Block child2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public ASTNode getTreeNode() {
|
||||
return myNode;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public ChildAttributes getChildAttributes(final int newChildIndex) {
|
||||
return new ChildAttributes(getIndent(), null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isIncomplete() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLeaf() {
|
||||
return ShiftIndentInsideHelper.mayShiftIndentInside(myNode);
|
||||
}
|
||||
|
||||
public void setStartOffset(final int startOffset) {
|
||||
myStartOffset = startOffset;
|
||||
// if (startOffset != -1) assert startOffset == myNode.getTextRange().getStartOffset();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,134 +1,134 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.formatter.java;
|
||||
|
||||
import com.intellij.formatting.*;
|
||||
import com.intellij.formatting.alignment.AlignmentStrategy;
|
||||
import com.intellij.lang.ASTNode;
|
||||
import com.intellij.openapi.util.TextRange;
|
||||
import com.intellij.psi.PsiFile;
|
||||
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
|
||||
import com.intellij.psi.formatter.FormatterUtil;
|
||||
import com.intellij.psi.impl.source.tree.JavaDocElementType;
|
||||
import com.intellij.psi.impl.source.tree.JavaElementType;
|
||||
import com.intellij.psi.impl.source.tree.StdTokenSets;
|
||||
import com.intellij.psi.tree.IElementType;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class SimpleJavaBlock extends AbstractJavaBlock {
|
||||
|
||||
private int myStartOffset = -1;
|
||||
private final Map<IElementType, Wrap> myReservedWrap = new HashMap<IElementType, Wrap>();
|
||||
|
||||
public SimpleJavaBlock(final ASTNode node, final Wrap wrap, final AlignmentStrategy alignment, final Indent indent, CommonCodeStyleSettings settings) {
|
||||
super(node, wrap, alignment, indent,settings);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<Block> buildChildren() {
|
||||
ASTNode child = myNode.getFirstChildNode();
|
||||
int offset = myStartOffset != -1 ? myStartOffset : child != null ? child.getTextRange().getStartOffset():0;
|
||||
final ArrayList<Block> result = new ArrayList<Block>();
|
||||
|
||||
Indent indent = null;
|
||||
while (child != null) {
|
||||
if (StdTokenSets.COMMENT_BIT_SET.contains(child.getElementType()) || child.getElementType() == JavaDocElementType.DOC_COMMENT) {
|
||||
result.add(createJavaBlock(child, mySettings, Indent.getNoneIndent(), null, AlignmentStrategy.getNullStrategy()));
|
||||
indent = Indent.getNoneIndent();
|
||||
}
|
||||
else if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
|
||||
break;
|
||||
}
|
||||
|
||||
offset += child.getTextLength();
|
||||
child = child.getTreeNext();
|
||||
}
|
||||
|
||||
myReservedAlignment = createChildAlignment();
|
||||
myReservedAlignment2 = createChildAlignment2(myReservedAlignment);
|
||||
Wrap childWrap = createChildWrap();
|
||||
while (child != null) {
|
||||
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0){
|
||||
final ASTNode astNode = child;
|
||||
AlignmentStrategy alignmentStrategyToUse = ALIGN_IN_COLUMNS_ELEMENT_TYPES.contains(myNode.getElementType())
|
||||
? myAlignmentStrategy
|
||||
: AlignmentStrategy.wrap(chooseAlignment(myReservedAlignment, myReservedAlignment2, child));
|
||||
child = processChild(result, astNode, alignmentStrategyToUse, childWrap, indent, offset);
|
||||
if (astNode != child && child != null) {
|
||||
offset = child.getTextRange().getStartOffset();
|
||||
}
|
||||
if (indent != null
|
||||
&& !(myNode.getPsi() instanceof PsiFile) && child != null && child.getElementType() != JavaElementType.MODIFIER_LIST)
|
||||
{
|
||||
indent = Indent.getContinuationIndent(myIndentSettings.USE_RELATIVE_INDENTS);
|
||||
}
|
||||
}
|
||||
if (child != null) {
|
||||
offset += child.getTextLength();
|
||||
child = child.getTreeNext();
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public TextRange getTextRange() {
|
||||
if (myStartOffset != -1) {
|
||||
return new TextRange(myStartOffset, myStartOffset + myNode.getTextLength());
|
||||
}
|
||||
return super.getTextRange();
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public ChildAttributes getChildAttributes(final int newChildIndex) {
|
||||
if (myNode.getElementType() == JavaElementType.CONDITIONAL_EXPRESSION && mySettings.ALIGN_MULTILINE_TERNARY_OPERATION) {
|
||||
final Alignment usedAlignment = getUsedAlignment(newChildIndex);
|
||||
if (usedAlignment != null) {
|
||||
return new ChildAttributes(null, usedAlignment);
|
||||
} else {
|
||||
return super.getChildAttributes(newChildIndex);
|
||||
}
|
||||
}
|
||||
else if (myNode.getElementType() == JavaElementType.SWITCH_LABEL_STATEMENT) {
|
||||
return new ChildAttributes(Indent.getNormalIndent(), null);
|
||||
}
|
||||
else {
|
||||
return super.getChildAttributes(newChildIndex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Wrap getReservedWrap(final IElementType elementType) {
|
||||
return myReservedWrap.get(elementType);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setReservedWrap(final Wrap reservedWrap, final IElementType operationType) {
|
||||
myReservedWrap.put(operationType, reservedWrap);
|
||||
}
|
||||
|
||||
public void setStartOffset(final int startOffset) {
|
||||
myStartOffset = startOffset;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.formatter.java;
|
||||
|
||||
import com.intellij.formatting.*;
|
||||
import com.intellij.formatting.alignment.AlignmentStrategy;
|
||||
import com.intellij.lang.ASTNode;
|
||||
import com.intellij.openapi.util.TextRange;
|
||||
import com.intellij.psi.PsiFile;
|
||||
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
|
||||
import com.intellij.psi.formatter.FormatterUtil;
|
||||
import com.intellij.psi.impl.source.tree.JavaDocElementType;
|
||||
import com.intellij.psi.impl.source.tree.JavaElementType;
|
||||
import com.intellij.psi.impl.source.tree.StdTokenSets;
|
||||
import com.intellij.psi.tree.IElementType;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class SimpleJavaBlock extends AbstractJavaBlock {
|
||||
|
||||
private int myStartOffset = -1;
|
||||
private final Map<IElementType, Wrap> myReservedWrap = new HashMap<IElementType, Wrap>();
|
||||
|
||||
public SimpleJavaBlock(final ASTNode node, final Wrap wrap, final AlignmentStrategy alignment, final Indent indent, CommonCodeStyleSettings settings) {
|
||||
super(node, wrap, alignment, indent,settings);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<Block> buildChildren() {
|
||||
ASTNode child = myNode.getFirstChildNode();
|
||||
int offset = myStartOffset != -1 ? myStartOffset : child != null ? child.getTextRange().getStartOffset():0;
|
||||
final ArrayList<Block> result = new ArrayList<Block>();
|
||||
|
||||
Indent indent = null;
|
||||
while (child != null) {
|
||||
if (StdTokenSets.COMMENT_BIT_SET.contains(child.getElementType()) || child.getElementType() == JavaDocElementType.DOC_COMMENT) {
|
||||
result.add(createJavaBlock(child, mySettings, Indent.getNoneIndent(), null, AlignmentStrategy.getNullStrategy()));
|
||||
indent = Indent.getNoneIndent();
|
||||
}
|
||||
else if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
|
||||
break;
|
||||
}
|
||||
|
||||
offset += child.getTextLength();
|
||||
child = child.getTreeNext();
|
||||
}
|
||||
|
||||
myReservedAlignment = createChildAlignment();
|
||||
myReservedAlignment2 = createChildAlignment2(myReservedAlignment);
|
||||
Wrap childWrap = createChildWrap();
|
||||
while (child != null) {
|
||||
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0){
|
||||
final ASTNode astNode = child;
|
||||
AlignmentStrategy alignmentStrategyToUse = ALIGN_IN_COLUMNS_ELEMENT_TYPES.contains(myNode.getElementType())
|
||||
? myAlignmentStrategy
|
||||
: AlignmentStrategy.wrap(chooseAlignment(myReservedAlignment, myReservedAlignment2, child));
|
||||
child = processChild(result, astNode, alignmentStrategyToUse, childWrap, indent, offset);
|
||||
if (astNode != child && child != null) {
|
||||
offset = child.getTextRange().getStartOffset();
|
||||
}
|
||||
if (indent != null
|
||||
&& !(myNode.getPsi() instanceof PsiFile) && child != null && child.getElementType() != JavaElementType.MODIFIER_LIST)
|
||||
{
|
||||
indent = Indent.getContinuationIndent(myIndentSettings.USE_RELATIVE_INDENTS);
|
||||
}
|
||||
}
|
||||
if (child != null) {
|
||||
offset += child.getTextLength();
|
||||
child = child.getTreeNext();
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public TextRange getTextRange() {
|
||||
if (myStartOffset != -1) {
|
||||
return new TextRange(myStartOffset, myStartOffset + myNode.getTextLength());
|
||||
}
|
||||
return super.getTextRange();
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public ChildAttributes getChildAttributes(final int newChildIndex) {
|
||||
if (myNode.getElementType() == JavaElementType.CONDITIONAL_EXPRESSION && mySettings.ALIGN_MULTILINE_TERNARY_OPERATION) {
|
||||
final Alignment usedAlignment = getUsedAlignment(newChildIndex);
|
||||
if (usedAlignment != null) {
|
||||
return new ChildAttributes(null, usedAlignment);
|
||||
} else {
|
||||
return super.getChildAttributes(newChildIndex);
|
||||
}
|
||||
}
|
||||
else if (myNode.getElementType() == JavaElementType.SWITCH_LABEL_STATEMENT) {
|
||||
return new ChildAttributes(Indent.getNormalIndent(), null);
|
||||
}
|
||||
else {
|
||||
return super.getChildAttributes(newChildIndex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Wrap getReservedWrap(final IElementType elementType) {
|
||||
return myReservedWrap.get(elementType);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setReservedWrap(final Wrap reservedWrap, final IElementType operationType) {
|
||||
myReservedWrap.put(operationType, reservedWrap);
|
||||
}
|
||||
|
||||
public void setStartOffset(final int startOffset) {
|
||||
myStartOffset = startOffset;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,65 +1,65 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.impl;
|
||||
|
||||
import com.intellij.openapi.module.Module;
|
||||
import com.intellij.openapi.module.ModuleUtil;
|
||||
import com.intellij.openapi.projectRoots.JavaSdk;
|
||||
import com.intellij.openapi.projectRoots.JavaSdkVersion;
|
||||
import com.intellij.openapi.projectRoots.Sdk;
|
||||
import com.intellij.openapi.roots.ModuleRootManager;
|
||||
import org.intellij.lang.regexp.RegExpLanguageHost;
|
||||
import org.intellij.lang.regexp.psi.RegExpGroup;
|
||||
|
||||
/**
|
||||
* @author yole
|
||||
*/
|
||||
public class JavaRegExpHost implements RegExpLanguageHost {
|
||||
@Override
|
||||
public boolean characterNeedsEscaping(char c) {
|
||||
return c == ']' || c == '}';
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsPerl5EmbeddedComments() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsPossessiveQuantifiers() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsPythonConditionalRefs() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsNamedGroupSyntax(RegExpGroup group) {
|
||||
if (group.isRubyNamedGroup()) {
|
||||
final Module module = ModuleUtil.findModuleForPsiElement(group);
|
||||
if (module != null) {
|
||||
final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
|
||||
if (sdk != null && sdk.getSdkType() instanceof JavaSdk) {
|
||||
final JavaSdkVersion version = JavaSdk.getInstance().getVersion(sdk);
|
||||
return version != null && version.isAtLeast(JavaSdkVersion.JDK_1_7);
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.impl;
|
||||
|
||||
import com.intellij.openapi.module.Module;
|
||||
import com.intellij.openapi.module.ModuleUtil;
|
||||
import com.intellij.openapi.projectRoots.JavaSdk;
|
||||
import com.intellij.openapi.projectRoots.JavaSdkVersion;
|
||||
import com.intellij.openapi.projectRoots.Sdk;
|
||||
import com.intellij.openapi.roots.ModuleRootManager;
|
||||
import org.intellij.lang.regexp.RegExpLanguageHost;
|
||||
import org.intellij.lang.regexp.psi.RegExpGroup;
|
||||
|
||||
/**
|
||||
* @author yole
|
||||
*/
|
||||
public class JavaRegExpHost implements RegExpLanguageHost {
|
||||
@Override
|
||||
public boolean characterNeedsEscaping(char c) {
|
||||
return c == ']' || c == '}';
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsPerl5EmbeddedComments() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsPossessiveQuantifiers() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsPythonConditionalRefs() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsNamedGroupSyntax(RegExpGroup group) {
|
||||
if (group.isRubyNamedGroup()) {
|
||||
final Module module = ModuleUtil.findModuleForPsiElement(group);
|
||||
if (module != null) {
|
||||
final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
|
||||
if (sdk != null && sdk.getSdkType() instanceof JavaSdk) {
|
||||
final JavaSdkVersion version = JavaSdk.getInstance().getVersion(sdk);
|
||||
return version != null && version.isAtLeast(JavaSdkVersion.JDK_1_7);
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,219 +1,219 @@
|
||||
/*
|
||||
* Copyright 2000-2009 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @author max
|
||||
*/
|
||||
package com.intellij.psi.impl.file;
|
||||
|
||||
import com.intellij.core.CoreJavaDirectoryService;
|
||||
import com.intellij.ide.fileTemplates.FileTemplate;
|
||||
import com.intellij.ide.fileTemplates.FileTemplateManager;
|
||||
import com.intellij.ide.fileTemplates.FileTemplateUtil;
|
||||
import com.intellij.ide.fileTemplates.JavaTemplateUtil;
|
||||
import com.intellij.ide.fileTemplates.ui.CreateFromTemplateDialog;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.fileTypes.StdFileTypes;
|
||||
import com.intellij.openapi.module.LanguageLevelUtil;
|
||||
import com.intellij.openapi.module.Module;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
|
||||
import com.intellij.openapi.roots.ProjectFileIndex;
|
||||
import com.intellij.openapi.roots.ProjectRootManager;
|
||||
import com.intellij.openapi.util.Key;
|
||||
import com.intellij.openapi.util.text.StringUtil;
|
||||
import com.intellij.openapi.vfs.VirtualFile;
|
||||
import com.intellij.pom.java.LanguageLevel;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.util.PsiUtil;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
public class JavaDirectoryServiceImpl extends CoreJavaDirectoryService {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.file.JavaDirectoryServiceImpl");
|
||||
|
||||
@Override
|
||||
public PsiPackage getPackage(@NotNull PsiDirectory dir) {
|
||||
ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(dir.getProject()).getFileIndex();
|
||||
String packageName = projectFileIndex.getPackageNameByDirectory(dir.getVirtualFile());
|
||||
if (packageName == null) return null;
|
||||
return JavaPsiFacade.getInstance(dir.getProject()).findPackage(packageName);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public PsiClass createClass(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
|
||||
return createClassFromTemplate(dir, name, JavaTemplateUtil.INTERNAL_CLASS_TEMPLATE_NAME);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public PsiClass createClass(@NotNull PsiDirectory dir, @NotNull String name, @NotNull String templateName) throws IncorrectOperationException {
|
||||
return createClassFromTemplate(dir, name, templateName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiClass createClass(@NotNull PsiDirectory dir,
|
||||
@NotNull String name,
|
||||
@NotNull String templateName,
|
||||
boolean askForUndefinedVariables) throws IncorrectOperationException {
|
||||
return createClass(dir, name, templateName, askForUndefinedVariables, Collections.<String, String>emptyMap());
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiClass createClass(@NotNull PsiDirectory dir,
|
||||
@NotNull String name,
|
||||
@NotNull String templateName,
|
||||
boolean askForUndefinedVariables, @NotNull final Map<String, String> additionalProperties) throws IncorrectOperationException {
|
||||
return createClassFromTemplate(dir, name, templateName, askForUndefinedVariables, additionalProperties);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public PsiClass createInterface(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
|
||||
String templateName = JavaTemplateUtil.INTERNAL_INTERFACE_TEMPLATE_NAME;
|
||||
PsiClass someClass = createClassFromTemplate(dir, name, templateName);
|
||||
if (!someClass.isInterface()) {
|
||||
throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName));
|
||||
}
|
||||
return someClass;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public PsiClass createEnum(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
|
||||
String templateName = JavaTemplateUtil.INTERNAL_ENUM_TEMPLATE_NAME;
|
||||
PsiClass someClass = createClassFromTemplate(dir, name, templateName);
|
||||
if (!someClass.isEnum()) {
|
||||
throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName));
|
||||
}
|
||||
return someClass;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public PsiClass createAnnotationType(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
|
||||
String templateName = JavaTemplateUtil.INTERNAL_ANNOTATION_TYPE_TEMPLATE_NAME;
|
||||
PsiClass someClass = createClassFromTemplate(dir, name, templateName);
|
||||
if (!someClass.isAnnotationType()) {
|
||||
throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName));
|
||||
}
|
||||
return someClass;
|
||||
}
|
||||
|
||||
private static PsiClass createClassFromTemplate(@NotNull PsiDirectory dir, String name, String templateName) throws IncorrectOperationException {
|
||||
return createClassFromTemplate(dir, name, templateName, false, Collections.<String, String>emptyMap());
|
||||
}
|
||||
|
||||
private static PsiClass createClassFromTemplate(@NotNull PsiDirectory dir,
|
||||
String name,
|
||||
String templateName,
|
||||
boolean askToDefineVariables, @NotNull Map<String, String> additionalProperties) throws IncorrectOperationException {
|
||||
//checkCreateClassOrInterface(dir, name);
|
||||
|
||||
FileTemplate template = FileTemplateManager.getInstance().getInternalTemplate(templateName);
|
||||
|
||||
Properties defaultProperties = FileTemplateManager.getInstance().getDefaultProperties(dir.getProject());
|
||||
Properties properties = new Properties(defaultProperties);
|
||||
properties.setProperty(FileTemplate.ATTRIBUTE_NAME, name);
|
||||
for (Map.Entry<String, String> entry : additionalProperties.entrySet()) {
|
||||
properties.setProperty(entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
String ext = StdFileTypes.JAVA.getDefaultExtension();
|
||||
String fileName = name + "." + ext;
|
||||
|
||||
PsiElement element;
|
||||
try {
|
||||
element = askToDefineVariables ? new CreateFromTemplateDialog(dir.getProject(), dir, template, null, properties).create()
|
||||
: FileTemplateUtil.createFromTemplate(template, fileName, properties, dir);
|
||||
}
|
||||
catch (IncorrectOperationException e) {
|
||||
throw e;
|
||||
}
|
||||
catch (Exception e) {
|
||||
LOG.error(e);
|
||||
return null;
|
||||
}
|
||||
if (element == null) return null;
|
||||
final PsiJavaFile file = (PsiJavaFile)element.getContainingFile();
|
||||
PsiClass[] classes = file.getClasses();
|
||||
if (classes.length < 1) {
|
||||
throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName));
|
||||
}
|
||||
return classes[0];
|
||||
}
|
||||
|
||||
private static String getIncorrectTemplateMessage(String templateName) {
|
||||
return PsiBundle.message("psi.error.incorroect.class.template.message",
|
||||
FileTemplateManager.getInstance().internalTemplateToSubject(templateName), templateName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkCreateClass(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
|
||||
checkCreateClassOrInterface(dir, name);
|
||||
}
|
||||
|
||||
public static void checkCreateClassOrInterface(@NotNull PsiDirectory directory, String name) throws IncorrectOperationException {
|
||||
PsiUtil.checkIsIdentifier(directory.getManager(), name);
|
||||
|
||||
String fileName = name + "." + StdFileTypes.JAVA.getDefaultExtension();
|
||||
directory.checkCreateFile(fileName);
|
||||
|
||||
PsiNameHelper helper = JavaPsiFacade.getInstance(directory.getProject()).getNameHelper();
|
||||
PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(directory);
|
||||
String qualifiedName = aPackage == null ? null : aPackage.getQualifiedName();
|
||||
if (!StringUtil.isEmpty(qualifiedName) && !helper.isQualifiedName(qualifiedName)) {
|
||||
throw new IncorrectOperationException("Cannot create class in invalid package: '"+qualifiedName+"'");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSourceRoot(@NotNull PsiDirectory dir) {
|
||||
final VirtualFile file = dir.getVirtualFile();
|
||||
final VirtualFile sourceRoot = ProjectRootManager.getInstance(dir.getProject()).getFileIndex().getSourceRootForFile(file);
|
||||
return file.equals(sourceRoot);
|
||||
}
|
||||
|
||||
private static final Key<LanguageLevel> LANG_LEVEL_IN_DIRECTORY = new Key<LanguageLevel>("LANG_LEVEL_IN_DIRECTORY");
|
||||
@Override
|
||||
public LanguageLevel getLanguageLevel(@NotNull PsiDirectory dir) {
|
||||
synchronized (PsiLock.LOCK) {
|
||||
LanguageLevel level = dir.getUserData(LANG_LEVEL_IN_DIRECTORY);
|
||||
if (level == null) {
|
||||
level = getLanguageLevelInner(dir);
|
||||
dir.putUserData(LANG_LEVEL_IN_DIRECTORY, level);
|
||||
}
|
||||
return level;
|
||||
}
|
||||
}
|
||||
|
||||
private static LanguageLevel getLanguageLevelInner(@NotNull PsiDirectory dir) {
|
||||
final VirtualFile virtualFile = dir.getVirtualFile();
|
||||
final Project project = dir.getProject();
|
||||
final Module module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(virtualFile);
|
||||
if (module != null) {
|
||||
return LanguageLevelUtil.getEffectiveLanguageLevel(module);
|
||||
}
|
||||
|
||||
return LanguageLevelProjectExtension.getInstance(project).getLanguageLevel();
|
||||
}
|
||||
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @author max
|
||||
*/
|
||||
package com.intellij.psi.impl.file;
|
||||
|
||||
import com.intellij.core.CoreJavaDirectoryService;
|
||||
import com.intellij.ide.fileTemplates.FileTemplate;
|
||||
import com.intellij.ide.fileTemplates.FileTemplateManager;
|
||||
import com.intellij.ide.fileTemplates.FileTemplateUtil;
|
||||
import com.intellij.ide.fileTemplates.JavaTemplateUtil;
|
||||
import com.intellij.ide.fileTemplates.ui.CreateFromTemplateDialog;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.fileTypes.StdFileTypes;
|
||||
import com.intellij.openapi.module.LanguageLevelUtil;
|
||||
import com.intellij.openapi.module.Module;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
|
||||
import com.intellij.openapi.roots.ProjectFileIndex;
|
||||
import com.intellij.openapi.roots.ProjectRootManager;
|
||||
import com.intellij.openapi.util.Key;
|
||||
import com.intellij.openapi.util.text.StringUtil;
|
||||
import com.intellij.openapi.vfs.VirtualFile;
|
||||
import com.intellij.pom.java.LanguageLevel;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.util.PsiUtil;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
public class JavaDirectoryServiceImpl extends CoreJavaDirectoryService {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.file.JavaDirectoryServiceImpl");
|
||||
|
||||
@Override
|
||||
public PsiPackage getPackage(@NotNull PsiDirectory dir) {
|
||||
ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(dir.getProject()).getFileIndex();
|
||||
String packageName = projectFileIndex.getPackageNameByDirectory(dir.getVirtualFile());
|
||||
if (packageName == null) return null;
|
||||
return JavaPsiFacade.getInstance(dir.getProject()).findPackage(packageName);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public PsiClass createClass(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
|
||||
return createClassFromTemplate(dir, name, JavaTemplateUtil.INTERNAL_CLASS_TEMPLATE_NAME);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public PsiClass createClass(@NotNull PsiDirectory dir, @NotNull String name, @NotNull String templateName) throws IncorrectOperationException {
|
||||
return createClassFromTemplate(dir, name, templateName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiClass createClass(@NotNull PsiDirectory dir,
|
||||
@NotNull String name,
|
||||
@NotNull String templateName,
|
||||
boolean askForUndefinedVariables) throws IncorrectOperationException {
|
||||
return createClass(dir, name, templateName, askForUndefinedVariables, Collections.<String, String>emptyMap());
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiClass createClass(@NotNull PsiDirectory dir,
|
||||
@NotNull String name,
|
||||
@NotNull String templateName,
|
||||
boolean askForUndefinedVariables, @NotNull final Map<String, String> additionalProperties) throws IncorrectOperationException {
|
||||
return createClassFromTemplate(dir, name, templateName, askForUndefinedVariables, additionalProperties);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public PsiClass createInterface(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
|
||||
String templateName = JavaTemplateUtil.INTERNAL_INTERFACE_TEMPLATE_NAME;
|
||||
PsiClass someClass = createClassFromTemplate(dir, name, templateName);
|
||||
if (!someClass.isInterface()) {
|
||||
throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName));
|
||||
}
|
||||
return someClass;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public PsiClass createEnum(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
|
||||
String templateName = JavaTemplateUtil.INTERNAL_ENUM_TEMPLATE_NAME;
|
||||
PsiClass someClass = createClassFromTemplate(dir, name, templateName);
|
||||
if (!someClass.isEnum()) {
|
||||
throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName));
|
||||
}
|
||||
return someClass;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public PsiClass createAnnotationType(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
|
||||
String templateName = JavaTemplateUtil.INTERNAL_ANNOTATION_TYPE_TEMPLATE_NAME;
|
||||
PsiClass someClass = createClassFromTemplate(dir, name, templateName);
|
||||
if (!someClass.isAnnotationType()) {
|
||||
throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName));
|
||||
}
|
||||
return someClass;
|
||||
}
|
||||
|
||||
private static PsiClass createClassFromTemplate(@NotNull PsiDirectory dir, String name, String templateName) throws IncorrectOperationException {
|
||||
return createClassFromTemplate(dir, name, templateName, false, Collections.<String, String>emptyMap());
|
||||
}
|
||||
|
||||
private static PsiClass createClassFromTemplate(@NotNull PsiDirectory dir,
|
||||
String name,
|
||||
String templateName,
|
||||
boolean askToDefineVariables, @NotNull Map<String, String> additionalProperties) throws IncorrectOperationException {
|
||||
//checkCreateClassOrInterface(dir, name);
|
||||
|
||||
FileTemplate template = FileTemplateManager.getInstance().getInternalTemplate(templateName);
|
||||
|
||||
Properties defaultProperties = FileTemplateManager.getInstance().getDefaultProperties(dir.getProject());
|
||||
Properties properties = new Properties(defaultProperties);
|
||||
properties.setProperty(FileTemplate.ATTRIBUTE_NAME, name);
|
||||
for (Map.Entry<String, String> entry : additionalProperties.entrySet()) {
|
||||
properties.setProperty(entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
String ext = StdFileTypes.JAVA.getDefaultExtension();
|
||||
String fileName = name + "." + ext;
|
||||
|
||||
PsiElement element;
|
||||
try {
|
||||
element = askToDefineVariables ? new CreateFromTemplateDialog(dir.getProject(), dir, template, null, properties).create()
|
||||
: FileTemplateUtil.createFromTemplate(template, fileName, properties, dir);
|
||||
}
|
||||
catch (IncorrectOperationException e) {
|
||||
throw e;
|
||||
}
|
||||
catch (Exception e) {
|
||||
LOG.error(e);
|
||||
return null;
|
||||
}
|
||||
if (element == null) return null;
|
||||
final PsiJavaFile file = (PsiJavaFile)element.getContainingFile();
|
||||
PsiClass[] classes = file.getClasses();
|
||||
if (classes.length < 1) {
|
||||
throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName));
|
||||
}
|
||||
return classes[0];
|
||||
}
|
||||
|
||||
private static String getIncorrectTemplateMessage(String templateName) {
|
||||
return PsiBundle.message("psi.error.incorroect.class.template.message",
|
||||
FileTemplateManager.getInstance().internalTemplateToSubject(templateName), templateName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkCreateClass(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
|
||||
checkCreateClassOrInterface(dir, name);
|
||||
}
|
||||
|
||||
public static void checkCreateClassOrInterface(@NotNull PsiDirectory directory, String name) throws IncorrectOperationException {
|
||||
PsiUtil.checkIsIdentifier(directory.getManager(), name);
|
||||
|
||||
String fileName = name + "." + StdFileTypes.JAVA.getDefaultExtension();
|
||||
directory.checkCreateFile(fileName);
|
||||
|
||||
PsiNameHelper helper = JavaPsiFacade.getInstance(directory.getProject()).getNameHelper();
|
||||
PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(directory);
|
||||
String qualifiedName = aPackage == null ? null : aPackage.getQualifiedName();
|
||||
if (!StringUtil.isEmpty(qualifiedName) && !helper.isQualifiedName(qualifiedName)) {
|
||||
throw new IncorrectOperationException("Cannot create class in invalid package: '"+qualifiedName+"'");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSourceRoot(@NotNull PsiDirectory dir) {
|
||||
final VirtualFile file = dir.getVirtualFile();
|
||||
final VirtualFile sourceRoot = ProjectRootManager.getInstance(dir.getProject()).getFileIndex().getSourceRootForFile(file);
|
||||
return file.equals(sourceRoot);
|
||||
}
|
||||
|
||||
private static final Key<LanguageLevel> LANG_LEVEL_IN_DIRECTORY = new Key<LanguageLevel>("LANG_LEVEL_IN_DIRECTORY");
|
||||
@Override
|
||||
public LanguageLevel getLanguageLevel(@NotNull PsiDirectory dir) {
|
||||
synchronized (PsiLock.LOCK) {
|
||||
LanguageLevel level = dir.getUserData(LANG_LEVEL_IN_DIRECTORY);
|
||||
if (level == null) {
|
||||
level = getLanguageLevelInner(dir);
|
||||
dir.putUserData(LANG_LEVEL_IN_DIRECTORY, level);
|
||||
}
|
||||
return level;
|
||||
}
|
||||
}
|
||||
|
||||
private static LanguageLevel getLanguageLevelInner(@NotNull PsiDirectory dir) {
|
||||
final VirtualFile virtualFile = dir.getVirtualFile();
|
||||
final Project project = dir.getProject();
|
||||
final Module module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(virtualFile);
|
||||
if (module != null) {
|
||||
return LanguageLevelUtil.getEffectiveLanguageLevel(module);
|
||||
}
|
||||
|
||||
return LanguageLevelProjectExtension.getInstance(project).getLanguageLevel();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,246 +1,246 @@
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.util;
|
||||
|
||||
import com.intellij.ide.fileTemplates.FileTemplate;
|
||||
import com.intellij.ide.fileTemplates.FileTemplateManager;
|
||||
import com.intellij.ide.fileTemplates.JavaCreateFromTemplateHandler;
|
||||
import com.intellij.ide.util.DirectoryChooserUtil;
|
||||
import com.intellij.ide.util.PackageUtil;
|
||||
import com.intellij.openapi.fileTypes.StdFileTypes;
|
||||
import com.intellij.openapi.module.Module;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.roots.ModuleRootManager;
|
||||
import com.intellij.openapi.roots.impl.DirectoryIndex;
|
||||
import com.intellij.openapi.roots.impl.DirectoryInfo;
|
||||
import com.intellij.openapi.util.text.StringUtil;
|
||||
import com.intellij.openapi.vfs.VirtualFile;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.application.ApplicationManager;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
|
||||
import com.intellij.psi.search.GlobalSearchScope;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import com.intellij.util.text.StringTokenizer;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* author: lesya
|
||||
*/
|
||||
public class CreateClassUtil {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.j2ee.CreateClassUtil");
|
||||
|
||||
@NonNls public static final String DEFAULT_CLASS_TEMPLATE = "#DEFAULT_CLASS_TEMPLATE";
|
||||
@NonNls private static final String DO_NOT_CREATE_CLASS_TEMPLATE = "#DO_NOT_CREATE_CLASS_TEMPLATE";
|
||||
@NonNls private static final String CLASS_NAME_PROPERTY = "Class_Name";
|
||||
@NonNls private static final String INTERFACE_NAME_PROPERTY = "Interface_Name";
|
||||
|
||||
private CreateClassUtil() {}
|
||||
|
||||
@Nullable
|
||||
private static PsiClass createClassFromTemplate(@NotNull final Properties attributes, @Nullable final String templateName,
|
||||
@NotNull final PsiDirectory directoryRoot,
|
||||
@NotNull final String className) throws IncorrectOperationException {
|
||||
if (templateName == null) return null;
|
||||
if (templateName.equals(DO_NOT_CREATE_CLASS_TEMPLATE)) return null;
|
||||
|
||||
final Project project = directoryRoot.getProject();
|
||||
try {
|
||||
final PsiDirectory directory = createParentDirectories(directoryRoot, className);
|
||||
final PsiFile psiFile = directory.findFile(className + "." + StdFileTypes.JAVA.getDefaultExtension());
|
||||
if (psiFile != null) {
|
||||
psiFile.delete();
|
||||
}
|
||||
|
||||
final String rawClassName = extractClassName(className);
|
||||
final PsiFile existing = directory.findFile(rawClassName + ".java");
|
||||
if (existing instanceof PsiJavaFile) {
|
||||
final PsiClass[] classes = ((PsiJavaFile)existing).getClasses();
|
||||
if (classes.length > 0) {
|
||||
return classes[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
final PsiClass aClass;
|
||||
if (templateName.equals(DEFAULT_CLASS_TEMPLATE)) {
|
||||
aClass = JavaDirectoryService.getInstance().createClass(directory, rawClassName);
|
||||
}
|
||||
else {
|
||||
final FileTemplateManager fileTemplateManager = FileTemplateManager.getInstance();
|
||||
FileTemplate fileTemplate = fileTemplateManager.getJ2eeTemplate(templateName);
|
||||
LOG.assertTrue(fileTemplate != null, templateName + " not found");
|
||||
final String text = fileTemplate.getText(attributes);
|
||||
aClass = JavaCreateFromTemplateHandler.createClassOrInterface(project, directory, text, true, fileTemplate.getExtension());
|
||||
}
|
||||
return (PsiClass)JavaCodeStyleManager.getInstance(project).shortenClassReferences(aClass);
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new IncorrectOperationException(e.toString(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private static PsiDirectory createParentDirectories(@NotNull PsiDirectory directoryRoot, @NotNull String className) throws IncorrectOperationException {
|
||||
final PsiPackage currentPackage = JavaDirectoryService.getInstance().getPackage(directoryRoot);
|
||||
final String packagePrefix = currentPackage == null? null : currentPackage.getQualifiedName() + ".";
|
||||
final String packageName = extractPackage(packagePrefix != null && className.startsWith(packagePrefix)?
|
||||
className.substring(packagePrefix.length()) : className);
|
||||
final StringTokenizer tokenizer = new StringTokenizer(packageName, ".");
|
||||
while (tokenizer.hasMoreTokens()) {
|
||||
String packagePart = tokenizer.nextToken();
|
||||
PsiDirectory subdirectory = directoryRoot.findSubdirectory(packagePart);
|
||||
if (subdirectory == null) {
|
||||
directoryRoot.checkCreateSubdirectory(packagePart);
|
||||
subdirectory = directoryRoot.createSubdirectory(packagePart);
|
||||
}
|
||||
directoryRoot = subdirectory;
|
||||
}
|
||||
return directoryRoot;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static PsiDirectory getRootDirectory(PsiClass aClass) {
|
||||
return getSourceRootDirectory(aClass.getContainingFile().getContainingDirectory());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static PsiDirectory getSourceRootDirectory(PsiDirectory directory) {
|
||||
PsiManager manager = directory.getManager();
|
||||
DirectoryIndex directoryIndex = DirectoryIndex.getInstance(manager.getProject());
|
||||
DirectoryInfo info = directoryIndex.getInfoForDirectory(directory.getVirtualFile());
|
||||
if (info == null || !info.hasSourceRoot()) return null;
|
||||
return manager.findDirectory(info.getSourceRoot());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static PsiDirectory obtainDirectoryRootForPackage(final Module module, final String packageName) {
|
||||
final Project project = module.getProject();
|
||||
GlobalSearchScope scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module);
|
||||
final PsiPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(packageName);
|
||||
if (aPackage != null) {
|
||||
PsiDirectory[] directories = aPackage.getDirectories(scope);
|
||||
if (directories.length == 1) return getSourceRootDirectory(directories[0]);
|
||||
}
|
||||
|
||||
final VirtualFile[] sourceRoots = ModuleRootManager.getInstance(module).getSourceRoots();
|
||||
List<PsiDirectory> directoryList = new ArrayList<PsiDirectory>();
|
||||
for (VirtualFile sourceRoot : sourceRoots) {
|
||||
final PsiDirectory directory = PsiManager.getInstance(project).findDirectory(sourceRoot);
|
||||
directoryList.add(directory);
|
||||
}
|
||||
PsiDirectory[] sourceDirectories = directoryList.toArray(new PsiDirectory[directoryList.size()]);
|
||||
|
||||
return DirectoryChooserUtil.selectDirectory(project, sourceDirectories, null, File.separatorChar + packageName.replace('.', File.separatorChar));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static PsiDirectory getRoot(Module module, String className) {
|
||||
String aPackage = extractPackage(className);
|
||||
PsiManager psiManager = PsiManager.getInstance(module.getProject());
|
||||
PsiPackage psiPackage = JavaPsiFacade.getInstance(psiManager.getProject()).findPackage(aPackage);
|
||||
if (psiPackage == null) return null;
|
||||
PsiDirectory[] directories = psiPackage.getDirectories(GlobalSearchScope.moduleScope(module));
|
||||
if (directories.length == 0) return null;
|
||||
|
||||
return directories[0];
|
||||
}
|
||||
|
||||
public static String extractClassName(String fqName) {
|
||||
return StringUtil.getShortName(fqName);
|
||||
}
|
||||
|
||||
public static String extractPackage(String fqName) {
|
||||
int i = fqName.lastIndexOf('.');
|
||||
return i == -1 ? "" : fqName.substring(0, i);
|
||||
}
|
||||
|
||||
public static String makeFQName(String aPackage, String className) {
|
||||
String fq = aPackage;
|
||||
if (!"".equals(aPackage)) {
|
||||
fq += ".";
|
||||
}
|
||||
fq += className;
|
||||
return fq;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static PsiClass createClassNamed(String newClassName, String templateName, @NotNull PsiDirectory directory) throws IncorrectOperationException {
|
||||
return createClassNamed(newClassName, FileTemplateManager.getInstance().getDefaultProperties(directory.getProject()), templateName, directory);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static PsiClass createClassNamed(String newClassName, Map classProperties, String templateName, @NotNull PsiDirectory directory)
|
||||
throws IncorrectOperationException {
|
||||
Properties defaultProperties = FileTemplateManager.getInstance().getDefaultProperties(directory.getProject());
|
||||
Properties properties = new Properties(defaultProperties);
|
||||
properties.putAll(classProperties);
|
||||
|
||||
return createClassNamed(newClassName, properties, templateName, directory);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static PsiClass createClassNamed(@Nullable String newClassName,
|
||||
@NotNull Properties properties,
|
||||
String templateName,
|
||||
@NotNull PsiDirectory directory) throws IncorrectOperationException {
|
||||
if (newClassName == null) {
|
||||
return null;
|
||||
}
|
||||
final String className = extractClassName(newClassName);
|
||||
properties.setProperty(CLASS_NAME_PROPERTY, className);
|
||||
properties.setProperty(INTERFACE_NAME_PROPERTY, className);
|
||||
|
||||
return createClassFromTemplate(properties, templateName, directory, newClassName);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static PsiClass createClassFromCustomTemplate(@Nullable PsiDirectory classDirectory,
|
||||
@Nullable final Module module,
|
||||
final String className,
|
||||
final String templateName) {
|
||||
if (classDirectory == null && module != null) {
|
||||
try {
|
||||
classDirectory = PackageUtil.findOrCreateDirectoryForPackage(module, "", null, false);
|
||||
}
|
||||
catch (IncorrectOperationException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (classDirectory == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
final Properties properties = ApplicationManager.getApplication().isUnitTestMode() ?
|
||||
new Properties() :
|
||||
FileTemplateManager.getInstance().getDefaultProperties(classDirectory.getProject());
|
||||
return createClassNamed(className, new Properties(properties), templateName, classDirectory);
|
||||
}
|
||||
catch (IncorrectOperationException e) {
|
||||
LOG.error(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.util;
|
||||
|
||||
import com.intellij.ide.fileTemplates.FileTemplate;
|
||||
import com.intellij.ide.fileTemplates.FileTemplateManager;
|
||||
import com.intellij.ide.fileTemplates.JavaCreateFromTemplateHandler;
|
||||
import com.intellij.ide.util.DirectoryChooserUtil;
|
||||
import com.intellij.ide.util.PackageUtil;
|
||||
import com.intellij.openapi.fileTypes.StdFileTypes;
|
||||
import com.intellij.openapi.module.Module;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.roots.ModuleRootManager;
|
||||
import com.intellij.openapi.roots.impl.DirectoryIndex;
|
||||
import com.intellij.openapi.roots.impl.DirectoryInfo;
|
||||
import com.intellij.openapi.util.text.StringUtil;
|
||||
import com.intellij.openapi.vfs.VirtualFile;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.application.ApplicationManager;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
|
||||
import com.intellij.psi.search.GlobalSearchScope;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import com.intellij.util.text.StringTokenizer;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* author: lesya
|
||||
*/
|
||||
public class CreateClassUtil {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.j2ee.CreateClassUtil");
|
||||
|
||||
@NonNls public static final String DEFAULT_CLASS_TEMPLATE = "#DEFAULT_CLASS_TEMPLATE";
|
||||
@NonNls private static final String DO_NOT_CREATE_CLASS_TEMPLATE = "#DO_NOT_CREATE_CLASS_TEMPLATE";
|
||||
@NonNls private static final String CLASS_NAME_PROPERTY = "Class_Name";
|
||||
@NonNls private static final String INTERFACE_NAME_PROPERTY = "Interface_Name";
|
||||
|
||||
private CreateClassUtil() {}
|
||||
|
||||
@Nullable
|
||||
private static PsiClass createClassFromTemplate(@NotNull final Properties attributes, @Nullable final String templateName,
|
||||
@NotNull final PsiDirectory directoryRoot,
|
||||
@NotNull final String className) throws IncorrectOperationException {
|
||||
if (templateName == null) return null;
|
||||
if (templateName.equals(DO_NOT_CREATE_CLASS_TEMPLATE)) return null;
|
||||
|
||||
final Project project = directoryRoot.getProject();
|
||||
try {
|
||||
final PsiDirectory directory = createParentDirectories(directoryRoot, className);
|
||||
final PsiFile psiFile = directory.findFile(className + "." + StdFileTypes.JAVA.getDefaultExtension());
|
||||
if (psiFile != null) {
|
||||
psiFile.delete();
|
||||
}
|
||||
|
||||
final String rawClassName = extractClassName(className);
|
||||
final PsiFile existing = directory.findFile(rawClassName + ".java");
|
||||
if (existing instanceof PsiJavaFile) {
|
||||
final PsiClass[] classes = ((PsiJavaFile)existing).getClasses();
|
||||
if (classes.length > 0) {
|
||||
return classes[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
final PsiClass aClass;
|
||||
if (templateName.equals(DEFAULT_CLASS_TEMPLATE)) {
|
||||
aClass = JavaDirectoryService.getInstance().createClass(directory, rawClassName);
|
||||
}
|
||||
else {
|
||||
final FileTemplateManager fileTemplateManager = FileTemplateManager.getInstance();
|
||||
FileTemplate fileTemplate = fileTemplateManager.getJ2eeTemplate(templateName);
|
||||
LOG.assertTrue(fileTemplate != null, templateName + " not found");
|
||||
final String text = fileTemplate.getText(attributes);
|
||||
aClass = JavaCreateFromTemplateHandler.createClassOrInterface(project, directory, text, true, fileTemplate.getExtension());
|
||||
}
|
||||
return (PsiClass)JavaCodeStyleManager.getInstance(project).shortenClassReferences(aClass);
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new IncorrectOperationException(e.toString(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private static PsiDirectory createParentDirectories(@NotNull PsiDirectory directoryRoot, @NotNull String className) throws IncorrectOperationException {
|
||||
final PsiPackage currentPackage = JavaDirectoryService.getInstance().getPackage(directoryRoot);
|
||||
final String packagePrefix = currentPackage == null? null : currentPackage.getQualifiedName() + ".";
|
||||
final String packageName = extractPackage(packagePrefix != null && className.startsWith(packagePrefix)?
|
||||
className.substring(packagePrefix.length()) : className);
|
||||
final StringTokenizer tokenizer = new StringTokenizer(packageName, ".");
|
||||
while (tokenizer.hasMoreTokens()) {
|
||||
String packagePart = tokenizer.nextToken();
|
||||
PsiDirectory subdirectory = directoryRoot.findSubdirectory(packagePart);
|
||||
if (subdirectory == null) {
|
||||
directoryRoot.checkCreateSubdirectory(packagePart);
|
||||
subdirectory = directoryRoot.createSubdirectory(packagePart);
|
||||
}
|
||||
directoryRoot = subdirectory;
|
||||
}
|
||||
return directoryRoot;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static PsiDirectory getRootDirectory(PsiClass aClass) {
|
||||
return getSourceRootDirectory(aClass.getContainingFile().getContainingDirectory());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static PsiDirectory getSourceRootDirectory(PsiDirectory directory) {
|
||||
PsiManager manager = directory.getManager();
|
||||
DirectoryIndex directoryIndex = DirectoryIndex.getInstance(manager.getProject());
|
||||
DirectoryInfo info = directoryIndex.getInfoForDirectory(directory.getVirtualFile());
|
||||
if (info == null || !info.hasSourceRoot()) return null;
|
||||
return manager.findDirectory(info.getSourceRoot());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static PsiDirectory obtainDirectoryRootForPackage(final Module module, final String packageName) {
|
||||
final Project project = module.getProject();
|
||||
GlobalSearchScope scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module);
|
||||
final PsiPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(packageName);
|
||||
if (aPackage != null) {
|
||||
PsiDirectory[] directories = aPackage.getDirectories(scope);
|
||||
if (directories.length == 1) return getSourceRootDirectory(directories[0]);
|
||||
}
|
||||
|
||||
final VirtualFile[] sourceRoots = ModuleRootManager.getInstance(module).getSourceRoots();
|
||||
List<PsiDirectory> directoryList = new ArrayList<PsiDirectory>();
|
||||
for (VirtualFile sourceRoot : sourceRoots) {
|
||||
final PsiDirectory directory = PsiManager.getInstance(project).findDirectory(sourceRoot);
|
||||
directoryList.add(directory);
|
||||
}
|
||||
PsiDirectory[] sourceDirectories = directoryList.toArray(new PsiDirectory[directoryList.size()]);
|
||||
|
||||
return DirectoryChooserUtil.selectDirectory(project, sourceDirectories, null, File.separatorChar + packageName.replace('.', File.separatorChar));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static PsiDirectory getRoot(Module module, String className) {
|
||||
String aPackage = extractPackage(className);
|
||||
PsiManager psiManager = PsiManager.getInstance(module.getProject());
|
||||
PsiPackage psiPackage = JavaPsiFacade.getInstance(psiManager.getProject()).findPackage(aPackage);
|
||||
if (psiPackage == null) return null;
|
||||
PsiDirectory[] directories = psiPackage.getDirectories(GlobalSearchScope.moduleScope(module));
|
||||
if (directories.length == 0) return null;
|
||||
|
||||
return directories[0];
|
||||
}
|
||||
|
||||
public static String extractClassName(String fqName) {
|
||||
return StringUtil.getShortName(fqName);
|
||||
}
|
||||
|
||||
public static String extractPackage(String fqName) {
|
||||
int i = fqName.lastIndexOf('.');
|
||||
return i == -1 ? "" : fqName.substring(0, i);
|
||||
}
|
||||
|
||||
public static String makeFQName(String aPackage, String className) {
|
||||
String fq = aPackage;
|
||||
if (!"".equals(aPackage)) {
|
||||
fq += ".";
|
||||
}
|
||||
fq += className;
|
||||
return fq;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static PsiClass createClassNamed(String newClassName, String templateName, @NotNull PsiDirectory directory) throws IncorrectOperationException {
|
||||
return createClassNamed(newClassName, FileTemplateManager.getInstance().getDefaultProperties(directory.getProject()), templateName, directory);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static PsiClass createClassNamed(String newClassName, Map classProperties, String templateName, @NotNull PsiDirectory directory)
|
||||
throws IncorrectOperationException {
|
||||
Properties defaultProperties = FileTemplateManager.getInstance().getDefaultProperties(directory.getProject());
|
||||
Properties properties = new Properties(defaultProperties);
|
||||
properties.putAll(classProperties);
|
||||
|
||||
return createClassNamed(newClassName, properties, templateName, directory);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static PsiClass createClassNamed(@Nullable String newClassName,
|
||||
@NotNull Properties properties,
|
||||
String templateName,
|
||||
@NotNull PsiDirectory directory) throws IncorrectOperationException {
|
||||
if (newClassName == null) {
|
||||
return null;
|
||||
}
|
||||
final String className = extractClassName(newClassName);
|
||||
properties.setProperty(CLASS_NAME_PROPERTY, className);
|
||||
properties.setProperty(INTERFACE_NAME_PROPERTY, className);
|
||||
|
||||
return createClassFromTemplate(properties, templateName, directory, newClassName);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static PsiClass createClassFromCustomTemplate(@Nullable PsiDirectory classDirectory,
|
||||
@Nullable final Module module,
|
||||
final String className,
|
||||
final String templateName) {
|
||||
if (classDirectory == null && module != null) {
|
||||
try {
|
||||
classDirectory = PackageUtil.findOrCreateDirectoryForPackage(module, "", null, false);
|
||||
}
|
||||
catch (IncorrectOperationException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (classDirectory == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
final Properties properties = ApplicationManager.getApplication().isUnitTestMode() ?
|
||||
new Properties() :
|
||||
FileTemplateManager.getInstance().getDefaultProperties(classDirectory.getProject());
|
||||
return createClassNamed(className, new Properties(properties), templateName, classDirectory);
|
||||
}
|
||||
catch (IncorrectOperationException e) {
|
||||
LOG.error(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+95
-95
@@ -1,95 +1,95 @@
|
||||
/*
|
||||
* Copyright 2000-2010 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.refactoring.changeSignature;
|
||||
|
||||
import com.intellij.psi.PsiClass;
|
||||
import com.intellij.psi.PsiMethod;
|
||||
import com.intellij.psi.PsiParameter;
|
||||
import com.intellij.psi.PsiTypeElement;
|
||||
import com.intellij.util.VisibilityUtil;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class JavaMethodDescriptor implements MethodDescriptor<ParameterInfoImpl, String> {
|
||||
|
||||
private final PsiMethod myMethod;
|
||||
|
||||
public JavaMethodDescriptor(PsiMethod method) {
|
||||
myMethod = method;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return myMethod.getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ParameterInfoImpl> getParameters() {
|
||||
final ArrayList<ParameterInfoImpl> result = new ArrayList<ParameterInfoImpl>();
|
||||
final PsiParameter[] parameters = myMethod.getParameterList().getParameters();
|
||||
for (int i = 0; i < parameters.length; i++) {
|
||||
PsiParameter parameter = parameters[i];
|
||||
ParameterInfoImpl info = new ParameterInfoImpl(i, parameter.getName(), parameter.getType());
|
||||
info.defaultValue = "";
|
||||
result.add(info);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVisibility() {
|
||||
return VisibilityUtil.getVisibilityModifier(myMethod.getModifierList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiMethod getMethod() {
|
||||
return myMethod;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getParametersCount() {
|
||||
return myMethod.getParameterList().getParametersCount();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getReturnTypeText() {
|
||||
final PsiTypeElement typeElement = myMethod.getReturnTypeElement();
|
||||
return typeElement != null ? typeElement.getText() : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canChangeVisibility() {
|
||||
PsiClass containingClass = myMethod.getContainingClass();
|
||||
return containingClass != null && !containingClass.isInterface();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canChangeParameters() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ReadWriteOption canChangeReturnType() {
|
||||
return myMethod.isConstructor() ? ReadWriteOption.None : ReadWriteOption.ReadWrite;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canChangeName() {
|
||||
return !myMethod.isConstructor();
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2010 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.refactoring.changeSignature;
|
||||
|
||||
import com.intellij.psi.PsiClass;
|
||||
import com.intellij.psi.PsiMethod;
|
||||
import com.intellij.psi.PsiParameter;
|
||||
import com.intellij.psi.PsiTypeElement;
|
||||
import com.intellij.util.VisibilityUtil;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class JavaMethodDescriptor implements MethodDescriptor<ParameterInfoImpl, String> {
|
||||
|
||||
private final PsiMethod myMethod;
|
||||
|
||||
public JavaMethodDescriptor(PsiMethod method) {
|
||||
myMethod = method;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return myMethod.getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ParameterInfoImpl> getParameters() {
|
||||
final ArrayList<ParameterInfoImpl> result = new ArrayList<ParameterInfoImpl>();
|
||||
final PsiParameter[] parameters = myMethod.getParameterList().getParameters();
|
||||
for (int i = 0; i < parameters.length; i++) {
|
||||
PsiParameter parameter = parameters[i];
|
||||
ParameterInfoImpl info = new ParameterInfoImpl(i, parameter.getName(), parameter.getType());
|
||||
info.defaultValue = "";
|
||||
result.add(info);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVisibility() {
|
||||
return VisibilityUtil.getVisibilityModifier(myMethod.getModifierList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiMethod getMethod() {
|
||||
return myMethod;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getParametersCount() {
|
||||
return myMethod.getParameterList().getParametersCount();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getReturnTypeText() {
|
||||
final PsiTypeElement typeElement = myMethod.getReturnTypeElement();
|
||||
return typeElement != null ? typeElement.getText() : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canChangeVisibility() {
|
||||
PsiClass containingClass = myMethod.getContainingClass();
|
||||
return containingClass != null && !containingClass.isInterface();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canChangeParameters() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ReadWriteOption canChangeReturnType() {
|
||||
return myMethod.isConstructor() ? ReadWriteOption.None : ReadWriteOption.ReadWrite;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canChangeName() {
|
||||
return !myMethod.isConstructor();
|
||||
}
|
||||
}
|
||||
|
||||
+364
-364
@@ -1,364 +1,364 @@
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.refactoring.rename;
|
||||
|
||||
import com.intellij.ide.util.SuperMethodWarningUtil;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.util.Comparing;
|
||||
import com.intellij.openapi.util.Pass;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.search.GlobalSearchScope;
|
||||
import com.intellij.psi.search.PsiElementProcessor;
|
||||
import com.intellij.psi.search.SearchScope;
|
||||
import com.intellij.psi.search.searches.ClassInheritorsSearch;
|
||||
import com.intellij.psi.search.searches.MethodReferencesSearch;
|
||||
import com.intellij.psi.search.searches.OverridingMethodsSearch;
|
||||
import com.intellij.psi.util.MethodSignature;
|
||||
import com.intellij.psi.util.MethodSignatureUtil;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.psi.util.TypeConversionUtil;
|
||||
import com.intellij.refactoring.HelpID;
|
||||
import com.intellij.refactoring.JavaRefactoringSettings;
|
||||
import com.intellij.refactoring.RefactoringBundle;
|
||||
import com.intellij.refactoring.listeners.RefactoringElementListener;
|
||||
import com.intellij.refactoring.util.ConflictsUtil;
|
||||
import com.intellij.refactoring.util.MoveRenameUsageInfo;
|
||||
import com.intellij.refactoring.util.RefactoringUIUtil;
|
||||
import com.intellij.refactoring.util.RefactoringUtil;
|
||||
import com.intellij.usageView.UsageInfo;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import com.intellij.util.Processor;
|
||||
import com.intellij.util.containers.HashSet;
|
||||
import com.intellij.util.containers.MultiMap;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class RenameJavaMethodProcessor extends RenameJavaMemberProcessor {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.rename.RenameJavaMethodProcessor");
|
||||
|
||||
public boolean canProcessElement(@NotNull final PsiElement element) {
|
||||
return element instanceof PsiMethod;
|
||||
}
|
||||
|
||||
public void renameElement(final PsiElement psiElement,
|
||||
final String newName,
|
||||
final UsageInfo[] usages,
|
||||
@Nullable RefactoringElementListener listener) throws IncorrectOperationException {
|
||||
PsiMethod method = (PsiMethod) psiElement;
|
||||
Set<PsiMethod> methodAndOverriders = new HashSet<PsiMethod>();
|
||||
Set<PsiClass> containingClasses = new HashSet<PsiClass>();
|
||||
LinkedHashSet<PsiElement> renamedReferences = new LinkedHashSet<PsiElement>();
|
||||
List<MemberHidesOuterMemberUsageInfo> outerHides = new ArrayList<MemberHidesOuterMemberUsageInfo>();
|
||||
List<MemberHidesStaticImportUsageInfo> staticImportHides = new ArrayList<MemberHidesStaticImportUsageInfo>();
|
||||
|
||||
methodAndOverriders.add(method);
|
||||
containingClasses.add(method.getContainingClass());
|
||||
|
||||
// do actual rename of overriding/implementing methods and of references to all them
|
||||
for (UsageInfo usage : usages) {
|
||||
PsiElement element = usage.getElement();
|
||||
if (element == null) continue;
|
||||
|
||||
if (usage instanceof MemberHidesStaticImportUsageInfo) {
|
||||
staticImportHides.add((MemberHidesStaticImportUsageInfo)usage);
|
||||
} else if (usage instanceof MemberHidesOuterMemberUsageInfo) {
|
||||
PsiJavaCodeReferenceElement collidingRef = (PsiJavaCodeReferenceElement)element;
|
||||
PsiMethod resolved = (PsiMethod)collidingRef.resolve();
|
||||
outerHides.add(new MemberHidesOuterMemberUsageInfo(element, resolved));
|
||||
}
|
||||
else if (!(element instanceof PsiMethod)) {
|
||||
final PsiReference ref;
|
||||
if (usage instanceof MoveRenameUsageInfo) {
|
||||
ref = usage.getReference();
|
||||
}
|
||||
else {
|
||||
ref = element.getReference();
|
||||
}
|
||||
if (ref instanceof PsiImportStaticReferenceElement && ((PsiImportStaticReferenceElement)ref).multiResolve(false).length > 1) {
|
||||
continue;
|
||||
}
|
||||
if (ref != null) {
|
||||
PsiElement e = processRef(ref, newName);
|
||||
if (e != null) {
|
||||
renamedReferences.add(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
PsiMethod overrider = (PsiMethod)element;
|
||||
methodAndOverriders.add(overrider);
|
||||
containingClasses.add(overrider.getContainingClass());
|
||||
}
|
||||
}
|
||||
|
||||
// do actual rename of method
|
||||
method.setName(newName);
|
||||
for (UsageInfo usage : usages) {
|
||||
PsiElement element = usage.getElement();
|
||||
if (element instanceof PsiMethod) {
|
||||
((PsiMethod)element).setName(newName);
|
||||
}
|
||||
}
|
||||
if (listener != null) {
|
||||
listener.elementRenamed(method);
|
||||
}
|
||||
|
||||
for (PsiElement element: renamedReferences) {
|
||||
fixNameCollisionsWithInnerClassMethod(element, newName, methodAndOverriders, containingClasses,
|
||||
method.hasModifierProperty(PsiModifier.STATIC));
|
||||
}
|
||||
qualifyOuterMemberReferences(outerHides);
|
||||
qualifyStaticImportReferences(staticImportHides);
|
||||
}
|
||||
|
||||
/**
|
||||
* handles rename of refs
|
||||
* @param ref
|
||||
* @param newName
|
||||
* @return
|
||||
*/
|
||||
@Nullable
|
||||
protected PsiElement processRef(PsiReference ref, String newName) {
|
||||
return ref.handleElementRename(newName);
|
||||
}
|
||||
|
||||
private static void fixNameCollisionsWithInnerClassMethod(final PsiElement element, final String newName,
|
||||
final Set<PsiMethod> methodAndOverriders, final Set<PsiClass> containingClasses,
|
||||
final boolean isStatic) throws IncorrectOperationException {
|
||||
if (!(element instanceof PsiReferenceExpression)) return;
|
||||
PsiElement elem = ((PsiReferenceExpression)element).resolve();
|
||||
|
||||
if (elem instanceof PsiMethod) {
|
||||
PsiMethod actualMethod = (PsiMethod) elem;
|
||||
if (!methodAndOverriders.contains(actualMethod)) {
|
||||
PsiClass outerClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
|
||||
while (outerClass != null) {
|
||||
if (containingClasses.contains(outerClass)) {
|
||||
qualifyMember(element, newName, outerClass, isStatic);
|
||||
break;
|
||||
}
|
||||
outerClass = PsiTreeUtil.getParentOfType(outerClass, PsiClass.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Collection<PsiReference> findReferences(final PsiElement element) {
|
||||
GlobalSearchScope projectScope = GlobalSearchScope.projectScope(element.getProject());
|
||||
return MethodReferencesSearch.search((PsiMethod)element, projectScope, true).findAll();
|
||||
}
|
||||
|
||||
public void findCollisions(final PsiElement element, final String newName, final Map<? extends PsiElement, String> allRenames,
|
||||
final List<UsageInfo> result) {
|
||||
final PsiMethod methodToRename = (PsiMethod)element;
|
||||
findSubmemberHidesMemberCollisions(methodToRename, newName, result);
|
||||
findMemberHidesOuterMemberCollisions((PsiMethod) element, newName, result);
|
||||
findCollisionsAgainstNewName(methodToRename, newName, result);
|
||||
findHidingMethodWithOtherSignature(methodToRename, newName, result);
|
||||
final PsiClass containingClass = methodToRename.getContainingClass();
|
||||
if (containingClass != null) {
|
||||
final PsiMethod patternMethod = (PsiMethod)methodToRename.copy();
|
||||
try {
|
||||
patternMethod.setName(newName);
|
||||
final PsiMethod methodInBaseClass = containingClass.findMethodBySignature(patternMethod, true);
|
||||
if (methodInBaseClass != null && methodInBaseClass.getContainingClass() != containingClass) {
|
||||
if (methodInBaseClass.hasModifierProperty(PsiModifier.FINAL)) {
|
||||
result.add(new UnresolvableCollisionUsageInfo(methodInBaseClass, methodToRename) {
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return "Renaming method will override final \"" + RefactoringUIUtil.getDescription(methodInBaseClass, true) + "\"";
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (IncorrectOperationException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void findHidingMethodWithOtherSignature(final PsiMethod methodToRename, final String newName, final List<UsageInfo> result) {
|
||||
final PsiClass containingClass = methodToRename.getContainingClass();
|
||||
if (containingClass != null) {
|
||||
final PsiMethod prototype = getPrototypeWithNewName(methodToRename, newName);
|
||||
if (prototype == null || containingClass.findMethodBySignature(prototype, true) != null) return;
|
||||
|
||||
final PsiMethod[] methodsByName = containingClass.findMethodsByName(newName, true);
|
||||
if (methodsByName.length > 0) {
|
||||
|
||||
for (UsageInfo info : result) {
|
||||
final PsiElement element = info.getElement();
|
||||
if (element instanceof PsiReferenceExpression) {
|
||||
if (((PsiReferenceExpression)element).resolve() == methodToRename) {
|
||||
final PsiMethodCallExpression copy = (PsiMethodCallExpression)JavaPsiFacade.getElementFactory(element.getProject())
|
||||
.createExpressionFromText(element.getParent().getText(), element);
|
||||
final PsiReferenceExpression expression = (PsiReferenceExpression)processRef(copy.getMethodExpression(), newName);
|
||||
if (expression == null) continue;
|
||||
final JavaResolveResult resolveResult = expression.advancedResolve(true);
|
||||
final PsiMember resolveResultElement = (PsiMember)resolveResult.getElement();
|
||||
if (resolveResult.isValidResult() && resolveResultElement != null) {
|
||||
result.add(new UnresolvableCollisionUsageInfo(element, methodToRename) {
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return "Method call would be linked to \"" + RefactoringUIUtil.getDescription(resolveResultElement, true) +
|
||||
"\" after rename";
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static PsiMethod getPrototypeWithNewName(PsiMethod methodToRename, String newName) {
|
||||
final PsiMethod prototype = (PsiMethod)methodToRename.copy();
|
||||
try {
|
||||
prototype.setName(newName);
|
||||
}
|
||||
catch (IncorrectOperationException e) {
|
||||
LOG.error(e);
|
||||
return null;
|
||||
}
|
||||
return prototype;
|
||||
}
|
||||
|
||||
public void findExistingNameConflicts(final PsiElement element, final String newName, final MultiMap<PsiElement, String> conflicts) {
|
||||
if (element instanceof PsiCompiledElement) return;
|
||||
final PsiMethod refactoredMethod = (PsiMethod)element;
|
||||
if (newName.equals(refactoredMethod.getName())) return;
|
||||
final PsiMethod prototype = getPrototypeWithNewName(refactoredMethod, newName);
|
||||
if (prototype == null) return;
|
||||
|
||||
ConflictsUtil.checkMethodConflicts(
|
||||
refactoredMethod.getContainingClass(),
|
||||
refactoredMethod,
|
||||
prototype,
|
||||
conflicts);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void prepareRenaming(PsiElement element, final String newName, final Map<PsiElement, String> allRenames, SearchScope scope) {
|
||||
final PsiMethod method = (PsiMethod) element;
|
||||
OverridingMethodsSearch.search(method, scope, true).forEach(new Processor<PsiMethod>() {
|
||||
public boolean process(PsiMethod overrider) {
|
||||
final String overriderName = overrider.getName();
|
||||
final String baseName = method.getName();
|
||||
final String newOverriderName = RefactoringUtil.suggestNewOverriderName(overriderName, baseName, newName);
|
||||
if (newOverriderName != null) {
|
||||
RenameProcessor.assertNonCompileElement(overrider);
|
||||
allRenames.put(overrider, newOverriderName);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@NonNls
|
||||
public String getHelpID(final PsiElement element) {
|
||||
return HelpID.RENAME_METHOD;
|
||||
}
|
||||
|
||||
public boolean isToSearchInComments(final PsiElement psiElement) {
|
||||
return JavaRefactoringSettings.getInstance().RENAME_SEARCH_IN_COMMENTS_FOR_METHOD;
|
||||
}
|
||||
|
||||
public void setToSearchInComments(final PsiElement element, final boolean enabled) {
|
||||
JavaRefactoringSettings.getInstance().RENAME_SEARCH_IN_COMMENTS_FOR_METHOD = enabled;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public PsiElement substituteElementToRename(PsiElement element, Editor editor) {
|
||||
PsiMethod psiMethod = (PsiMethod)element;
|
||||
if (psiMethod.isConstructor()) {
|
||||
PsiClass containingClass = psiMethod.getContainingClass();
|
||||
if (containingClass == null) return null;
|
||||
if (Comparing.strEqual(psiMethod.getName(), containingClass.getName())) {
|
||||
element = containingClass;
|
||||
if (!PsiElementRenameHandler.canRename(element.getProject(), editor, element)) {
|
||||
return null;
|
||||
}
|
||||
return element;
|
||||
}
|
||||
}
|
||||
return SuperMethodWarningUtil.checkSuperMethod(psiMethod, RefactoringBundle.message("to.rename"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void substituteElementToRename(@NotNull PsiElement element,
|
||||
@NotNull final Editor editor,
|
||||
@NotNull final Pass<PsiElement> renameCallback) {
|
||||
final PsiMethod psiMethod = (PsiMethod)element;
|
||||
if (psiMethod.isConstructor()) {
|
||||
final PsiClass containingClass = psiMethod.getContainingClass();
|
||||
if (containingClass == null) return;
|
||||
if (!Comparing.strEqual(psiMethod.getName(), containingClass.getName())) {
|
||||
renameCallback.pass(psiMethod);
|
||||
return;
|
||||
}
|
||||
super.substituteElementToRename(element, editor, renameCallback);
|
||||
}
|
||||
else {
|
||||
SuperMethodWarningUtil.checkSuperMethod(psiMethod, "Rename", new PsiElementProcessor<PsiMethod>() {
|
||||
@Override
|
||||
public boolean execute(@NotNull PsiMethod method) {
|
||||
if (!PsiElementRenameHandler.canRename(method.getProject(), editor, method)) return false;
|
||||
renameCallback.pass(method);
|
||||
return false;
|
||||
}
|
||||
}, editor);
|
||||
}
|
||||
}
|
||||
|
||||
private static void findSubmemberHidesMemberCollisions(final PsiMethod method, final String newName, final List<UsageInfo> result) {
|
||||
final PsiClass containingClass = method.getContainingClass();
|
||||
if (containingClass == null) return;
|
||||
if (method.hasModifierProperty(PsiModifier.PRIVATE)) return;
|
||||
Collection<PsiClass> inheritors = ClassInheritorsSearch.search(containingClass, true).findAll();
|
||||
|
||||
MethodSignature oldSignature = method.getSignature(PsiSubstitutor.EMPTY);
|
||||
MethodSignature newSignature = MethodSignatureUtil.createMethodSignature(newName, oldSignature.getParameterTypes(),
|
||||
oldSignature.getTypeParameters(),
|
||||
oldSignature.getSubstitutor(),
|
||||
method.isConstructor());
|
||||
for (PsiClass inheritor : inheritors) {
|
||||
PsiSubstitutor superSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(containingClass, inheritor, PsiSubstitutor.EMPTY);
|
||||
final PsiMethod[] methodsByName = inheritor.findMethodsByName(newName, false);
|
||||
for (PsiMethod conflictingMethod : methodsByName) {
|
||||
if (newSignature.equals(conflictingMethod.getSignature(superSubstitutor))) {
|
||||
result.add(new SubmemberHidesMemberUsageInfo(conflictingMethod, method));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isToSearchForTextOccurrences(final PsiElement element) {
|
||||
return JavaRefactoringSettings.getInstance().RENAME_SEARCH_FOR_TEXT_FOR_METHOD;
|
||||
}
|
||||
|
||||
public void setToSearchForTextOccurrences(final PsiElement element, final boolean enabled) {
|
||||
JavaRefactoringSettings.getInstance().RENAME_SEARCH_FOR_TEXT_FOR_METHOD = enabled;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.refactoring.rename;
|
||||
|
||||
import com.intellij.ide.util.SuperMethodWarningUtil;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.util.Comparing;
|
||||
import com.intellij.openapi.util.Pass;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.search.GlobalSearchScope;
|
||||
import com.intellij.psi.search.PsiElementProcessor;
|
||||
import com.intellij.psi.search.SearchScope;
|
||||
import com.intellij.psi.search.searches.ClassInheritorsSearch;
|
||||
import com.intellij.psi.search.searches.MethodReferencesSearch;
|
||||
import com.intellij.psi.search.searches.OverridingMethodsSearch;
|
||||
import com.intellij.psi.util.MethodSignature;
|
||||
import com.intellij.psi.util.MethodSignatureUtil;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.psi.util.TypeConversionUtil;
|
||||
import com.intellij.refactoring.HelpID;
|
||||
import com.intellij.refactoring.JavaRefactoringSettings;
|
||||
import com.intellij.refactoring.RefactoringBundle;
|
||||
import com.intellij.refactoring.listeners.RefactoringElementListener;
|
||||
import com.intellij.refactoring.util.ConflictsUtil;
|
||||
import com.intellij.refactoring.util.MoveRenameUsageInfo;
|
||||
import com.intellij.refactoring.util.RefactoringUIUtil;
|
||||
import com.intellij.refactoring.util.RefactoringUtil;
|
||||
import com.intellij.usageView.UsageInfo;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import com.intellij.util.Processor;
|
||||
import com.intellij.util.containers.HashSet;
|
||||
import com.intellij.util.containers.MultiMap;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class RenameJavaMethodProcessor extends RenameJavaMemberProcessor {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.rename.RenameJavaMethodProcessor");
|
||||
|
||||
public boolean canProcessElement(@NotNull final PsiElement element) {
|
||||
return element instanceof PsiMethod;
|
||||
}
|
||||
|
||||
public void renameElement(final PsiElement psiElement,
|
||||
final String newName,
|
||||
final UsageInfo[] usages,
|
||||
@Nullable RefactoringElementListener listener) throws IncorrectOperationException {
|
||||
PsiMethod method = (PsiMethod) psiElement;
|
||||
Set<PsiMethod> methodAndOverriders = new HashSet<PsiMethod>();
|
||||
Set<PsiClass> containingClasses = new HashSet<PsiClass>();
|
||||
LinkedHashSet<PsiElement> renamedReferences = new LinkedHashSet<PsiElement>();
|
||||
List<MemberHidesOuterMemberUsageInfo> outerHides = new ArrayList<MemberHidesOuterMemberUsageInfo>();
|
||||
List<MemberHidesStaticImportUsageInfo> staticImportHides = new ArrayList<MemberHidesStaticImportUsageInfo>();
|
||||
|
||||
methodAndOverriders.add(method);
|
||||
containingClasses.add(method.getContainingClass());
|
||||
|
||||
// do actual rename of overriding/implementing methods and of references to all them
|
||||
for (UsageInfo usage : usages) {
|
||||
PsiElement element = usage.getElement();
|
||||
if (element == null) continue;
|
||||
|
||||
if (usage instanceof MemberHidesStaticImportUsageInfo) {
|
||||
staticImportHides.add((MemberHidesStaticImportUsageInfo)usage);
|
||||
} else if (usage instanceof MemberHidesOuterMemberUsageInfo) {
|
||||
PsiJavaCodeReferenceElement collidingRef = (PsiJavaCodeReferenceElement)element;
|
||||
PsiMethod resolved = (PsiMethod)collidingRef.resolve();
|
||||
outerHides.add(new MemberHidesOuterMemberUsageInfo(element, resolved));
|
||||
}
|
||||
else if (!(element instanceof PsiMethod)) {
|
||||
final PsiReference ref;
|
||||
if (usage instanceof MoveRenameUsageInfo) {
|
||||
ref = usage.getReference();
|
||||
}
|
||||
else {
|
||||
ref = element.getReference();
|
||||
}
|
||||
if (ref instanceof PsiImportStaticReferenceElement && ((PsiImportStaticReferenceElement)ref).multiResolve(false).length > 1) {
|
||||
continue;
|
||||
}
|
||||
if (ref != null) {
|
||||
PsiElement e = processRef(ref, newName);
|
||||
if (e != null) {
|
||||
renamedReferences.add(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
PsiMethod overrider = (PsiMethod)element;
|
||||
methodAndOverriders.add(overrider);
|
||||
containingClasses.add(overrider.getContainingClass());
|
||||
}
|
||||
}
|
||||
|
||||
// do actual rename of method
|
||||
method.setName(newName);
|
||||
for (UsageInfo usage : usages) {
|
||||
PsiElement element = usage.getElement();
|
||||
if (element instanceof PsiMethod) {
|
||||
((PsiMethod)element).setName(newName);
|
||||
}
|
||||
}
|
||||
if (listener != null) {
|
||||
listener.elementRenamed(method);
|
||||
}
|
||||
|
||||
for (PsiElement element: renamedReferences) {
|
||||
fixNameCollisionsWithInnerClassMethod(element, newName, methodAndOverriders, containingClasses,
|
||||
method.hasModifierProperty(PsiModifier.STATIC));
|
||||
}
|
||||
qualifyOuterMemberReferences(outerHides);
|
||||
qualifyStaticImportReferences(staticImportHides);
|
||||
}
|
||||
|
||||
/**
|
||||
* handles rename of refs
|
||||
* @param ref
|
||||
* @param newName
|
||||
* @return
|
||||
*/
|
||||
@Nullable
|
||||
protected PsiElement processRef(PsiReference ref, String newName) {
|
||||
return ref.handleElementRename(newName);
|
||||
}
|
||||
|
||||
private static void fixNameCollisionsWithInnerClassMethod(final PsiElement element, final String newName,
|
||||
final Set<PsiMethod> methodAndOverriders, final Set<PsiClass> containingClasses,
|
||||
final boolean isStatic) throws IncorrectOperationException {
|
||||
if (!(element instanceof PsiReferenceExpression)) return;
|
||||
PsiElement elem = ((PsiReferenceExpression)element).resolve();
|
||||
|
||||
if (elem instanceof PsiMethod) {
|
||||
PsiMethod actualMethod = (PsiMethod) elem;
|
||||
if (!methodAndOverriders.contains(actualMethod)) {
|
||||
PsiClass outerClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
|
||||
while (outerClass != null) {
|
||||
if (containingClasses.contains(outerClass)) {
|
||||
qualifyMember(element, newName, outerClass, isStatic);
|
||||
break;
|
||||
}
|
||||
outerClass = PsiTreeUtil.getParentOfType(outerClass, PsiClass.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Collection<PsiReference> findReferences(final PsiElement element) {
|
||||
GlobalSearchScope projectScope = GlobalSearchScope.projectScope(element.getProject());
|
||||
return MethodReferencesSearch.search((PsiMethod)element, projectScope, true).findAll();
|
||||
}
|
||||
|
||||
public void findCollisions(final PsiElement element, final String newName, final Map<? extends PsiElement, String> allRenames,
|
||||
final List<UsageInfo> result) {
|
||||
final PsiMethod methodToRename = (PsiMethod)element;
|
||||
findSubmemberHidesMemberCollisions(methodToRename, newName, result);
|
||||
findMemberHidesOuterMemberCollisions((PsiMethod) element, newName, result);
|
||||
findCollisionsAgainstNewName(methodToRename, newName, result);
|
||||
findHidingMethodWithOtherSignature(methodToRename, newName, result);
|
||||
final PsiClass containingClass = methodToRename.getContainingClass();
|
||||
if (containingClass != null) {
|
||||
final PsiMethod patternMethod = (PsiMethod)methodToRename.copy();
|
||||
try {
|
||||
patternMethod.setName(newName);
|
||||
final PsiMethod methodInBaseClass = containingClass.findMethodBySignature(patternMethod, true);
|
||||
if (methodInBaseClass != null && methodInBaseClass.getContainingClass() != containingClass) {
|
||||
if (methodInBaseClass.hasModifierProperty(PsiModifier.FINAL)) {
|
||||
result.add(new UnresolvableCollisionUsageInfo(methodInBaseClass, methodToRename) {
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return "Renaming method will override final \"" + RefactoringUIUtil.getDescription(methodInBaseClass, true) + "\"";
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (IncorrectOperationException e) {
|
||||
LOG.error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void findHidingMethodWithOtherSignature(final PsiMethod methodToRename, final String newName, final List<UsageInfo> result) {
|
||||
final PsiClass containingClass = methodToRename.getContainingClass();
|
||||
if (containingClass != null) {
|
||||
final PsiMethod prototype = getPrototypeWithNewName(methodToRename, newName);
|
||||
if (prototype == null || containingClass.findMethodBySignature(prototype, true) != null) return;
|
||||
|
||||
final PsiMethod[] methodsByName = containingClass.findMethodsByName(newName, true);
|
||||
if (methodsByName.length > 0) {
|
||||
|
||||
for (UsageInfo info : result) {
|
||||
final PsiElement element = info.getElement();
|
||||
if (element instanceof PsiReferenceExpression) {
|
||||
if (((PsiReferenceExpression)element).resolve() == methodToRename) {
|
||||
final PsiMethodCallExpression copy = (PsiMethodCallExpression)JavaPsiFacade.getElementFactory(element.getProject())
|
||||
.createExpressionFromText(element.getParent().getText(), element);
|
||||
final PsiReferenceExpression expression = (PsiReferenceExpression)processRef(copy.getMethodExpression(), newName);
|
||||
if (expression == null) continue;
|
||||
final JavaResolveResult resolveResult = expression.advancedResolve(true);
|
||||
final PsiMember resolveResultElement = (PsiMember)resolveResult.getElement();
|
||||
if (resolveResult.isValidResult() && resolveResultElement != null) {
|
||||
result.add(new UnresolvableCollisionUsageInfo(element, methodToRename) {
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return "Method call would be linked to \"" + RefactoringUIUtil.getDescription(resolveResultElement, true) +
|
||||
"\" after rename";
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static PsiMethod getPrototypeWithNewName(PsiMethod methodToRename, String newName) {
|
||||
final PsiMethod prototype = (PsiMethod)methodToRename.copy();
|
||||
try {
|
||||
prototype.setName(newName);
|
||||
}
|
||||
catch (IncorrectOperationException e) {
|
||||
LOG.error(e);
|
||||
return null;
|
||||
}
|
||||
return prototype;
|
||||
}
|
||||
|
||||
public void findExistingNameConflicts(final PsiElement element, final String newName, final MultiMap<PsiElement, String> conflicts) {
|
||||
if (element instanceof PsiCompiledElement) return;
|
||||
final PsiMethod refactoredMethod = (PsiMethod)element;
|
||||
if (newName.equals(refactoredMethod.getName())) return;
|
||||
final PsiMethod prototype = getPrototypeWithNewName(refactoredMethod, newName);
|
||||
if (prototype == null) return;
|
||||
|
||||
ConflictsUtil.checkMethodConflicts(
|
||||
refactoredMethod.getContainingClass(),
|
||||
refactoredMethod,
|
||||
prototype,
|
||||
conflicts);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void prepareRenaming(PsiElement element, final String newName, final Map<PsiElement, String> allRenames, SearchScope scope) {
|
||||
final PsiMethod method = (PsiMethod) element;
|
||||
OverridingMethodsSearch.search(method, scope, true).forEach(new Processor<PsiMethod>() {
|
||||
public boolean process(PsiMethod overrider) {
|
||||
final String overriderName = overrider.getName();
|
||||
final String baseName = method.getName();
|
||||
final String newOverriderName = RefactoringUtil.suggestNewOverriderName(overriderName, baseName, newName);
|
||||
if (newOverriderName != null) {
|
||||
RenameProcessor.assertNonCompileElement(overrider);
|
||||
allRenames.put(overrider, newOverriderName);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@NonNls
|
||||
public String getHelpID(final PsiElement element) {
|
||||
return HelpID.RENAME_METHOD;
|
||||
}
|
||||
|
||||
public boolean isToSearchInComments(final PsiElement psiElement) {
|
||||
return JavaRefactoringSettings.getInstance().RENAME_SEARCH_IN_COMMENTS_FOR_METHOD;
|
||||
}
|
||||
|
||||
public void setToSearchInComments(final PsiElement element, final boolean enabled) {
|
||||
JavaRefactoringSettings.getInstance().RENAME_SEARCH_IN_COMMENTS_FOR_METHOD = enabled;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public PsiElement substituteElementToRename(PsiElement element, Editor editor) {
|
||||
PsiMethod psiMethod = (PsiMethod)element;
|
||||
if (psiMethod.isConstructor()) {
|
||||
PsiClass containingClass = psiMethod.getContainingClass();
|
||||
if (containingClass == null) return null;
|
||||
if (Comparing.strEqual(psiMethod.getName(), containingClass.getName())) {
|
||||
element = containingClass;
|
||||
if (!PsiElementRenameHandler.canRename(element.getProject(), editor, element)) {
|
||||
return null;
|
||||
}
|
||||
return element;
|
||||
}
|
||||
}
|
||||
return SuperMethodWarningUtil.checkSuperMethod(psiMethod, RefactoringBundle.message("to.rename"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void substituteElementToRename(@NotNull PsiElement element,
|
||||
@NotNull final Editor editor,
|
||||
@NotNull final Pass<PsiElement> renameCallback) {
|
||||
final PsiMethod psiMethod = (PsiMethod)element;
|
||||
if (psiMethod.isConstructor()) {
|
||||
final PsiClass containingClass = psiMethod.getContainingClass();
|
||||
if (containingClass == null) return;
|
||||
if (!Comparing.strEqual(psiMethod.getName(), containingClass.getName())) {
|
||||
renameCallback.pass(psiMethod);
|
||||
return;
|
||||
}
|
||||
super.substituteElementToRename(element, editor, renameCallback);
|
||||
}
|
||||
else {
|
||||
SuperMethodWarningUtil.checkSuperMethod(psiMethod, "Rename", new PsiElementProcessor<PsiMethod>() {
|
||||
@Override
|
||||
public boolean execute(@NotNull PsiMethod method) {
|
||||
if (!PsiElementRenameHandler.canRename(method.getProject(), editor, method)) return false;
|
||||
renameCallback.pass(method);
|
||||
return false;
|
||||
}
|
||||
}, editor);
|
||||
}
|
||||
}
|
||||
|
||||
private static void findSubmemberHidesMemberCollisions(final PsiMethod method, final String newName, final List<UsageInfo> result) {
|
||||
final PsiClass containingClass = method.getContainingClass();
|
||||
if (containingClass == null) return;
|
||||
if (method.hasModifierProperty(PsiModifier.PRIVATE)) return;
|
||||
Collection<PsiClass> inheritors = ClassInheritorsSearch.search(containingClass, true).findAll();
|
||||
|
||||
MethodSignature oldSignature = method.getSignature(PsiSubstitutor.EMPTY);
|
||||
MethodSignature newSignature = MethodSignatureUtil.createMethodSignature(newName, oldSignature.getParameterTypes(),
|
||||
oldSignature.getTypeParameters(),
|
||||
oldSignature.getSubstitutor(),
|
||||
method.isConstructor());
|
||||
for (PsiClass inheritor : inheritors) {
|
||||
PsiSubstitutor superSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(containingClass, inheritor, PsiSubstitutor.EMPTY);
|
||||
final PsiMethod[] methodsByName = inheritor.findMethodsByName(newName, false);
|
||||
for (PsiMethod conflictingMethod : methodsByName) {
|
||||
if (newSignature.equals(conflictingMethod.getSignature(superSubstitutor))) {
|
||||
result.add(new SubmemberHidesMemberUsageInfo(conflictingMethod, method));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isToSearchForTextOccurrences(final PsiElement element) {
|
||||
return JavaRefactoringSettings.getInstance().RENAME_SEARCH_FOR_TEXT_FOR_METHOD;
|
||||
}
|
||||
|
||||
public void setToSearchForTextOccurrences(final PsiElement element, final boolean enabled) {
|
||||
JavaRefactoringSettings.getInstance().RENAME_SEARCH_FOR_TEXT_FOR_METHOD = enabled;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,38 +1,38 @@
|
||||
/*
|
||||
* Copyright 2000-2011 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.refactoring.ui;
|
||||
|
||||
import com.intellij.psi.PsiModifier;
|
||||
|
||||
import static com.intellij.util.VisibilityUtil.toPresentableText;
|
||||
|
||||
/**
|
||||
* @author Konstantin Bulenkov
|
||||
*/
|
||||
public class JavaComboBoxVisibilityPanel extends ComboBoxVisibilityPanel<String> implements PsiModifier {
|
||||
private static final String[] MODIFIERS = {PRIVATE, PACKAGE_LOCAL, PROTECTED, PUBLIC};
|
||||
|
||||
private static final String[] PRESENTABLE_NAMES = {
|
||||
toPresentableText(PRIVATE),
|
||||
toPresentableText(PACKAGE_LOCAL),
|
||||
toPresentableText(PROTECTED),
|
||||
toPresentableText(PUBLIC)
|
||||
};
|
||||
|
||||
public JavaComboBoxVisibilityPanel() {
|
||||
super(MODIFIERS, PRESENTABLE_NAMES);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2011 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.refactoring.ui;
|
||||
|
||||
import com.intellij.psi.PsiModifier;
|
||||
|
||||
import static com.intellij.util.VisibilityUtil.toPresentableText;
|
||||
|
||||
/**
|
||||
* @author Konstantin Bulenkov
|
||||
*/
|
||||
public class JavaComboBoxVisibilityPanel extends ComboBoxVisibilityPanel<String> implements PsiModifier {
|
||||
private static final String[] MODIFIERS = {PRIVATE, PACKAGE_LOCAL, PROTECTED, PUBLIC};
|
||||
|
||||
private static final String[] PRESENTABLE_NAMES = {
|
||||
toPresentableText(PRIVATE),
|
||||
toPresentableText(PACKAGE_LOCAL),
|
||||
toPresentableText(PROTECTED),
|
||||
toPresentableText(PUBLIC)
|
||||
};
|
||||
|
||||
public JavaComboBoxVisibilityPanel() {
|
||||
super(MODIFIERS, PRESENTABLE_NAMES);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,167 +1,167 @@
|
||||
/*
|
||||
* Copyright 2000-2009 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Created by IntelliJ IDEA.
|
||||
* User: dsl
|
||||
* Date: 07.06.2002
|
||||
* Time: 18:16:19
|
||||
* To change template for new class use
|
||||
* Code Style | Class Templates options (Tools | IDE Options).
|
||||
*/
|
||||
package com.intellij.refactoring.ui;
|
||||
|
||||
import com.intellij.psi.PsiModifier;
|
||||
import com.intellij.refactoring.RefactoringBundle;
|
||||
import com.intellij.ui.IdeBorderFactory;
|
||||
import com.intellij.util.VisibilityUtil;
|
||||
import com.intellij.util.ui.UIUtil;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.event.ChangeEvent;
|
||||
import java.awt.*;
|
||||
import java.awt.event.ItemEvent;
|
||||
import java.awt.event.ItemListener;
|
||||
|
||||
public class JavaVisibilityPanel extends VisibilityPanelBase<String> {
|
||||
private JRadioButton myRbAsIs;
|
||||
private JRadioButton myRbEscalate;
|
||||
private final JRadioButton myRbPrivate;
|
||||
private final JRadioButton myRbProtected;
|
||||
private final JRadioButton myRbPackageLocal;
|
||||
private final JRadioButton myRbPublic;
|
||||
|
||||
public JavaVisibilityPanel(boolean hasAsIs, final boolean hasEscalate) {
|
||||
setBorder(IdeBorderFactory.createTitledBorder(RefactoringBundle.message("visibility.border.title"), true,
|
||||
new Insets(IdeBorderFactory.TITLED_BORDER_TOP_INSET,
|
||||
UIUtil.DEFAULT_HGAP,
|
||||
IdeBorderFactory.TITLED_BORDER_BOTTOM_INSET,
|
||||
IdeBorderFactory.TITLED_BORDER_RIGHT_INSET)));
|
||||
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
|
||||
ButtonGroup bg = new ButtonGroup();
|
||||
|
||||
ItemListener listener = new ItemListener() {
|
||||
public void itemStateChanged(ItemEvent e) {
|
||||
if (e.getStateChange() == ItemEvent.SELECTED) {
|
||||
myEventDispatcher.getMulticaster().stateChanged(new ChangeEvent(this));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (hasEscalate) {
|
||||
myRbEscalate = new JRadioButton();
|
||||
myRbEscalate.setText(RefactoringBundle.getEscalateVisibility());
|
||||
myRbEscalate.addItemListener(listener);
|
||||
add(myRbEscalate);
|
||||
bg.add(myRbEscalate);
|
||||
}
|
||||
|
||||
if (hasAsIs) {
|
||||
myRbAsIs = new JRadioButton();
|
||||
myRbAsIs.setText(RefactoringBundle.getVisibilityAsIs());
|
||||
myRbAsIs.addItemListener(listener);
|
||||
add(myRbAsIs);
|
||||
bg.add(myRbAsIs);
|
||||
}
|
||||
|
||||
|
||||
myRbPrivate = new JRadioButton();
|
||||
myRbPrivate.setText(RefactoringBundle.getVisibilityPrivate());
|
||||
myRbPrivate.addItemListener(listener);
|
||||
myRbPrivate.setFocusable(false);
|
||||
add(myRbPrivate);
|
||||
bg.add(myRbPrivate);
|
||||
|
||||
myRbPackageLocal = new JRadioButton();
|
||||
myRbPackageLocal.setText(RefactoringBundle.getVisibilityPackageLocal());
|
||||
myRbPackageLocal.addItemListener(listener);
|
||||
myRbPackageLocal.setFocusable(false);
|
||||
add(myRbPackageLocal);
|
||||
bg.add(myRbPackageLocal);
|
||||
|
||||
myRbProtected = new JRadioButton();
|
||||
myRbProtected.setText(RefactoringBundle.getVisibilityProtected());
|
||||
myRbProtected.addItemListener(listener);
|
||||
myRbProtected.setFocusable(false);
|
||||
add(myRbProtected);
|
||||
bg.add(myRbProtected);
|
||||
|
||||
myRbPublic = new JRadioButton();
|
||||
myRbPublic.setText(RefactoringBundle.getVisibilityPublic());
|
||||
myRbPublic.addItemListener(listener);
|
||||
myRbPublic.setFocusable(false);
|
||||
add(myRbPublic);
|
||||
bg.add(myRbPublic);
|
||||
}
|
||||
|
||||
|
||||
@Nullable
|
||||
public String getVisibility() {
|
||||
if (myRbPublic.isSelected()) {
|
||||
return PsiModifier.PUBLIC;
|
||||
}
|
||||
if (myRbPackageLocal.isSelected()) {
|
||||
return PsiModifier.PACKAGE_LOCAL;
|
||||
}
|
||||
if (myRbProtected.isSelected()) {
|
||||
return PsiModifier.PROTECTED;
|
||||
}
|
||||
if (myRbPrivate.isSelected()) {
|
||||
return PsiModifier.PRIVATE;
|
||||
}
|
||||
if (myRbEscalate != null && myRbEscalate.isSelected()) {
|
||||
return VisibilityUtil.ESCALATE_VISIBILITY;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public void setVisibility(@Nullable String visibility) {
|
||||
if (PsiModifier.PUBLIC.equals(visibility)) {
|
||||
myRbPublic.setSelected(true);
|
||||
}
|
||||
else if (PsiModifier.PROTECTED.equals(visibility)) {
|
||||
myRbProtected.setSelected(true);
|
||||
}
|
||||
else if (PsiModifier.PACKAGE_LOCAL.equals(visibility)) {
|
||||
myRbPackageLocal.setSelected(true);
|
||||
}
|
||||
else if (PsiModifier.PRIVATE.equals(visibility)) {
|
||||
myRbPrivate.setSelected(true);
|
||||
}
|
||||
else if (myRbEscalate != null) {
|
||||
myRbEscalate.setSelected(true);
|
||||
}
|
||||
else if (myRbAsIs != null) {
|
||||
myRbAsIs.setSelected(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void disableAllButPublic() {
|
||||
myRbPrivate.setEnabled(false);
|
||||
myRbProtected.setEnabled(false);
|
||||
myRbPackageLocal.setEnabled(false);
|
||||
if (myRbEscalate != null) {
|
||||
myRbEscalate.setEnabled(false);
|
||||
}
|
||||
if (myRbAsIs != null) {
|
||||
myRbAsIs.setEnabled(false);
|
||||
}
|
||||
myRbPublic.setEnabled(true);
|
||||
myRbPublic.setSelected(true);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Created by IntelliJ IDEA.
|
||||
* User: dsl
|
||||
* Date: 07.06.2002
|
||||
* Time: 18:16:19
|
||||
* To change template for new class use
|
||||
* Code Style | Class Templates options (Tools | IDE Options).
|
||||
*/
|
||||
package com.intellij.refactoring.ui;
|
||||
|
||||
import com.intellij.psi.PsiModifier;
|
||||
import com.intellij.refactoring.RefactoringBundle;
|
||||
import com.intellij.ui.IdeBorderFactory;
|
||||
import com.intellij.util.VisibilityUtil;
|
||||
import com.intellij.util.ui.UIUtil;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.event.ChangeEvent;
|
||||
import java.awt.*;
|
||||
import java.awt.event.ItemEvent;
|
||||
import java.awt.event.ItemListener;
|
||||
|
||||
public class JavaVisibilityPanel extends VisibilityPanelBase<String> {
|
||||
private JRadioButton myRbAsIs;
|
||||
private JRadioButton myRbEscalate;
|
||||
private final JRadioButton myRbPrivate;
|
||||
private final JRadioButton myRbProtected;
|
||||
private final JRadioButton myRbPackageLocal;
|
||||
private final JRadioButton myRbPublic;
|
||||
|
||||
public JavaVisibilityPanel(boolean hasAsIs, final boolean hasEscalate) {
|
||||
setBorder(IdeBorderFactory.createTitledBorder(RefactoringBundle.message("visibility.border.title"), true,
|
||||
new Insets(IdeBorderFactory.TITLED_BORDER_TOP_INSET,
|
||||
UIUtil.DEFAULT_HGAP,
|
||||
IdeBorderFactory.TITLED_BORDER_BOTTOM_INSET,
|
||||
IdeBorderFactory.TITLED_BORDER_RIGHT_INSET)));
|
||||
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
|
||||
ButtonGroup bg = new ButtonGroup();
|
||||
|
||||
ItemListener listener = new ItemListener() {
|
||||
public void itemStateChanged(ItemEvent e) {
|
||||
if (e.getStateChange() == ItemEvent.SELECTED) {
|
||||
myEventDispatcher.getMulticaster().stateChanged(new ChangeEvent(this));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (hasEscalate) {
|
||||
myRbEscalate = new JRadioButton();
|
||||
myRbEscalate.setText(RefactoringBundle.getEscalateVisibility());
|
||||
myRbEscalate.addItemListener(listener);
|
||||
add(myRbEscalate);
|
||||
bg.add(myRbEscalate);
|
||||
}
|
||||
|
||||
if (hasAsIs) {
|
||||
myRbAsIs = new JRadioButton();
|
||||
myRbAsIs.setText(RefactoringBundle.getVisibilityAsIs());
|
||||
myRbAsIs.addItemListener(listener);
|
||||
add(myRbAsIs);
|
||||
bg.add(myRbAsIs);
|
||||
}
|
||||
|
||||
|
||||
myRbPrivate = new JRadioButton();
|
||||
myRbPrivate.setText(RefactoringBundle.getVisibilityPrivate());
|
||||
myRbPrivate.addItemListener(listener);
|
||||
myRbPrivate.setFocusable(false);
|
||||
add(myRbPrivate);
|
||||
bg.add(myRbPrivate);
|
||||
|
||||
myRbPackageLocal = new JRadioButton();
|
||||
myRbPackageLocal.setText(RefactoringBundle.getVisibilityPackageLocal());
|
||||
myRbPackageLocal.addItemListener(listener);
|
||||
myRbPackageLocal.setFocusable(false);
|
||||
add(myRbPackageLocal);
|
||||
bg.add(myRbPackageLocal);
|
||||
|
||||
myRbProtected = new JRadioButton();
|
||||
myRbProtected.setText(RefactoringBundle.getVisibilityProtected());
|
||||
myRbProtected.addItemListener(listener);
|
||||
myRbProtected.setFocusable(false);
|
||||
add(myRbProtected);
|
||||
bg.add(myRbProtected);
|
||||
|
||||
myRbPublic = new JRadioButton();
|
||||
myRbPublic.setText(RefactoringBundle.getVisibilityPublic());
|
||||
myRbPublic.addItemListener(listener);
|
||||
myRbPublic.setFocusable(false);
|
||||
add(myRbPublic);
|
||||
bg.add(myRbPublic);
|
||||
}
|
||||
|
||||
|
||||
@Nullable
|
||||
public String getVisibility() {
|
||||
if (myRbPublic.isSelected()) {
|
||||
return PsiModifier.PUBLIC;
|
||||
}
|
||||
if (myRbPackageLocal.isSelected()) {
|
||||
return PsiModifier.PACKAGE_LOCAL;
|
||||
}
|
||||
if (myRbProtected.isSelected()) {
|
||||
return PsiModifier.PROTECTED;
|
||||
}
|
||||
if (myRbPrivate.isSelected()) {
|
||||
return PsiModifier.PRIVATE;
|
||||
}
|
||||
if (myRbEscalate != null && myRbEscalate.isSelected()) {
|
||||
return VisibilityUtil.ESCALATE_VISIBILITY;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public void setVisibility(@Nullable String visibility) {
|
||||
if (PsiModifier.PUBLIC.equals(visibility)) {
|
||||
myRbPublic.setSelected(true);
|
||||
}
|
||||
else if (PsiModifier.PROTECTED.equals(visibility)) {
|
||||
myRbProtected.setSelected(true);
|
||||
}
|
||||
else if (PsiModifier.PACKAGE_LOCAL.equals(visibility)) {
|
||||
myRbPackageLocal.setSelected(true);
|
||||
}
|
||||
else if (PsiModifier.PRIVATE.equals(visibility)) {
|
||||
myRbPrivate.setSelected(true);
|
||||
}
|
||||
else if (myRbEscalate != null) {
|
||||
myRbEscalate.setSelected(true);
|
||||
}
|
||||
else if (myRbAsIs != null) {
|
||||
myRbAsIs.setSelected(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void disableAllButPublic() {
|
||||
myRbPrivate.setEnabled(false);
|
||||
myRbProtected.setEnabled(false);
|
||||
myRbPackageLocal.setEnabled(false);
|
||||
if (myRbEscalate != null) {
|
||||
myRbEscalate.setEnabled(false);
|
||||
}
|
||||
if (myRbAsIs != null) {
|
||||
myRbAsIs.setEnabled(false);
|
||||
}
|
||||
myRbPublic.setEnabled(true);
|
||||
myRbPublic.setSelected(true);
|
||||
}
|
||||
}
|
||||
|
||||
+97
-97
@@ -1,97 +1,97 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.search.searches;
|
||||
|
||||
import com.intellij.openapi.application.ApplicationManager;
|
||||
import com.intellij.openapi.extensions.ExtensionPointName;
|
||||
import com.intellij.openapi.util.Computable;
|
||||
import com.intellij.psi.PsiAnonymousClass;
|
||||
import com.intellij.psi.PsiClass;
|
||||
import com.intellij.psi.PsiMethod;
|
||||
import com.intellij.psi.PsiModifier;
|
||||
import com.intellij.psi.search.SearchScope;
|
||||
import com.intellij.util.EmptyQuery;
|
||||
import com.intellij.util.Query;
|
||||
import com.intellij.util.QueryExecutor;
|
||||
|
||||
/**
|
||||
* @author max
|
||||
*/
|
||||
public class OverridingMethodsSearch extends ExtensibleQueryFactory<PsiMethod, OverridingMethodsSearch.SearchParameters> {
|
||||
public static ExtensionPointName<QueryExecutor> EP_NAME = ExtensionPointName.create("com.intellij.overridingMethodsSearch");
|
||||
public static final OverridingMethodsSearch INSTANCE = new OverridingMethodsSearch();
|
||||
|
||||
public static class SearchParameters {
|
||||
private final PsiMethod myMethod;
|
||||
private final SearchScope myScope;
|
||||
private final boolean myCheckDeep;
|
||||
|
||||
public SearchParameters(final PsiMethod aClass, SearchScope scope, final boolean checkDeep) {
|
||||
myMethod = aClass;
|
||||
myScope = scope;
|
||||
myCheckDeep = checkDeep;
|
||||
}
|
||||
|
||||
public PsiMethod getMethod() {
|
||||
return myMethod;
|
||||
}
|
||||
|
||||
public boolean isCheckDeep() {
|
||||
return myCheckDeep;
|
||||
}
|
||||
|
||||
public SearchScope getScope() {
|
||||
return myScope;
|
||||
}
|
||||
}
|
||||
|
||||
private OverridingMethodsSearch() {
|
||||
}
|
||||
|
||||
public static Query<PsiMethod> search(final PsiMethod method, SearchScope scope, final boolean checkDeep) {
|
||||
if (ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
|
||||
@Override
|
||||
public Boolean compute() {
|
||||
return cannotBeOverriden(method);
|
||||
}
|
||||
})) return EmptyQuery.getEmptyQuery(); // Optimization
|
||||
return INSTANCE.createUniqueResultsQuery(new SearchParameters(method, scope, checkDeep));
|
||||
}
|
||||
|
||||
private static boolean cannotBeOverriden(final PsiMethod method) {
|
||||
final PsiClass parentClass = method.getContainingClass();
|
||||
return parentClass == null
|
||||
|| method.isConstructor()
|
||||
|| method.hasModifierProperty(PsiModifier.STATIC)
|
||||
|| method.hasModifierProperty(PsiModifier.FINAL)
|
||||
|| method.hasModifierProperty(PsiModifier.PRIVATE)
|
||||
|| parentClass instanceof PsiAnonymousClass
|
||||
|| parentClass.hasModifierProperty(PsiModifier.FINAL);
|
||||
}
|
||||
|
||||
public static Query<PsiMethod> search(final PsiMethod method, final boolean checkDeep) {
|
||||
return search(method, ApplicationManager.getApplication().runReadAction(new Computable<SearchScope>() {
|
||||
@Override
|
||||
public SearchScope compute() {
|
||||
return method.getUseScope();
|
||||
}
|
||||
}), checkDeep);
|
||||
}
|
||||
|
||||
public static Query<PsiMethod> search(final PsiMethod method) {
|
||||
return search(method, true);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.search.searches;
|
||||
|
||||
import com.intellij.openapi.application.ApplicationManager;
|
||||
import com.intellij.openapi.extensions.ExtensionPointName;
|
||||
import com.intellij.openapi.util.Computable;
|
||||
import com.intellij.psi.PsiAnonymousClass;
|
||||
import com.intellij.psi.PsiClass;
|
||||
import com.intellij.psi.PsiMethod;
|
||||
import com.intellij.psi.PsiModifier;
|
||||
import com.intellij.psi.search.SearchScope;
|
||||
import com.intellij.util.EmptyQuery;
|
||||
import com.intellij.util.Query;
|
||||
import com.intellij.util.QueryExecutor;
|
||||
|
||||
/**
|
||||
* @author max
|
||||
*/
|
||||
public class OverridingMethodsSearch extends ExtensibleQueryFactory<PsiMethod, OverridingMethodsSearch.SearchParameters> {
|
||||
public static ExtensionPointName<QueryExecutor> EP_NAME = ExtensionPointName.create("com.intellij.overridingMethodsSearch");
|
||||
public static final OverridingMethodsSearch INSTANCE = new OverridingMethodsSearch();
|
||||
|
||||
public static class SearchParameters {
|
||||
private final PsiMethod myMethod;
|
||||
private final SearchScope myScope;
|
||||
private final boolean myCheckDeep;
|
||||
|
||||
public SearchParameters(final PsiMethod aClass, SearchScope scope, final boolean checkDeep) {
|
||||
myMethod = aClass;
|
||||
myScope = scope;
|
||||
myCheckDeep = checkDeep;
|
||||
}
|
||||
|
||||
public PsiMethod getMethod() {
|
||||
return myMethod;
|
||||
}
|
||||
|
||||
public boolean isCheckDeep() {
|
||||
return myCheckDeep;
|
||||
}
|
||||
|
||||
public SearchScope getScope() {
|
||||
return myScope;
|
||||
}
|
||||
}
|
||||
|
||||
private OverridingMethodsSearch() {
|
||||
}
|
||||
|
||||
public static Query<PsiMethod> search(final PsiMethod method, SearchScope scope, final boolean checkDeep) {
|
||||
if (ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
|
||||
@Override
|
||||
public Boolean compute() {
|
||||
return cannotBeOverriden(method);
|
||||
}
|
||||
})) return EmptyQuery.getEmptyQuery(); // Optimization
|
||||
return INSTANCE.createUniqueResultsQuery(new SearchParameters(method, scope, checkDeep));
|
||||
}
|
||||
|
||||
private static boolean cannotBeOverriden(final PsiMethod method) {
|
||||
final PsiClass parentClass = method.getContainingClass();
|
||||
return parentClass == null
|
||||
|| method.isConstructor()
|
||||
|| method.hasModifierProperty(PsiModifier.STATIC)
|
||||
|| method.hasModifierProperty(PsiModifier.FINAL)
|
||||
|| method.hasModifierProperty(PsiModifier.PRIVATE)
|
||||
|| parentClass instanceof PsiAnonymousClass
|
||||
|| parentClass.hasModifierProperty(PsiModifier.FINAL);
|
||||
}
|
||||
|
||||
public static Query<PsiMethod> search(final PsiMethod method, final boolean checkDeep) {
|
||||
return search(method, ApplicationManager.getApplication().runReadAction(new Computable<SearchScope>() {
|
||||
@Override
|
||||
public SearchScope compute() {
|
||||
return method.getUseScope();
|
||||
}
|
||||
}), checkDeep);
|
||||
}
|
||||
|
||||
public static Query<PsiMethod> search(final PsiMethod method) {
|
||||
return search(method, true);
|
||||
}
|
||||
}
|
||||
|
||||
+80
-80
@@ -1,80 +1,80 @@
|
||||
package com.intellij.psi.impl.search;
|
||||
|
||||
import com.intellij.openapi.application.ApplicationManager;
|
||||
import com.intellij.openapi.util.Computable;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.search.SearchScope;
|
||||
import com.intellij.psi.search.searches.ClassInheritorsSearch;
|
||||
import com.intellij.psi.search.searches.OverridingMethodsSearch;
|
||||
import com.intellij.psi.util.MethodSignature;
|
||||
import com.intellij.psi.util.MethodSignatureUtil;
|
||||
import com.intellij.psi.util.TypeConversionUtil;
|
||||
import com.intellij.util.Processor;
|
||||
import com.intellij.util.QueryExecutor;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* @author max
|
||||
*/
|
||||
public class JavaOverridingMethodsSearcher implements QueryExecutor<PsiMethod, OverridingMethodsSearch.SearchParameters> {
|
||||
@Override
|
||||
public boolean execute(@NotNull final OverridingMethodsSearch.SearchParameters p, @NotNull final Processor<PsiMethod> consumer) {
|
||||
final PsiMethod method = p.getMethod();
|
||||
final SearchScope scope = p.getScope();
|
||||
|
||||
final PsiClass parentClass = ApplicationManager.getApplication().runReadAction(new Computable<PsiClass>() {
|
||||
@Nullable
|
||||
@Override
|
||||
public PsiClass compute() {
|
||||
return method.getContainingClass();
|
||||
}
|
||||
});
|
||||
assert parentClass != null;
|
||||
Processor<PsiClass> inheritorsProcessor = new Processor<PsiClass>() {
|
||||
@Override
|
||||
public boolean process(final PsiClass inheritor) {
|
||||
PsiMethod found = ApplicationManager.getApplication().runReadAction(new Computable<PsiMethod>() {
|
||||
@Override
|
||||
@Nullable
|
||||
public PsiMethod compute() {
|
||||
return findOverridingMethod(inheritor, parentClass, method);
|
||||
}
|
||||
});
|
||||
return found == null || consumer.process(found) && p.isCheckDeep();
|
||||
}
|
||||
};
|
||||
|
||||
return ClassInheritorsSearch.search(parentClass, scope, true).forEach(inheritorsProcessor);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static PsiMethod findOverridingMethod(PsiClass inheritor, @NotNull PsiClass parentClass, PsiMethod method) {
|
||||
PsiSubstitutor substitutor = inheritor.isInheritor(parentClass, true) ?
|
||||
TypeConversionUtil.getSuperClassSubstitutor(parentClass, inheritor, PsiSubstitutor.EMPTY) :
|
||||
PsiSubstitutor.EMPTY;
|
||||
MethodSignature signature = method.getSignature(substitutor);
|
||||
PsiMethod found = MethodSignatureUtil.findMethodBySuperSignature(inheritor, signature, false);
|
||||
if (found != null && isAcceptable(found, method)) {
|
||||
return found;
|
||||
}
|
||||
|
||||
if (parentClass.isInterface() && !inheritor.isInterface()) { //check for sibling implementation
|
||||
final PsiClass superClass = inheritor.getSuperClass();
|
||||
if (superClass != null && !superClass.isInheritor(parentClass, true)) {
|
||||
PsiMethod derived = MethodSignatureUtil.findMethodInSuperClassBySignatureInDerived(inheritor, superClass, signature, true);
|
||||
if (derived != null && isAcceptable(derived, method)) {
|
||||
return derived;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean isAcceptable(final PsiMethod found, final PsiMethod method) {
|
||||
return !found.hasModifierProperty(PsiModifier.STATIC) &&
|
||||
(!method.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) ||
|
||||
JavaPsiFacade.getInstance(found.getProject())
|
||||
.arePackagesTheSame(method.getContainingClass(), found.getContainingClass()));
|
||||
}
|
||||
}
|
||||
package com.intellij.psi.impl.search;
|
||||
|
||||
import com.intellij.openapi.application.ApplicationManager;
|
||||
import com.intellij.openapi.util.Computable;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.search.SearchScope;
|
||||
import com.intellij.psi.search.searches.ClassInheritorsSearch;
|
||||
import com.intellij.psi.search.searches.OverridingMethodsSearch;
|
||||
import com.intellij.psi.util.MethodSignature;
|
||||
import com.intellij.psi.util.MethodSignatureUtil;
|
||||
import com.intellij.psi.util.TypeConversionUtil;
|
||||
import com.intellij.util.Processor;
|
||||
import com.intellij.util.QueryExecutor;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* @author max
|
||||
*/
|
||||
public class JavaOverridingMethodsSearcher implements QueryExecutor<PsiMethod, OverridingMethodsSearch.SearchParameters> {
|
||||
@Override
|
||||
public boolean execute(@NotNull final OverridingMethodsSearch.SearchParameters p, @NotNull final Processor<PsiMethod> consumer) {
|
||||
final PsiMethod method = p.getMethod();
|
||||
final SearchScope scope = p.getScope();
|
||||
|
||||
final PsiClass parentClass = ApplicationManager.getApplication().runReadAction(new Computable<PsiClass>() {
|
||||
@Nullable
|
||||
@Override
|
||||
public PsiClass compute() {
|
||||
return method.getContainingClass();
|
||||
}
|
||||
});
|
||||
assert parentClass != null;
|
||||
Processor<PsiClass> inheritorsProcessor = new Processor<PsiClass>() {
|
||||
@Override
|
||||
public boolean process(final PsiClass inheritor) {
|
||||
PsiMethod found = ApplicationManager.getApplication().runReadAction(new Computable<PsiMethod>() {
|
||||
@Override
|
||||
@Nullable
|
||||
public PsiMethod compute() {
|
||||
return findOverridingMethod(inheritor, parentClass, method);
|
||||
}
|
||||
});
|
||||
return found == null || consumer.process(found) && p.isCheckDeep();
|
||||
}
|
||||
};
|
||||
|
||||
return ClassInheritorsSearch.search(parentClass, scope, true).forEach(inheritorsProcessor);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static PsiMethod findOverridingMethod(PsiClass inheritor, @NotNull PsiClass parentClass, PsiMethod method) {
|
||||
PsiSubstitutor substitutor = inheritor.isInheritor(parentClass, true) ?
|
||||
TypeConversionUtil.getSuperClassSubstitutor(parentClass, inheritor, PsiSubstitutor.EMPTY) :
|
||||
PsiSubstitutor.EMPTY;
|
||||
MethodSignature signature = method.getSignature(substitutor);
|
||||
PsiMethod found = MethodSignatureUtil.findMethodBySuperSignature(inheritor, signature, false);
|
||||
if (found != null && isAcceptable(found, method)) {
|
||||
return found;
|
||||
}
|
||||
|
||||
if (parentClass.isInterface() && !inheritor.isInterface()) { //check for sibling implementation
|
||||
final PsiClass superClass = inheritor.getSuperClass();
|
||||
if (superClass != null && !superClass.isInheritor(parentClass, true)) {
|
||||
PsiMethod derived = MethodSignatureUtil.findMethodInSuperClassBySignatureInDerived(inheritor, superClass, signature, true);
|
||||
if (derived != null && isAcceptable(derived, method)) {
|
||||
return derived;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean isAcceptable(final PsiMethod found, final PsiMethod method) {
|
||||
return !found.hasModifierProperty(PsiModifier.STATIC) &&
|
||||
(!method.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) ||
|
||||
JavaPsiFacade.getInstance(found.getProject())
|
||||
.arePackagesTheSame(method.getContainingClass(), found.getContainingClass()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,71 +1,71 @@
|
||||
package com.intellij.psi.impl.search;
|
||||
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.search.searches.SuperMethodsSearch;
|
||||
import com.intellij.psi.util.InheritanceUtil;
|
||||
import com.intellij.psi.util.MethodSignatureBackedByPsiMethod;
|
||||
import com.intellij.psi.util.MethodSignatureUtil;
|
||||
import com.intellij.util.Processor;
|
||||
import com.intellij.util.QueryExecutor;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author ven
|
||||
*/
|
||||
public class MethodSuperSearcher implements QueryExecutor<MethodSignatureBackedByPsiMethod, SuperMethodsSearch.SearchParameters> {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.search.MethodSuperSearcher");
|
||||
|
||||
@Override
|
||||
public boolean execute(@NotNull final SuperMethodsSearch.SearchParameters queryParameters, @NotNull final Processor<MethodSignatureBackedByPsiMethod> consumer) {
|
||||
final PsiClass parentClass = queryParameters.getPsiClass();
|
||||
final PsiMethod method = queryParameters.getMethod();
|
||||
HierarchicalMethodSignature signature = method.getHierarchicalMethodSignature();
|
||||
|
||||
final boolean checkBases = queryParameters.isCheckBases();
|
||||
final boolean allowStaticMethod = queryParameters.isAllowStaticMethod();
|
||||
final List<HierarchicalMethodSignature> supers = signature.getSuperSignatures();
|
||||
for (HierarchicalMethodSignature superSignature : supers) {
|
||||
if (MethodSignatureUtil.isSubsignature(superSignature, signature)) {
|
||||
if (!addSuperMethods(superSignature, method, parentClass, allowStaticMethod, checkBases, consumer)) return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean addSuperMethods(final HierarchicalMethodSignature signature,
|
||||
final PsiMethod method,
|
||||
final PsiClass parentClass,
|
||||
final boolean allowStaticMethod,
|
||||
final boolean checkBases,
|
||||
final Processor<MethodSignatureBackedByPsiMethod> consumer) {
|
||||
PsiMethod signatureMethod = signature.getMethod();
|
||||
PsiClass hisClass = signatureMethod.getContainingClass();
|
||||
if (parentClass == null || InheritanceUtil.isInheritorOrSelf(parentClass, hisClass, true)) {
|
||||
if (isAcceptable(signatureMethod, method, allowStaticMethod)) {
|
||||
if (parentClass != null && !parentClass.equals(hisClass) && !checkBases) {
|
||||
return true;
|
||||
}
|
||||
LOG.assertTrue(signatureMethod != method, method); // method != method.getsuper()
|
||||
return consumer.process(signature); //no need to check super classes
|
||||
}
|
||||
}
|
||||
for (HierarchicalMethodSignature superSignature : signature.getSuperSignatures()) {
|
||||
if (MethodSignatureUtil.isSubsignature(superSignature, signature)) {
|
||||
addSuperMethods(superSignature, method, parentClass, allowStaticMethod, checkBases, consumer);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean isAcceptable(final PsiMethod superMethod, final PsiMethod method, final boolean allowStaticMethod) {
|
||||
boolean hisStatic = superMethod.hasModifierProperty(PsiModifier.STATIC);
|
||||
return hisStatic == method.hasModifierProperty(PsiModifier.STATIC) &&
|
||||
(allowStaticMethod || !hisStatic) &&
|
||||
JavaPsiFacade.getInstance(method.getProject()).getResolveHelper().isAccessible(superMethod, method, null);
|
||||
}
|
||||
}
|
||||
package com.intellij.psi.impl.search;
|
||||
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.search.searches.SuperMethodsSearch;
|
||||
import com.intellij.psi.util.InheritanceUtil;
|
||||
import com.intellij.psi.util.MethodSignatureBackedByPsiMethod;
|
||||
import com.intellij.psi.util.MethodSignatureUtil;
|
||||
import com.intellij.util.Processor;
|
||||
import com.intellij.util.QueryExecutor;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author ven
|
||||
*/
|
||||
public class MethodSuperSearcher implements QueryExecutor<MethodSignatureBackedByPsiMethod, SuperMethodsSearch.SearchParameters> {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.search.MethodSuperSearcher");
|
||||
|
||||
@Override
|
||||
public boolean execute(@NotNull final SuperMethodsSearch.SearchParameters queryParameters, @NotNull final Processor<MethodSignatureBackedByPsiMethod> consumer) {
|
||||
final PsiClass parentClass = queryParameters.getPsiClass();
|
||||
final PsiMethod method = queryParameters.getMethod();
|
||||
HierarchicalMethodSignature signature = method.getHierarchicalMethodSignature();
|
||||
|
||||
final boolean checkBases = queryParameters.isCheckBases();
|
||||
final boolean allowStaticMethod = queryParameters.isAllowStaticMethod();
|
||||
final List<HierarchicalMethodSignature> supers = signature.getSuperSignatures();
|
||||
for (HierarchicalMethodSignature superSignature : supers) {
|
||||
if (MethodSignatureUtil.isSubsignature(superSignature, signature)) {
|
||||
if (!addSuperMethods(superSignature, method, parentClass, allowStaticMethod, checkBases, consumer)) return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean addSuperMethods(final HierarchicalMethodSignature signature,
|
||||
final PsiMethod method,
|
||||
final PsiClass parentClass,
|
||||
final boolean allowStaticMethod,
|
||||
final boolean checkBases,
|
||||
final Processor<MethodSignatureBackedByPsiMethod> consumer) {
|
||||
PsiMethod signatureMethod = signature.getMethod();
|
||||
PsiClass hisClass = signatureMethod.getContainingClass();
|
||||
if (parentClass == null || InheritanceUtil.isInheritorOrSelf(parentClass, hisClass, true)) {
|
||||
if (isAcceptable(signatureMethod, method, allowStaticMethod)) {
|
||||
if (parentClass != null && !parentClass.equals(hisClass) && !checkBases) {
|
||||
return true;
|
||||
}
|
||||
LOG.assertTrue(signatureMethod != method, method); // method != method.getsuper()
|
||||
return consumer.process(signature); //no need to check super classes
|
||||
}
|
||||
}
|
||||
for (HierarchicalMethodSignature superSignature : signature.getSuperSignatures()) {
|
||||
if (MethodSignatureUtil.isSubsignature(superSignature, signature)) {
|
||||
addSuperMethods(superSignature, method, parentClass, allowStaticMethod, checkBases, consumer);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean isAcceptable(final PsiMethod superMethod, final PsiMethod method, final boolean allowStaticMethod) {
|
||||
boolean hisStatic = superMethod.hasModifierProperty(PsiModifier.STATIC);
|
||||
return hisStatic == method.hasModifierProperty(PsiModifier.STATIC) &&
|
||||
(allowStaticMethod || !hisStatic) &&
|
||||
JavaPsiFacade.getInstance(method.getProject()).getResolveHelper().isAccessible(superMethod, method, null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,213 +1,213 @@
|
||||
/*
|
||||
* Copyright 2000-2011 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @author max
|
||||
*/
|
||||
package com.intellij.psi.codeStyle;
|
||||
|
||||
import com.intellij.openapi.components.ServiceManager;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import org.intellij.lang.annotations.MagicConstant;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
public abstract class JavaCodeStyleManager {
|
||||
public static JavaCodeStyleManager getInstance(Project project) {
|
||||
return ServiceManager.getService(project, JavaCodeStyleManager.class);
|
||||
}
|
||||
|
||||
public static final int DO_NOT_ADD_IMPORTS = 0x1000;
|
||||
public static final int UNCOMPLETE_CODE = 0x2000;
|
||||
|
||||
public abstract boolean addImport(@NotNull PsiJavaFile file, @NotNull PsiClass refClass);
|
||||
public abstract PsiElement shortenClassReferences(@NotNull PsiElement element, @MagicConstant(flags = {DO_NOT_ADD_IMPORTS, UNCOMPLETE_CODE}) int flags) throws IncorrectOperationException;
|
||||
|
||||
@NotNull public abstract String getPrefixByVariableKind(VariableKind variableKind);
|
||||
@NotNull public abstract String getSuffixByVariableKind(VariableKind variableKind);
|
||||
|
||||
public abstract int findEntryIndex(@NotNull PsiImportStatementBase statement);
|
||||
|
||||
/**
|
||||
* Replaces fully-qualified class names in the contents of the specified element with
|
||||
* non-qualified names and adds import statements as necessary.
|
||||
*
|
||||
* @param element the element to shorten references in.
|
||||
* @return the element in the PSI tree after the shorten references operation corresponding
|
||||
* to the original element.
|
||||
* @throws com.intellij.util.IncorrectOperationException if the file to shorten references in is read-only.
|
||||
*/
|
||||
public abstract PsiElement shortenClassReferences(@NotNull PsiElement element) throws IncorrectOperationException;
|
||||
|
||||
/**
|
||||
* Replaces fully-qualified class names in a part of contents of the specified element with
|
||||
* non-qualified names and adds import statements as necessary.
|
||||
*
|
||||
* @param element the element to shorten references in.
|
||||
* @param startOffset the start offset in the <b>element</b> of the part where class references are
|
||||
* shortened.
|
||||
* @param endOffset the end offset in the <b>element</b> of the part where class references are
|
||||
* shortened.
|
||||
* @throws IncorrectOperationException if the file to shorten references in is read-only.
|
||||
*/
|
||||
public abstract void shortenClassReferences(@NotNull PsiElement element, int startOffset, int endOffset) throws IncorrectOperationException;
|
||||
|
||||
/**
|
||||
* Optimizes imports in the specified Java or JSP file.
|
||||
*
|
||||
* @param file the file to optimize the imports in.
|
||||
* @throws IncorrectOperationException if the file is read-only.
|
||||
*/
|
||||
public abstract void optimizeImports(@NotNull PsiFile file) throws IncorrectOperationException;
|
||||
|
||||
/**
|
||||
* Calculates the import list that would be substituted in the specified Java or JSP
|
||||
* file if an Optimize Imports operation was performed on it.
|
||||
*
|
||||
* @param file the file to calculate the import list for.
|
||||
* @return the calculated import list.
|
||||
*/
|
||||
public abstract PsiImportList prepareOptimizeImportsResult(@NotNull PsiJavaFile file);
|
||||
|
||||
/**
|
||||
* Returns the kind of the specified variable (local, parameter, field, static field or static
|
||||
* final field).
|
||||
*
|
||||
* @param variable the variable to get the kind for.
|
||||
* @return the variable kind.
|
||||
*/
|
||||
public VariableKind getVariableKind(@NotNull PsiVariable variable){
|
||||
if (variable instanceof PsiField) {
|
||||
if (variable.hasModifierProperty(PsiModifier.STATIC)) {
|
||||
if (variable.hasModifierProperty(PsiModifier.FINAL)) {
|
||||
return VariableKind.STATIC_FINAL_FIELD;
|
||||
}
|
||||
return VariableKind.STATIC_FIELD;
|
||||
}
|
||||
return VariableKind.FIELD;
|
||||
}
|
||||
else {
|
||||
if (variable instanceof PsiParameter) {
|
||||
if (((PsiParameter)variable).getDeclarationScope() instanceof PsiForeachStatement) {
|
||||
return VariableKind.LOCAL_VARIABLE;
|
||||
}
|
||||
return VariableKind.PARAMETER;
|
||||
}
|
||||
return VariableKind.LOCAL_VARIABLE;
|
||||
}
|
||||
}
|
||||
|
||||
public SuggestedNameInfo suggestVariableName(@NotNull final VariableKind kind,
|
||||
@Nullable final String propertyName,
|
||||
@Nullable final PsiExpression expr,
|
||||
@Nullable PsiType type) {
|
||||
return suggestVariableName(kind, propertyName, expr, type, true);
|
||||
}
|
||||
|
||||
|
||||
public abstract SuggestedNameInfo suggestVariableName(@NotNull VariableKind kind,
|
||||
@Nullable String propertyName,
|
||||
@Nullable PsiExpression expr,
|
||||
@Nullable PsiType type,
|
||||
boolean correctKeywords);
|
||||
/**
|
||||
* Generates a stripped-down name (with no code style defined prefixes or suffixes, usable as
|
||||
* a property name) from the specified name of a variable of the specified kind.
|
||||
*
|
||||
* @param name the name of the variable.
|
||||
* @param variableKind the kind of the variable.
|
||||
* @return the stripped-down name.
|
||||
*/
|
||||
public abstract String variableNameToPropertyName(@NonNls String name, VariableKind variableKind);
|
||||
|
||||
/**
|
||||
* Appends code style defined prefixes and/or suffixes for the specified variable kind
|
||||
* to the specified variable name.
|
||||
*
|
||||
* @param propertyName the base name of the variable.
|
||||
* @param variableKind the kind of the variable.
|
||||
* @return the variable name.
|
||||
*/
|
||||
public abstract String propertyNameToVariableName(@NonNls String propertyName, VariableKind variableKind);
|
||||
|
||||
/**
|
||||
* Suggests a unique name for the variable used at the specified location.
|
||||
*
|
||||
* @param baseName the base name for the variable.
|
||||
* @param place the location where the variable will be used.
|
||||
* @param lookForward if true, the existing variables are searched in both directions; if false - only backward
|
||||
* @return the generated unique name,
|
||||
*/
|
||||
public abstract String suggestUniqueVariableName(@NonNls String baseName, PsiElement place, boolean lookForward);
|
||||
|
||||
/**
|
||||
* Suggests a unique name for the variable used at the specified location.
|
||||
*
|
||||
* @param baseNameInfo the base name info for the variable.
|
||||
* @param place the location where the variable will be used.
|
||||
* @param lookForward if true, the existing variables are searched in both directions; if false - only backward
|
||||
* @return the generated unique name
|
||||
*/
|
||||
@NotNull
|
||||
public SuggestedNameInfo suggestUniqueVariableName(@NotNull SuggestedNameInfo baseNameInfo,
|
||||
PsiElement place,
|
||||
boolean lookForward) {
|
||||
return suggestUniqueVariableName(baseNameInfo, place, false, lookForward);
|
||||
}
|
||||
|
||||
/**
|
||||
* Suggests a unique name for the variable used at the specified location.
|
||||
*
|
||||
*
|
||||
* @param baseNameInfo the base name info for the variable.
|
||||
* @param place the location where the variable will be used.
|
||||
* @param ignorePlaceName if true and place is PsiNamedElement, place.getName() would be still treated as unique name
|
||||
* @param lookForward if true, the existing variables are searched in both directions; if false - only backward @return the generated unique name,
|
||||
* @return the generated unique name
|
||||
*/
|
||||
@NotNull public abstract SuggestedNameInfo suggestUniqueVariableName(@NotNull SuggestedNameInfo baseNameInfo,
|
||||
PsiElement place,
|
||||
boolean ignorePlaceName,
|
||||
boolean lookForward);
|
||||
|
||||
/**
|
||||
* Replaces all references to Java classes in the contents of the specified element,
|
||||
* except for references to classes in the same package or in implicitly imported packages,
|
||||
* with full-qualified references.
|
||||
*
|
||||
* @param element the element to replace the references in.
|
||||
* @return the element in the PSI tree after the qualify operation corresponding to the
|
||||
* original element.
|
||||
*/
|
||||
public abstract PsiElement qualifyClassReferences(@NotNull PsiElement element);
|
||||
|
||||
/**
|
||||
* Removes unused import statements from the specified Java file.
|
||||
*
|
||||
* @param file the file to remove the import statements from.
|
||||
* @throws IncorrectOperationException if the operation fails for some reason (for example,
|
||||
* the file is read-only).
|
||||
*/
|
||||
public abstract void removeRedundantImports(@NotNull PsiJavaFile file) throws IncorrectOperationException;
|
||||
|
||||
@Nullable
|
||||
public abstract Collection<PsiImportStatementBase> findRedundantImports(PsiJavaFile file);
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2011 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @author max
|
||||
*/
|
||||
package com.intellij.psi.codeStyle;
|
||||
|
||||
import com.intellij.openapi.components.ServiceManager;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import org.intellij.lang.annotations.MagicConstant;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
public abstract class JavaCodeStyleManager {
|
||||
public static JavaCodeStyleManager getInstance(Project project) {
|
||||
return ServiceManager.getService(project, JavaCodeStyleManager.class);
|
||||
}
|
||||
|
||||
public static final int DO_NOT_ADD_IMPORTS = 0x1000;
|
||||
public static final int UNCOMPLETE_CODE = 0x2000;
|
||||
|
||||
public abstract boolean addImport(@NotNull PsiJavaFile file, @NotNull PsiClass refClass);
|
||||
public abstract PsiElement shortenClassReferences(@NotNull PsiElement element, @MagicConstant(flags = {DO_NOT_ADD_IMPORTS, UNCOMPLETE_CODE}) int flags) throws IncorrectOperationException;
|
||||
|
||||
@NotNull public abstract String getPrefixByVariableKind(VariableKind variableKind);
|
||||
@NotNull public abstract String getSuffixByVariableKind(VariableKind variableKind);
|
||||
|
||||
public abstract int findEntryIndex(@NotNull PsiImportStatementBase statement);
|
||||
|
||||
/**
|
||||
* Replaces fully-qualified class names in the contents of the specified element with
|
||||
* non-qualified names and adds import statements as necessary.
|
||||
*
|
||||
* @param element the element to shorten references in.
|
||||
* @return the element in the PSI tree after the shorten references operation corresponding
|
||||
* to the original element.
|
||||
* @throws com.intellij.util.IncorrectOperationException if the file to shorten references in is read-only.
|
||||
*/
|
||||
public abstract PsiElement shortenClassReferences(@NotNull PsiElement element) throws IncorrectOperationException;
|
||||
|
||||
/**
|
||||
* Replaces fully-qualified class names in a part of contents of the specified element with
|
||||
* non-qualified names and adds import statements as necessary.
|
||||
*
|
||||
* @param element the element to shorten references in.
|
||||
* @param startOffset the start offset in the <b>element</b> of the part where class references are
|
||||
* shortened.
|
||||
* @param endOffset the end offset in the <b>element</b> of the part where class references are
|
||||
* shortened.
|
||||
* @throws IncorrectOperationException if the file to shorten references in is read-only.
|
||||
*/
|
||||
public abstract void shortenClassReferences(@NotNull PsiElement element, int startOffset, int endOffset) throws IncorrectOperationException;
|
||||
|
||||
/**
|
||||
* Optimizes imports in the specified Java or JSP file.
|
||||
*
|
||||
* @param file the file to optimize the imports in.
|
||||
* @throws IncorrectOperationException if the file is read-only.
|
||||
*/
|
||||
public abstract void optimizeImports(@NotNull PsiFile file) throws IncorrectOperationException;
|
||||
|
||||
/**
|
||||
* Calculates the import list that would be substituted in the specified Java or JSP
|
||||
* file if an Optimize Imports operation was performed on it.
|
||||
*
|
||||
* @param file the file to calculate the import list for.
|
||||
* @return the calculated import list.
|
||||
*/
|
||||
public abstract PsiImportList prepareOptimizeImportsResult(@NotNull PsiJavaFile file);
|
||||
|
||||
/**
|
||||
* Returns the kind of the specified variable (local, parameter, field, static field or static
|
||||
* final field).
|
||||
*
|
||||
* @param variable the variable to get the kind for.
|
||||
* @return the variable kind.
|
||||
*/
|
||||
public VariableKind getVariableKind(@NotNull PsiVariable variable){
|
||||
if (variable instanceof PsiField) {
|
||||
if (variable.hasModifierProperty(PsiModifier.STATIC)) {
|
||||
if (variable.hasModifierProperty(PsiModifier.FINAL)) {
|
||||
return VariableKind.STATIC_FINAL_FIELD;
|
||||
}
|
||||
return VariableKind.STATIC_FIELD;
|
||||
}
|
||||
return VariableKind.FIELD;
|
||||
}
|
||||
else {
|
||||
if (variable instanceof PsiParameter) {
|
||||
if (((PsiParameter)variable).getDeclarationScope() instanceof PsiForeachStatement) {
|
||||
return VariableKind.LOCAL_VARIABLE;
|
||||
}
|
||||
return VariableKind.PARAMETER;
|
||||
}
|
||||
return VariableKind.LOCAL_VARIABLE;
|
||||
}
|
||||
}
|
||||
|
||||
public SuggestedNameInfo suggestVariableName(@NotNull final VariableKind kind,
|
||||
@Nullable final String propertyName,
|
||||
@Nullable final PsiExpression expr,
|
||||
@Nullable PsiType type) {
|
||||
return suggestVariableName(kind, propertyName, expr, type, true);
|
||||
}
|
||||
|
||||
|
||||
public abstract SuggestedNameInfo suggestVariableName(@NotNull VariableKind kind,
|
||||
@Nullable String propertyName,
|
||||
@Nullable PsiExpression expr,
|
||||
@Nullable PsiType type,
|
||||
boolean correctKeywords);
|
||||
/**
|
||||
* Generates a stripped-down name (with no code style defined prefixes or suffixes, usable as
|
||||
* a property name) from the specified name of a variable of the specified kind.
|
||||
*
|
||||
* @param name the name of the variable.
|
||||
* @param variableKind the kind of the variable.
|
||||
* @return the stripped-down name.
|
||||
*/
|
||||
public abstract String variableNameToPropertyName(@NonNls String name, VariableKind variableKind);
|
||||
|
||||
/**
|
||||
* Appends code style defined prefixes and/or suffixes for the specified variable kind
|
||||
* to the specified variable name.
|
||||
*
|
||||
* @param propertyName the base name of the variable.
|
||||
* @param variableKind the kind of the variable.
|
||||
* @return the variable name.
|
||||
*/
|
||||
public abstract String propertyNameToVariableName(@NonNls String propertyName, VariableKind variableKind);
|
||||
|
||||
/**
|
||||
* Suggests a unique name for the variable used at the specified location.
|
||||
*
|
||||
* @param baseName the base name for the variable.
|
||||
* @param place the location where the variable will be used.
|
||||
* @param lookForward if true, the existing variables are searched in both directions; if false - only backward
|
||||
* @return the generated unique name,
|
||||
*/
|
||||
public abstract String suggestUniqueVariableName(@NonNls String baseName, PsiElement place, boolean lookForward);
|
||||
|
||||
/**
|
||||
* Suggests a unique name for the variable used at the specified location.
|
||||
*
|
||||
* @param baseNameInfo the base name info for the variable.
|
||||
* @param place the location where the variable will be used.
|
||||
* @param lookForward if true, the existing variables are searched in both directions; if false - only backward
|
||||
* @return the generated unique name
|
||||
*/
|
||||
@NotNull
|
||||
public SuggestedNameInfo suggestUniqueVariableName(@NotNull SuggestedNameInfo baseNameInfo,
|
||||
PsiElement place,
|
||||
boolean lookForward) {
|
||||
return suggestUniqueVariableName(baseNameInfo, place, false, lookForward);
|
||||
}
|
||||
|
||||
/**
|
||||
* Suggests a unique name for the variable used at the specified location.
|
||||
*
|
||||
*
|
||||
* @param baseNameInfo the base name info for the variable.
|
||||
* @param place the location where the variable will be used.
|
||||
* @param ignorePlaceName if true and place is PsiNamedElement, place.getName() would be still treated as unique name
|
||||
* @param lookForward if true, the existing variables are searched in both directions; if false - only backward @return the generated unique name,
|
||||
* @return the generated unique name
|
||||
*/
|
||||
@NotNull public abstract SuggestedNameInfo suggestUniqueVariableName(@NotNull SuggestedNameInfo baseNameInfo,
|
||||
PsiElement place,
|
||||
boolean ignorePlaceName,
|
||||
boolean lookForward);
|
||||
|
||||
/**
|
||||
* Replaces all references to Java classes in the contents of the specified element,
|
||||
* except for references to classes in the same package or in implicitly imported packages,
|
||||
* with full-qualified references.
|
||||
*
|
||||
* @param element the element to replace the references in.
|
||||
* @return the element in the PSI tree after the qualify operation corresponding to the
|
||||
* original element.
|
||||
*/
|
||||
public abstract PsiElement qualifyClassReferences(@NotNull PsiElement element);
|
||||
|
||||
/**
|
||||
* Removes unused import statements from the specified Java file.
|
||||
*
|
||||
* @param file the file to remove the import statements from.
|
||||
* @throws IncorrectOperationException if the operation fails for some reason (for example,
|
||||
* the file is read-only).
|
||||
*/
|
||||
public abstract void removeRedundantImports(@NotNull PsiJavaFile file) throws IncorrectOperationException;
|
||||
|
||||
@Nullable
|
||||
public abstract Collection<PsiImportStatementBase> findRedundantImports(PsiJavaFile file);
|
||||
}
|
||||
|
||||
@@ -1,77 +1,77 @@
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.search.searches;
|
||||
|
||||
import com.intellij.openapi.extensions.ExtensionPointName;
|
||||
import com.intellij.psi.PsiClass;
|
||||
import com.intellij.psi.PsiMethod;
|
||||
import com.intellij.psi.util.MethodSignatureBackedByPsiMethod;
|
||||
import com.intellij.psi.util.MethodSignatureUtil;
|
||||
import com.intellij.util.Query;
|
||||
import com.intellij.util.QueryExecutor;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* @author max
|
||||
*/
|
||||
public class SuperMethodsSearch extends ExtensibleQueryFactory<MethodSignatureBackedByPsiMethod, SuperMethodsSearch.SearchParameters> {
|
||||
public static ExtensionPointName<QueryExecutor> EP_NAME = ExtensionPointName.create("com.intellij.superMethodsSearch");
|
||||
public static final SuperMethodsSearch SUPER_METHODS_SEARCH_INSTANCE = new SuperMethodsSearch();
|
||||
|
||||
public static class SearchParameters {
|
||||
private final PsiMethod myMethod;
|
||||
//null means any class would be matched
|
||||
@Nullable private final PsiClass myClass;
|
||||
private final boolean myCheckBases;
|
||||
private final boolean myAllowStaticMethod;
|
||||
|
||||
public SearchParameters(final PsiMethod method,
|
||||
@Nullable final PsiClass aClass,
|
||||
final boolean checkBases,
|
||||
final boolean allowStaticMethod) {
|
||||
myCheckBases = checkBases;
|
||||
myClass = aClass;
|
||||
myMethod = method;
|
||||
myAllowStaticMethod = allowStaticMethod;
|
||||
}
|
||||
|
||||
public final boolean isCheckBases() {
|
||||
return myCheckBases;
|
||||
}
|
||||
|
||||
public final PsiMethod getMethod() {
|
||||
return myMethod;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public final PsiClass getPsiClass() {
|
||||
return myClass;
|
||||
}
|
||||
|
||||
public final boolean isAllowStaticMethod() {
|
||||
return myAllowStaticMethod;
|
||||
}
|
||||
}
|
||||
|
||||
private SuperMethodsSearch() {
|
||||
}
|
||||
|
||||
public static Query<MethodSignatureBackedByPsiMethod> search(final PsiMethod derivedMethod, @Nullable final PsiClass psiClass, boolean checkBases, boolean allowStaticMethod) {
|
||||
final SearchParameters parameters = new SearchParameters(derivedMethod, psiClass, checkBases, allowStaticMethod);
|
||||
return SUPER_METHODS_SEARCH_INSTANCE.createUniqueResultsQuery(parameters, MethodSignatureUtil.METHOD_BASED_HASHING_STRATEGY);
|
||||
}
|
||||
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.search.searches;
|
||||
|
||||
import com.intellij.openapi.extensions.ExtensionPointName;
|
||||
import com.intellij.psi.PsiClass;
|
||||
import com.intellij.psi.PsiMethod;
|
||||
import com.intellij.psi.util.MethodSignatureBackedByPsiMethod;
|
||||
import com.intellij.psi.util.MethodSignatureUtil;
|
||||
import com.intellij.util.Query;
|
||||
import com.intellij.util.QueryExecutor;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* @author max
|
||||
*/
|
||||
public class SuperMethodsSearch extends ExtensibleQueryFactory<MethodSignatureBackedByPsiMethod, SuperMethodsSearch.SearchParameters> {
|
||||
public static ExtensionPointName<QueryExecutor> EP_NAME = ExtensionPointName.create("com.intellij.superMethodsSearch");
|
||||
public static final SuperMethodsSearch SUPER_METHODS_SEARCH_INSTANCE = new SuperMethodsSearch();
|
||||
|
||||
public static class SearchParameters {
|
||||
private final PsiMethod myMethod;
|
||||
//null means any class would be matched
|
||||
@Nullable private final PsiClass myClass;
|
||||
private final boolean myCheckBases;
|
||||
private final boolean myAllowStaticMethod;
|
||||
|
||||
public SearchParameters(final PsiMethod method,
|
||||
@Nullable final PsiClass aClass,
|
||||
final boolean checkBases,
|
||||
final boolean allowStaticMethod) {
|
||||
myCheckBases = checkBases;
|
||||
myClass = aClass;
|
||||
myMethod = method;
|
||||
myAllowStaticMethod = allowStaticMethod;
|
||||
}
|
||||
|
||||
public final boolean isCheckBases() {
|
||||
return myCheckBases;
|
||||
}
|
||||
|
||||
public final PsiMethod getMethod() {
|
||||
return myMethod;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public final PsiClass getPsiClass() {
|
||||
return myClass;
|
||||
}
|
||||
|
||||
public final boolean isAllowStaticMethod() {
|
||||
return myAllowStaticMethod;
|
||||
}
|
||||
}
|
||||
|
||||
private SuperMethodsSearch() {
|
||||
}
|
||||
|
||||
public static Query<MethodSignatureBackedByPsiMethod> search(final PsiMethod derivedMethod, @Nullable final PsiClass psiClass, boolean checkBases, boolean allowStaticMethod) {
|
||||
final SearchParameters parameters = new SearchParameters(derivedMethod, psiClass, checkBases, allowStaticMethod);
|
||||
return SUPER_METHODS_SEARCH_INSTANCE.createUniqueResultsQuery(parameters, MethodSignatureUtil.METHOD_BASED_HASHING_STRATEGY);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,188 +1,188 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.core;
|
||||
|
||||
import com.intellij.openapi.util.Comparing;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
|
||||
import com.intellij.psi.codeStyle.SuggestedNameInfo;
|
||||
import com.intellij.psi.codeStyle.VariableKind;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.psi.util.PsiUtil;
|
||||
import com.intellij.util.ArrayUtil;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import org.intellij.lang.annotations.MagicConstant;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashSet;
|
||||
|
||||
public class CoreJavaCodeStyleManager extends JavaCodeStyleManager {
|
||||
@Override
|
||||
public boolean addImport(@NotNull PsiJavaFile file, @NotNull PsiClass refClass) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiElement shortenClassReferences(@NotNull PsiElement element,
|
||||
@MagicConstant(flags = {DO_NOT_ADD_IMPORTS, UNCOMPLETE_CODE}) int flags)
|
||||
throws IncorrectOperationException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getPrefixByVariableKind(VariableKind variableKind) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getSuffixByVariableKind(VariableKind variableKind) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int findEntryIndex(@NotNull PsiImportStatementBase statement) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiElement shortenClassReferences(@NotNull PsiElement element) throws IncorrectOperationException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shortenClassReferences(@NotNull PsiElement element, int startOffset, int endOffset) throws IncorrectOperationException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void optimizeImports(@NotNull PsiFile file) throws IncorrectOperationException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiImportList prepareOptimizeImportsResult(@NotNull PsiJavaFile file) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SuggestedNameInfo suggestVariableName(@NotNull VariableKind kind,
|
||||
@Nullable String propertyName,
|
||||
@Nullable PsiExpression expr,
|
||||
@Nullable PsiType type,
|
||||
boolean correctKeywords) {
|
||||
return SuggestedNameInfo.NULL_INFO;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String variableNameToPropertyName(@NonNls String name, VariableKind variableKind) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String propertyNameToVariableName(@NonNls String propertyName, VariableKind variableKind) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String suggestUniqueVariableName(@NonNls String baseName, PsiElement place, boolean lookForward) {
|
||||
int index = 0;
|
||||
PsiElement scope = PsiTreeUtil.getNonStrictParentOfType(place, PsiStatement.class, PsiCodeBlock.class, PsiMethod.class);
|
||||
NextName:
|
||||
while (true) {
|
||||
String name = baseName;
|
||||
if (index > 0) {
|
||||
name += index;
|
||||
}
|
||||
index++;
|
||||
if (PsiUtil.isVariableNameUnique(name, place)) {
|
||||
if (lookForward) {
|
||||
final String name1 = name;
|
||||
PsiElement run = scope;
|
||||
while (run != null) {
|
||||
class CancelException extends RuntimeException {
|
||||
}
|
||||
try {
|
||||
run.accept(new JavaRecursiveElementWalkingVisitor() {
|
||||
@Override
|
||||
public void visitAnonymousClass(final PsiAnonymousClass aClass) {
|
||||
}
|
||||
|
||||
@Override public void visitVariable(PsiVariable variable) {
|
||||
if (name1.equals(variable.getName())) {
|
||||
throw new CancelException();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (CancelException e) {
|
||||
continue NextName;
|
||||
}
|
||||
run = run.getNextSibling();
|
||||
if (scope instanceof PsiMethod) {//do not check next member for param name conflict
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public SuggestedNameInfo suggestUniqueVariableName(@NotNull final SuggestedNameInfo baseNameInfo,
|
||||
PsiElement place,
|
||||
boolean ignorePlaceName,
|
||||
boolean lookForward) {
|
||||
final String[] names = baseNameInfo.names;
|
||||
final LinkedHashSet<String> uniqueNames = new LinkedHashSet<String>(names.length);
|
||||
for (String name : names) {
|
||||
if (ignorePlaceName && place instanceof PsiNamedElement) {
|
||||
final String placeName = ((PsiNamedElement)place).getName();
|
||||
if (Comparing.strEqual(placeName, name)) {
|
||||
uniqueNames.add(name);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
uniqueNames.add(suggestUniqueVariableName(name, place, lookForward));
|
||||
}
|
||||
|
||||
return new SuggestedNameInfo(ArrayUtil.toStringArray(uniqueNames)) {
|
||||
@Override
|
||||
public void nameChosen(String name) {
|
||||
baseNameInfo.nameChosen(name);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiElement qualifyClassReferences(@NotNull PsiElement element) {
|
||||
return element;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeRedundantImports(@NotNull PsiJavaFile file) throws IncorrectOperationException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<PsiImportStatementBase> findRedundantImports(PsiJavaFile file) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.core;
|
||||
|
||||
import com.intellij.openapi.util.Comparing;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
|
||||
import com.intellij.psi.codeStyle.SuggestedNameInfo;
|
||||
import com.intellij.psi.codeStyle.VariableKind;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.psi.util.PsiUtil;
|
||||
import com.intellij.util.ArrayUtil;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import org.intellij.lang.annotations.MagicConstant;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashSet;
|
||||
|
||||
public class CoreJavaCodeStyleManager extends JavaCodeStyleManager {
|
||||
@Override
|
||||
public boolean addImport(@NotNull PsiJavaFile file, @NotNull PsiClass refClass) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiElement shortenClassReferences(@NotNull PsiElement element,
|
||||
@MagicConstant(flags = {DO_NOT_ADD_IMPORTS, UNCOMPLETE_CODE}) int flags)
|
||||
throws IncorrectOperationException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getPrefixByVariableKind(VariableKind variableKind) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getSuffixByVariableKind(VariableKind variableKind) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int findEntryIndex(@NotNull PsiImportStatementBase statement) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiElement shortenClassReferences(@NotNull PsiElement element) throws IncorrectOperationException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shortenClassReferences(@NotNull PsiElement element, int startOffset, int endOffset) throws IncorrectOperationException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void optimizeImports(@NotNull PsiFile file) throws IncorrectOperationException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiImportList prepareOptimizeImportsResult(@NotNull PsiJavaFile file) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SuggestedNameInfo suggestVariableName(@NotNull VariableKind kind,
|
||||
@Nullable String propertyName,
|
||||
@Nullable PsiExpression expr,
|
||||
@Nullable PsiType type,
|
||||
boolean correctKeywords) {
|
||||
return SuggestedNameInfo.NULL_INFO;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String variableNameToPropertyName(@NonNls String name, VariableKind variableKind) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String propertyNameToVariableName(@NonNls String propertyName, VariableKind variableKind) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String suggestUniqueVariableName(@NonNls String baseName, PsiElement place, boolean lookForward) {
|
||||
int index = 0;
|
||||
PsiElement scope = PsiTreeUtil.getNonStrictParentOfType(place, PsiStatement.class, PsiCodeBlock.class, PsiMethod.class);
|
||||
NextName:
|
||||
while (true) {
|
||||
String name = baseName;
|
||||
if (index > 0) {
|
||||
name += index;
|
||||
}
|
||||
index++;
|
||||
if (PsiUtil.isVariableNameUnique(name, place)) {
|
||||
if (lookForward) {
|
||||
final String name1 = name;
|
||||
PsiElement run = scope;
|
||||
while (run != null) {
|
||||
class CancelException extends RuntimeException {
|
||||
}
|
||||
try {
|
||||
run.accept(new JavaRecursiveElementWalkingVisitor() {
|
||||
@Override
|
||||
public void visitAnonymousClass(final PsiAnonymousClass aClass) {
|
||||
}
|
||||
|
||||
@Override public void visitVariable(PsiVariable variable) {
|
||||
if (name1.equals(variable.getName())) {
|
||||
throw new CancelException();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (CancelException e) {
|
||||
continue NextName;
|
||||
}
|
||||
run = run.getNextSibling();
|
||||
if (scope instanceof PsiMethod) {//do not check next member for param name conflict
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public SuggestedNameInfo suggestUniqueVariableName(@NotNull final SuggestedNameInfo baseNameInfo,
|
||||
PsiElement place,
|
||||
boolean ignorePlaceName,
|
||||
boolean lookForward) {
|
||||
final String[] names = baseNameInfo.names;
|
||||
final LinkedHashSet<String> uniqueNames = new LinkedHashSet<String>(names.length);
|
||||
for (String name : names) {
|
||||
if (ignorePlaceName && place instanceof PsiNamedElement) {
|
||||
final String placeName = ((PsiNamedElement)place).getName();
|
||||
if (Comparing.strEqual(placeName, name)) {
|
||||
uniqueNames.add(name);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
uniqueNames.add(suggestUniqueVariableName(name, place, lookForward));
|
||||
}
|
||||
|
||||
return new SuggestedNameInfo(ArrayUtil.toStringArray(uniqueNames)) {
|
||||
@Override
|
||||
public void nameChosen(String name) {
|
||||
baseNameInfo.nameChosen(name);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiElement qualifyClassReferences(@NotNull PsiElement element) {
|
||||
return element;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeRedundantImports(@NotNull PsiJavaFile file) throws IncorrectOperationException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<PsiImportStatementBase> findRedundantImports(PsiJavaFile file) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,56 +1,56 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.impl;
|
||||
|
||||
import com.intellij.psi.CommonClassNames;
|
||||
import com.intellij.psi.PsiClass;
|
||||
import com.intellij.psi.PsiElement;
|
||||
import com.intellij.psi.PsiMethod;
|
||||
import com.intellij.psi.util.PsiSuperMethodUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
public class FindSuperElementsHelper {
|
||||
@Nullable
|
||||
public static PsiElement[] findSuperElements(@NotNull PsiElement element) {
|
||||
if (element instanceof PsiClass) {
|
||||
PsiClass aClass = (PsiClass) element;
|
||||
List<PsiClass> allSupers = new ArrayList<PsiClass>(Arrays.asList(aClass.getSupers()));
|
||||
for (Iterator<PsiClass> iterator = allSupers.iterator(); iterator.hasNext();) {
|
||||
PsiClass superClass = iterator.next();
|
||||
if (CommonClassNames.JAVA_LANG_OBJECT.equals(superClass.getQualifiedName())) iterator.remove();
|
||||
}
|
||||
return allSupers.toArray(new PsiClass[allSupers.size()]);
|
||||
} else if (element instanceof PsiMethod) {
|
||||
PsiMethod method = (PsiMethod) element;
|
||||
if (method.isConstructor()) {
|
||||
PsiMethod constructorInSuper = PsiSuperMethodUtil.findConstructorInSuper(method);
|
||||
if (constructorInSuper != null) {
|
||||
return new PsiMethod[]{constructorInSuper};
|
||||
}
|
||||
} else {
|
||||
return method.findSuperMethods(false);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.impl;
|
||||
|
||||
import com.intellij.psi.CommonClassNames;
|
||||
import com.intellij.psi.PsiClass;
|
||||
import com.intellij.psi.PsiElement;
|
||||
import com.intellij.psi.PsiMethod;
|
||||
import com.intellij.psi.util.PsiSuperMethodUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
public class FindSuperElementsHelper {
|
||||
@Nullable
|
||||
public static PsiElement[] findSuperElements(@NotNull PsiElement element) {
|
||||
if (element instanceof PsiClass) {
|
||||
PsiClass aClass = (PsiClass) element;
|
||||
List<PsiClass> allSupers = new ArrayList<PsiClass>(Arrays.asList(aClass.getSupers()));
|
||||
for (Iterator<PsiClass> iterator = allSupers.iterator(); iterator.hasNext();) {
|
||||
PsiClass superClass = iterator.next();
|
||||
if (CommonClassNames.JAVA_LANG_OBJECT.equals(superClass.getQualifiedName())) iterator.remove();
|
||||
}
|
||||
return allSupers.toArray(new PsiClass[allSupers.size()]);
|
||||
} else if (element instanceof PsiMethod) {
|
||||
PsiMethod method = (PsiMethod) element;
|
||||
if (method.isConstructor()) {
|
||||
PsiMethod constructorInSuper = PsiSuperMethodUtil.findConstructorInSuper(method);
|
||||
if (constructorInSuper != null) {
|
||||
return new PsiMethod[]{constructorInSuper};
|
||||
}
|
||||
} else {
|
||||
return method.findSuperMethods(false);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+401
-401
@@ -1,401 +1,401 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.impl.source.tree.java;
|
||||
|
||||
import com.intellij.openapi.util.text.StringUtil;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.impl.PsiManagerEx;
|
||||
import com.intellij.psi.impl.ResolveScopeManager;
|
||||
import com.intellij.psi.impl.source.tree.JavaElementType;
|
||||
import com.intellij.psi.impl.source.tree.LeafElement;
|
||||
import com.intellij.psi.impl.source.tree.TreeElement;
|
||||
import com.intellij.psi.impl.source.tree.injected.StringLiteralEscaper;
|
||||
import com.intellij.psi.search.GlobalSearchScope;
|
||||
import com.intellij.psi.tree.IElementType;
|
||||
import com.intellij.psi.tree.TokenSet;
|
||||
import com.intellij.util.text.LiteralFormatUtil;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class PsiLiteralExpressionImpl
|
||||
extends ExpressionPsiElement
|
||||
implements PsiLiteralExpression, PsiLanguageInjectionHost, ContributedReferenceHost {
|
||||
@NonNls private static final String QUOT = """;
|
||||
|
||||
@NonNls public static final String HEX_PREFIX = "0x";
|
||||
@NonNls public static final String BIN_PREFIX = "0b";
|
||||
@NonNls public static final String _2_IN_31 = Long.toString(-1L << 31).substring(1);
|
||||
@NonNls public static final String _2_IN_63 = Long.toString(-1L << 63).substring(1);
|
||||
public static final TokenSet INTEGER_LITERALS = TokenSet.create(JavaTokenType.INTEGER_LITERAL, JavaTokenType.LONG_LITERAL);
|
||||
public static final TokenSet REAL_LITERALS = TokenSet.create(JavaTokenType.FLOAT_LITERAL, JavaTokenType.DOUBLE_LITERAL);
|
||||
public static final TokenSet NUMERIC_LITERALS = TokenSet.orSet(INTEGER_LITERALS, REAL_LITERALS);
|
||||
|
||||
public PsiLiteralExpressionImpl() {
|
||||
super(JavaElementType.LITERAL_EXPRESSION);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiType getType() {
|
||||
final IElementType type = getLiteralElementType();
|
||||
if (type == JavaTokenType.INTEGER_LITERAL) {
|
||||
return PsiType.INT;
|
||||
}
|
||||
if (type == JavaTokenType.LONG_LITERAL) {
|
||||
return PsiType.LONG;
|
||||
}
|
||||
if (type == JavaTokenType.FLOAT_LITERAL) {
|
||||
return PsiType.FLOAT;
|
||||
}
|
||||
if (type == JavaTokenType.DOUBLE_LITERAL) {
|
||||
return PsiType.DOUBLE;
|
||||
}
|
||||
if (type == JavaTokenType.CHARACTER_LITERAL) {
|
||||
return PsiType.CHAR;
|
||||
}
|
||||
if (type == JavaTokenType.STRING_LITERAL) {
|
||||
PsiManagerEx manager = getManager();
|
||||
GlobalSearchScope resolveScope = ResolveScopeManager.getElementResolveScope(this);
|
||||
return PsiType.getJavaLangString(manager, resolveScope);
|
||||
}
|
||||
if (type == JavaTokenType.TRUE_KEYWORD || type == JavaTokenType.FALSE_KEYWORD) {
|
||||
return PsiType.BOOLEAN;
|
||||
}
|
||||
if (type == JavaTokenType.NULL_KEYWORD) {
|
||||
return PsiType.NULL;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public IElementType getLiteralElementType() {
|
||||
return getFirstChildNode().getElementType();
|
||||
}
|
||||
|
||||
public String getCanonicalText() {
|
||||
final TreeElement literal = getFirstChildNode();
|
||||
final IElementType type = literal.getElementType();
|
||||
return NUMERIC_LITERALS.contains(type) ? LiteralFormatUtil.removeUnderscores(literal.getText()) : literal.getText();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getValue() {
|
||||
final IElementType type = getLiteralElementType();
|
||||
String text = NUMERIC_LITERALS.contains(type) ? getCanonicalText().toLowerCase() : getCanonicalText();
|
||||
final int textLength = text.length();
|
||||
|
||||
if (type == JavaTokenType.INTEGER_LITERAL) {
|
||||
try {
|
||||
if (text.startsWith(HEX_PREFIX)) {
|
||||
// should fit in 32 bits
|
||||
final long value = parseDigits(text.substring(2), 4, 32);
|
||||
return Integer.valueOf((int)value);
|
||||
}
|
||||
if (text.startsWith(BIN_PREFIX)) {
|
||||
// should fit in 32 bits
|
||||
final long value = parseDigits(text.substring(2), 1, 32);
|
||||
return Integer.valueOf((int)value);
|
||||
}
|
||||
if (StringUtil.startsWithChar(text, '0')) {
|
||||
// should fit in 32 bits
|
||||
final long value = parseDigits(text, 3, 32);
|
||||
return Integer.valueOf((int)value);
|
||||
}
|
||||
final long l = Long.parseLong(text, 10);
|
||||
if (text.equals(_2_IN_31)) return Integer.valueOf((int)l);
|
||||
long converted = (int)l;
|
||||
return l == converted ? Integer.valueOf((int)l) : null;
|
||||
}
|
||||
catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (type == JavaTokenType.LONG_LITERAL) {
|
||||
if (StringUtil.endsWithChar(text, 'L') || StringUtil.endsWithChar(text, 'l')) {
|
||||
text = text.substring(0, textLength - 1);
|
||||
}
|
||||
try {
|
||||
if (text.startsWith(HEX_PREFIX)) {
|
||||
return parseDigits(text.substring(2), 4, 64);
|
||||
}
|
||||
if (text.startsWith(BIN_PREFIX)) {
|
||||
return parseDigits(text.substring(2), 1, 64);
|
||||
}
|
||||
if (StringUtil.startsWithChar(text, '0')) {
|
||||
// should fit in 64 bits
|
||||
return parseDigits(text, 3, 64);
|
||||
}
|
||||
if (_2_IN_63.equals(text)) return Long.valueOf(-1L << 63);
|
||||
return Long.valueOf(text, 10);
|
||||
}
|
||||
catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (type == JavaTokenType.FLOAT_LITERAL) {
|
||||
try {
|
||||
return Float.valueOf(text);
|
||||
}
|
||||
catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (type == JavaTokenType.DOUBLE_LITERAL) {
|
||||
try {
|
||||
return Double.valueOf(text);
|
||||
}
|
||||
catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (type == JavaTokenType.CHARACTER_LITERAL) {
|
||||
if (StringUtil.endsWithChar(text, '\'')) {
|
||||
if (textLength == 1) return null;
|
||||
text = text.substring(1, textLength - 1);
|
||||
}
|
||||
else {
|
||||
text = text.substring(1, textLength);
|
||||
}
|
||||
StringBuilder chars = new StringBuilder();
|
||||
boolean success = parseStringCharacters(text, chars, null);
|
||||
if (!success) return null;
|
||||
if (chars.length() != 1) return null;
|
||||
return Character.valueOf(chars.charAt(0));
|
||||
}
|
||||
if (type == JavaTokenType.STRING_LITERAL) {
|
||||
String innerText = getInnerText();
|
||||
return innerText == null ? null : internedParseStringCharacters(innerText);
|
||||
}
|
||||
if (type == JavaTokenType.TRUE_KEYWORD) {
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
if (type == JavaTokenType.FALSE_KEYWORD) {
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getInnerText() {
|
||||
String text = getCanonicalText();
|
||||
int textLength = text.length();
|
||||
if (StringUtil.endsWithChar(text, '\"')) {
|
||||
if (textLength == 1) return null;
|
||||
text = text.substring(1, textLength - 1);
|
||||
}
|
||||
else {
|
||||
if (text.startsWith(QUOT) && text.endsWith(QUOT) && textLength > QUOT.length()) {
|
||||
text = text.substring(QUOT.length(), textLength - QUOT.length());
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
// convert text to number according to radix specified
|
||||
// if number is more than maxBits bits long, throws NumberFormatException
|
||||
private static long parseDigits(final String text, final int bitsInRadix, final int maxBits) throws NumberFormatException {
|
||||
final int radix = 1 << bitsInRadix;
|
||||
final int textLength = text.length();
|
||||
if (textLength == 0) {
|
||||
throw new NumberFormatException(text);
|
||||
}
|
||||
long integer = textLength == 1 ? 0 : Long.parseLong(text.substring(0, textLength - 1), radix);
|
||||
if ((integer & (-1L << (maxBits - bitsInRadix))) != 0) {
|
||||
throw new NumberFormatException(text);
|
||||
}
|
||||
final int lastDigit = Character.digit(text.charAt(textLength - 1), radix);
|
||||
if (lastDigit == -1) {
|
||||
throw new NumberFormatException(text);
|
||||
}
|
||||
integer <<= bitsInRadix;
|
||||
integer |= lastDigit;
|
||||
return integer;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static String internedParseStringCharacters(final String chars) {
|
||||
final StringBuilder outChars = new StringBuilder(chars.length());
|
||||
final boolean success = parseStringCharacters(chars, outChars, null);
|
||||
return success ? outChars.toString() : null;
|
||||
}
|
||||
|
||||
public static boolean parseStringCharacters(@NotNull String chars, @NotNull StringBuilder outChars, @Nullable int[] sourceOffsets) {
|
||||
assert sourceOffsets == null || sourceOffsets.length == chars.length()+1;
|
||||
if (chars.indexOf('\\') < 0) {
|
||||
outChars.append(chars);
|
||||
if (sourceOffsets != null) {
|
||||
for (int i = 0; i < sourceOffsets.length; i++) {
|
||||
sourceOffsets[i] = i;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
int index = 0;
|
||||
final int outOffset = outChars.length();
|
||||
while (index < chars.length()) {
|
||||
char c = chars.charAt(index++);
|
||||
if (sourceOffsets != null) {
|
||||
sourceOffsets[outChars.length()-outOffset] = index - 1;
|
||||
sourceOffsets[outChars.length() + 1 -outOffset] = index;
|
||||
}
|
||||
if (c != '\\') {
|
||||
outChars.append(c);
|
||||
continue;
|
||||
}
|
||||
if (index == chars.length()) return false;
|
||||
c = chars.charAt(index++);
|
||||
switch (c) {
|
||||
case'b':
|
||||
outChars.append('\b');
|
||||
break;
|
||||
|
||||
case't':
|
||||
outChars.append('\t');
|
||||
break;
|
||||
|
||||
case'n':
|
||||
outChars.append('\n');
|
||||
break;
|
||||
|
||||
case'f':
|
||||
outChars.append('\f');
|
||||
break;
|
||||
|
||||
case'r':
|
||||
outChars.append('\r');
|
||||
break;
|
||||
|
||||
case'"':
|
||||
outChars.append('"');
|
||||
break;
|
||||
|
||||
case'\'':
|
||||
outChars.append('\'');
|
||||
break;
|
||||
|
||||
case'\\':
|
||||
outChars.append('\\');
|
||||
break;
|
||||
|
||||
case'0':
|
||||
case'1':
|
||||
case'2':
|
||||
case'3':
|
||||
case'4':
|
||||
case'5':
|
||||
case'6':
|
||||
case'7':
|
||||
char startC = c;
|
||||
int v = (int)c - '0';
|
||||
if (index < chars.length()) {
|
||||
c = chars.charAt(index++);
|
||||
if ('0' <= c && c <= '7') {
|
||||
v <<= 3;
|
||||
v += c - '0';
|
||||
if (startC <= '3' && index < chars.length()) {
|
||||
c = chars.charAt(index++);
|
||||
if ('0' <= c && c <= '7') {
|
||||
v <<= 3;
|
||||
v += c - '0';
|
||||
}
|
||||
else {
|
||||
index--;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
index--;
|
||||
}
|
||||
}
|
||||
outChars.append((char)v);
|
||||
break;
|
||||
|
||||
case'u':
|
||||
// uuuuu1234 is valid too
|
||||
while (index != chars.length() && chars.charAt(index) == 'u') {
|
||||
index++;
|
||||
}
|
||||
if (index + 4 <= chars.length()) {
|
||||
try {
|
||||
int code = Integer.parseInt(chars.substring(index, index + 4), 16);
|
||||
//line separators are invalid here
|
||||
if (code == 0x000a || code == 0x000d) return false;
|
||||
c = chars.charAt(index);
|
||||
if (c == '+' || c == '-') return false;
|
||||
outChars.append((char)code);
|
||||
index += 4;
|
||||
}
|
||||
catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
if (sourceOffsets != null) {
|
||||
sourceOffsets[outChars.length()-outOffset] = index;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(@NotNull PsiElementVisitor visitor) {
|
||||
if (visitor instanceof JavaElementVisitor) {
|
||||
((JavaElementVisitor)visitor).visitLiteralExpression(this);
|
||||
}
|
||||
else {
|
||||
visitor.visitElement(this);
|
||||
}
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "PsiLiteralExpression:" + getText();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValidHost() {
|
||||
return getValue() instanceof String;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public PsiReference[] getReferences() {
|
||||
return PsiReferenceService.getService().getContributedReferences(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiLanguageInjectionHost updateText(@NotNull final String text) {
|
||||
TreeElement valueNode = getFirstChildNode();
|
||||
assert valueNode instanceof LeafElement;
|
||||
((LeafElement)valueNode).replaceWithText(text);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public LiteralTextEscaper<PsiLiteralExpressionImpl> createLiteralTextEscaper() {
|
||||
return new StringLiteralEscaper<PsiLiteralExpressionImpl>(this);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.impl.source.tree.java;
|
||||
|
||||
import com.intellij.openapi.util.text.StringUtil;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.impl.PsiManagerEx;
|
||||
import com.intellij.psi.impl.ResolveScopeManager;
|
||||
import com.intellij.psi.impl.source.tree.JavaElementType;
|
||||
import com.intellij.psi.impl.source.tree.LeafElement;
|
||||
import com.intellij.psi.impl.source.tree.TreeElement;
|
||||
import com.intellij.psi.impl.source.tree.injected.StringLiteralEscaper;
|
||||
import com.intellij.psi.search.GlobalSearchScope;
|
||||
import com.intellij.psi.tree.IElementType;
|
||||
import com.intellij.psi.tree.TokenSet;
|
||||
import com.intellij.util.text.LiteralFormatUtil;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class PsiLiteralExpressionImpl
|
||||
extends ExpressionPsiElement
|
||||
implements PsiLiteralExpression, PsiLanguageInjectionHost, ContributedReferenceHost {
|
||||
@NonNls private static final String QUOT = """;
|
||||
|
||||
@NonNls public static final String HEX_PREFIX = "0x";
|
||||
@NonNls public static final String BIN_PREFIX = "0b";
|
||||
@NonNls public static final String _2_IN_31 = Long.toString(-1L << 31).substring(1);
|
||||
@NonNls public static final String _2_IN_63 = Long.toString(-1L << 63).substring(1);
|
||||
public static final TokenSet INTEGER_LITERALS = TokenSet.create(JavaTokenType.INTEGER_LITERAL, JavaTokenType.LONG_LITERAL);
|
||||
public static final TokenSet REAL_LITERALS = TokenSet.create(JavaTokenType.FLOAT_LITERAL, JavaTokenType.DOUBLE_LITERAL);
|
||||
public static final TokenSet NUMERIC_LITERALS = TokenSet.orSet(INTEGER_LITERALS, REAL_LITERALS);
|
||||
|
||||
public PsiLiteralExpressionImpl() {
|
||||
super(JavaElementType.LITERAL_EXPRESSION);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiType getType() {
|
||||
final IElementType type = getLiteralElementType();
|
||||
if (type == JavaTokenType.INTEGER_LITERAL) {
|
||||
return PsiType.INT;
|
||||
}
|
||||
if (type == JavaTokenType.LONG_LITERAL) {
|
||||
return PsiType.LONG;
|
||||
}
|
||||
if (type == JavaTokenType.FLOAT_LITERAL) {
|
||||
return PsiType.FLOAT;
|
||||
}
|
||||
if (type == JavaTokenType.DOUBLE_LITERAL) {
|
||||
return PsiType.DOUBLE;
|
||||
}
|
||||
if (type == JavaTokenType.CHARACTER_LITERAL) {
|
||||
return PsiType.CHAR;
|
||||
}
|
||||
if (type == JavaTokenType.STRING_LITERAL) {
|
||||
PsiManagerEx manager = getManager();
|
||||
GlobalSearchScope resolveScope = ResolveScopeManager.getElementResolveScope(this);
|
||||
return PsiType.getJavaLangString(manager, resolveScope);
|
||||
}
|
||||
if (type == JavaTokenType.TRUE_KEYWORD || type == JavaTokenType.FALSE_KEYWORD) {
|
||||
return PsiType.BOOLEAN;
|
||||
}
|
||||
if (type == JavaTokenType.NULL_KEYWORD) {
|
||||
return PsiType.NULL;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public IElementType getLiteralElementType() {
|
||||
return getFirstChildNode().getElementType();
|
||||
}
|
||||
|
||||
public String getCanonicalText() {
|
||||
final TreeElement literal = getFirstChildNode();
|
||||
final IElementType type = literal.getElementType();
|
||||
return NUMERIC_LITERALS.contains(type) ? LiteralFormatUtil.removeUnderscores(literal.getText()) : literal.getText();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getValue() {
|
||||
final IElementType type = getLiteralElementType();
|
||||
String text = NUMERIC_LITERALS.contains(type) ? getCanonicalText().toLowerCase() : getCanonicalText();
|
||||
final int textLength = text.length();
|
||||
|
||||
if (type == JavaTokenType.INTEGER_LITERAL) {
|
||||
try {
|
||||
if (text.startsWith(HEX_PREFIX)) {
|
||||
// should fit in 32 bits
|
||||
final long value = parseDigits(text.substring(2), 4, 32);
|
||||
return Integer.valueOf((int)value);
|
||||
}
|
||||
if (text.startsWith(BIN_PREFIX)) {
|
||||
// should fit in 32 bits
|
||||
final long value = parseDigits(text.substring(2), 1, 32);
|
||||
return Integer.valueOf((int)value);
|
||||
}
|
||||
if (StringUtil.startsWithChar(text, '0')) {
|
||||
// should fit in 32 bits
|
||||
final long value = parseDigits(text, 3, 32);
|
||||
return Integer.valueOf((int)value);
|
||||
}
|
||||
final long l = Long.parseLong(text, 10);
|
||||
if (text.equals(_2_IN_31)) return Integer.valueOf((int)l);
|
||||
long converted = (int)l;
|
||||
return l == converted ? Integer.valueOf((int)l) : null;
|
||||
}
|
||||
catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (type == JavaTokenType.LONG_LITERAL) {
|
||||
if (StringUtil.endsWithChar(text, 'L') || StringUtil.endsWithChar(text, 'l')) {
|
||||
text = text.substring(0, textLength - 1);
|
||||
}
|
||||
try {
|
||||
if (text.startsWith(HEX_PREFIX)) {
|
||||
return parseDigits(text.substring(2), 4, 64);
|
||||
}
|
||||
if (text.startsWith(BIN_PREFIX)) {
|
||||
return parseDigits(text.substring(2), 1, 64);
|
||||
}
|
||||
if (StringUtil.startsWithChar(text, '0')) {
|
||||
// should fit in 64 bits
|
||||
return parseDigits(text, 3, 64);
|
||||
}
|
||||
if (_2_IN_63.equals(text)) return Long.valueOf(-1L << 63);
|
||||
return Long.valueOf(text, 10);
|
||||
}
|
||||
catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (type == JavaTokenType.FLOAT_LITERAL) {
|
||||
try {
|
||||
return Float.valueOf(text);
|
||||
}
|
||||
catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (type == JavaTokenType.DOUBLE_LITERAL) {
|
||||
try {
|
||||
return Double.valueOf(text);
|
||||
}
|
||||
catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (type == JavaTokenType.CHARACTER_LITERAL) {
|
||||
if (StringUtil.endsWithChar(text, '\'')) {
|
||||
if (textLength == 1) return null;
|
||||
text = text.substring(1, textLength - 1);
|
||||
}
|
||||
else {
|
||||
text = text.substring(1, textLength);
|
||||
}
|
||||
StringBuilder chars = new StringBuilder();
|
||||
boolean success = parseStringCharacters(text, chars, null);
|
||||
if (!success) return null;
|
||||
if (chars.length() != 1) return null;
|
||||
return Character.valueOf(chars.charAt(0));
|
||||
}
|
||||
if (type == JavaTokenType.STRING_LITERAL) {
|
||||
String innerText = getInnerText();
|
||||
return innerText == null ? null : internedParseStringCharacters(innerText);
|
||||
}
|
||||
if (type == JavaTokenType.TRUE_KEYWORD) {
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
if (type == JavaTokenType.FALSE_KEYWORD) {
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getInnerText() {
|
||||
String text = getCanonicalText();
|
||||
int textLength = text.length();
|
||||
if (StringUtil.endsWithChar(text, '\"')) {
|
||||
if (textLength == 1) return null;
|
||||
text = text.substring(1, textLength - 1);
|
||||
}
|
||||
else {
|
||||
if (text.startsWith(QUOT) && text.endsWith(QUOT) && textLength > QUOT.length()) {
|
||||
text = text.substring(QUOT.length(), textLength - QUOT.length());
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
// convert text to number according to radix specified
|
||||
// if number is more than maxBits bits long, throws NumberFormatException
|
||||
private static long parseDigits(final String text, final int bitsInRadix, final int maxBits) throws NumberFormatException {
|
||||
final int radix = 1 << bitsInRadix;
|
||||
final int textLength = text.length();
|
||||
if (textLength == 0) {
|
||||
throw new NumberFormatException(text);
|
||||
}
|
||||
long integer = textLength == 1 ? 0 : Long.parseLong(text.substring(0, textLength - 1), radix);
|
||||
if ((integer & (-1L << (maxBits - bitsInRadix))) != 0) {
|
||||
throw new NumberFormatException(text);
|
||||
}
|
||||
final int lastDigit = Character.digit(text.charAt(textLength - 1), radix);
|
||||
if (lastDigit == -1) {
|
||||
throw new NumberFormatException(text);
|
||||
}
|
||||
integer <<= bitsInRadix;
|
||||
integer |= lastDigit;
|
||||
return integer;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static String internedParseStringCharacters(final String chars) {
|
||||
final StringBuilder outChars = new StringBuilder(chars.length());
|
||||
final boolean success = parseStringCharacters(chars, outChars, null);
|
||||
return success ? outChars.toString() : null;
|
||||
}
|
||||
|
||||
public static boolean parseStringCharacters(@NotNull String chars, @NotNull StringBuilder outChars, @Nullable int[] sourceOffsets) {
|
||||
assert sourceOffsets == null || sourceOffsets.length == chars.length()+1;
|
||||
if (chars.indexOf('\\') < 0) {
|
||||
outChars.append(chars);
|
||||
if (sourceOffsets != null) {
|
||||
for (int i = 0; i < sourceOffsets.length; i++) {
|
||||
sourceOffsets[i] = i;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
int index = 0;
|
||||
final int outOffset = outChars.length();
|
||||
while (index < chars.length()) {
|
||||
char c = chars.charAt(index++);
|
||||
if (sourceOffsets != null) {
|
||||
sourceOffsets[outChars.length()-outOffset] = index - 1;
|
||||
sourceOffsets[outChars.length() + 1 -outOffset] = index;
|
||||
}
|
||||
if (c != '\\') {
|
||||
outChars.append(c);
|
||||
continue;
|
||||
}
|
||||
if (index == chars.length()) return false;
|
||||
c = chars.charAt(index++);
|
||||
switch (c) {
|
||||
case'b':
|
||||
outChars.append('\b');
|
||||
break;
|
||||
|
||||
case't':
|
||||
outChars.append('\t');
|
||||
break;
|
||||
|
||||
case'n':
|
||||
outChars.append('\n');
|
||||
break;
|
||||
|
||||
case'f':
|
||||
outChars.append('\f');
|
||||
break;
|
||||
|
||||
case'r':
|
||||
outChars.append('\r');
|
||||
break;
|
||||
|
||||
case'"':
|
||||
outChars.append('"');
|
||||
break;
|
||||
|
||||
case'\'':
|
||||
outChars.append('\'');
|
||||
break;
|
||||
|
||||
case'\\':
|
||||
outChars.append('\\');
|
||||
break;
|
||||
|
||||
case'0':
|
||||
case'1':
|
||||
case'2':
|
||||
case'3':
|
||||
case'4':
|
||||
case'5':
|
||||
case'6':
|
||||
case'7':
|
||||
char startC = c;
|
||||
int v = (int)c - '0';
|
||||
if (index < chars.length()) {
|
||||
c = chars.charAt(index++);
|
||||
if ('0' <= c && c <= '7') {
|
||||
v <<= 3;
|
||||
v += c - '0';
|
||||
if (startC <= '3' && index < chars.length()) {
|
||||
c = chars.charAt(index++);
|
||||
if ('0' <= c && c <= '7') {
|
||||
v <<= 3;
|
||||
v += c - '0';
|
||||
}
|
||||
else {
|
||||
index--;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
index--;
|
||||
}
|
||||
}
|
||||
outChars.append((char)v);
|
||||
break;
|
||||
|
||||
case'u':
|
||||
// uuuuu1234 is valid too
|
||||
while (index != chars.length() && chars.charAt(index) == 'u') {
|
||||
index++;
|
||||
}
|
||||
if (index + 4 <= chars.length()) {
|
||||
try {
|
||||
int code = Integer.parseInt(chars.substring(index, index + 4), 16);
|
||||
//line separators are invalid here
|
||||
if (code == 0x000a || code == 0x000d) return false;
|
||||
c = chars.charAt(index);
|
||||
if (c == '+' || c == '-') return false;
|
||||
outChars.append((char)code);
|
||||
index += 4;
|
||||
}
|
||||
catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
if (sourceOffsets != null) {
|
||||
sourceOffsets[outChars.length()-outOffset] = index;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(@NotNull PsiElementVisitor visitor) {
|
||||
if (visitor instanceof JavaElementVisitor) {
|
||||
((JavaElementVisitor)visitor).visitLiteralExpression(this);
|
||||
}
|
||||
else {
|
||||
visitor.visitElement(this);
|
||||
}
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "PsiLiteralExpression:" + getText();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValidHost() {
|
||||
return getValue() instanceof String;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public PsiReference[] getReferences() {
|
||||
return PsiReferenceService.getService().getContributedReferences(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PsiLanguageInjectionHost updateText(@NotNull final String text) {
|
||||
TreeElement valueNode = getFirstChildNode();
|
||||
assert valueNode instanceof LeafElement;
|
||||
((LeafElement)valueNode).replaceWithText(text);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public LiteralTextEscaper<PsiLiteralExpressionImpl> createLiteralTextEscaper() {
|
||||
return new StringLiteralEscaper<PsiLiteralExpressionImpl>(this);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
public class Util {
|
||||
int goo() {
|
||||
ret<caret>cond ? 1: 0;
|
||||
}
|
||||
}
|
||||
public class Util {
|
||||
int goo() {
|
||||
ret<caret>cond ? 1: 0;
|
||||
}
|
||||
}
|
||||
|
||||
+6
-6
@@ -1,7 +1,7 @@
|
||||
class Util {
|
||||
void foox() {
|
||||
int fooy;
|
||||
foo<caret>
|
||||
}
|
||||
|
||||
class Util {
|
||||
void foox() {
|
||||
int fooy;
|
||||
foo<caret>
|
||||
}
|
||||
|
||||
}
|
||||
+16
-16
@@ -1,17 +1,17 @@
|
||||
class Foo {
|
||||
int ELXEMENT_A = 1;
|
||||
int ELXEMENT_B = 1;
|
||||
int ELXEMENT_C = 1;
|
||||
int ELXEMENT_D = 1;
|
||||
int ELXEMENT_E = 1;
|
||||
int ELXEMENT_F = 1;
|
||||
int ELXEMENT_G = 1;
|
||||
int ELXEMENT_H = 1;
|
||||
int ELXEMENT_I = 1;
|
||||
|
||||
|
||||
{
|
||||
Elx<caret>
|
||||
}
|
||||
|
||||
class Foo {
|
||||
int ELXEMENT_A = 1;
|
||||
int ELXEMENT_B = 1;
|
||||
int ELXEMENT_C = 1;
|
||||
int ELXEMENT_D = 1;
|
||||
int ELXEMENT_E = 1;
|
||||
int ELXEMENT_F = 1;
|
||||
int ELXEMENT_G = 1;
|
||||
int ELXEMENT_H = 1;
|
||||
int ELXEMENT_I = 1;
|
||||
|
||||
|
||||
{
|
||||
Elx<caret>
|
||||
}
|
||||
|
||||
}
|
||||
+4
-4
@@ -1,5 +1,5 @@
|
||||
class FooBar {
|
||||
void foo(FooBar _fooBar) {
|
||||
fb<caret>
|
||||
}
|
||||
class FooBar {
|
||||
void foo(FooBar _fooBar) {
|
||||
fb<caret>
|
||||
}
|
||||
}
|
||||
+32
-32
@@ -1,33 +1,33 @@
|
||||
class MyClass {
|
||||
public void foo() {
|
||||
MyDD<String> d = new MyDD<String>() {
|
||||
@Override
|
||||
public int hashCode() {
|
||||
<selection>return super.hashCode(); //To change body of overridden methods use File | Settings | File Templates.</selection>
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return super.equals(obj); //To change body of overridden methods use File | Settings | File Templates.
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
return super.clone(); //To change body of overridden methods use File | Settings | File Templates.
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString(); //To change body of overridden methods use File | Settings | File Templates.
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void finalize() throws Throwable {
|
||||
super.finalize(); //To change body of overridden methods use File | Settings | File Templates.
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
abstract class MyDD<T> {
|
||||
class MyClass {
|
||||
public void foo() {
|
||||
MyDD<String> d = new MyDD<String>() {
|
||||
@Override
|
||||
public int hashCode() {
|
||||
<selection>return super.hashCode(); //To change body of overridden methods use File | Settings | File Templates.</selection>
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return super.equals(obj); //To change body of overridden methods use File | Settings | File Templates.
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
return super.clone(); //To change body of overridden methods use File | Settings | File Templates.
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString(); //To change body of overridden methods use File | Settings | File Templates.
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void finalize() throws Throwable {
|
||||
super.finalize(); //To change body of overridden methods use File | Settings | File Templates.
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
abstract class MyDD<T> {
|
||||
}
|
||||
+30
-30
@@ -1,31 +1,31 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
public class Test {
|
||||
public interface Some<T> {
|
||||
T test(T p1, T p2);
|
||||
}
|
||||
|
||||
class Foo {
|
||||
public Foo create() {return null;}
|
||||
public Foo create1() {return null;}
|
||||
}
|
||||
|
||||
{
|
||||
Some<Foo> some = (i1, i2) -> {
|
||||
return i1.create();
|
||||
};
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
public class Test {
|
||||
public interface Some<T> {
|
||||
T test(T p1, T p2);
|
||||
}
|
||||
|
||||
class Foo {
|
||||
public Foo create() {return null;}
|
||||
public Foo create1() {return null;}
|
||||
}
|
||||
|
||||
{
|
||||
Some<Foo> some = (i1, i2) -> {
|
||||
return i1.create();
|
||||
};
|
||||
}
|
||||
}
|
||||
+28
-28
@@ -1,29 +1,29 @@
|
||||
interface Function<X, Y> { }
|
||||
class A {
|
||||
private static final Function<String, String> a = new Function<String, String>() {
|
||||
@Override
|
||||
public int hashCode() {
|
||||
<selection>return super.hashCode(); //To change body of overridden methods use File | Settings | File Templates.</selection>
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return super.equals(obj); //To change body of overridden methods use File | Settings | File Templates.
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
return super.clone(); //To change body of overridden methods use File | Settings | File Templates.
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString(); //To change body of overridden methods use File | Settings | File Templates.
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void finalize() throws Throwable {
|
||||
super.finalize(); //To change body of overridden methods use File | Settings | File Templates.
|
||||
}
|
||||
};
|
||||
interface Function<X, Y> { }
|
||||
class A {
|
||||
private static final Function<String, String> a = new Function<String, String>() {
|
||||
@Override
|
||||
public int hashCode() {
|
||||
<selection>return super.hashCode(); //To change body of overridden methods use File | Settings | File Templates.</selection>
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return super.equals(obj); //To change body of overridden methods use File | Settings | File Templates.
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
return super.clone(); //To change body of overridden methods use File | Settings | File Templates.
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString(); //To change body of overridden methods use File | Settings | File Templates.
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void finalize() throws Throwable {
|
||||
super.finalize(); //To change body of overridden methods use File | Settings | File Templates.
|
||||
}
|
||||
};
|
||||
}
|
||||
+7
-7
@@ -1,7 +1,7 @@
|
||||
// "Break string on '\n'" "true"
|
||||
|
||||
class A {
|
||||
String s = "Hello,\n\r" +
|
||||
"world\n" +
|
||||
"!\n";
|
||||
}
|
||||
// "Break string on '\n'" "true"
|
||||
|
||||
class A {
|
||||
String s = "Hello,\n\r" +
|
||||
"world\n" +
|
||||
"!\n";
|
||||
}
|
||||
|
||||
+5
-5
@@ -1,5 +1,5 @@
|
||||
// "Break string on '\n'" "true"
|
||||
|
||||
class A {
|
||||
String s = "Hello,\n\rwor<caret>ld\n!\n";
|
||||
}
|
||||
// "Break string on '\n'" "true"
|
||||
|
||||
class A {
|
||||
String s = "Hello,\n\rwor<caret>ld\n!\n";
|
||||
}
|
||||
|
||||
+5
-5
@@ -1,5 +1,5 @@
|
||||
// "Break string on '\n'" "false"
|
||||
|
||||
class A {
|
||||
String s = "Hello!\n";
|
||||
}
|
||||
// "Break string on '\n'" "false"
|
||||
|
||||
class A {
|
||||
String s = "Hello!\n";
|
||||
}
|
||||
|
||||
+5
-5
@@ -1,5 +1,5 @@
|
||||
// "Break string on '\n'" "false"
|
||||
|
||||
class A {
|
||||
String s = "Hello!\n\r";
|
||||
}
|
||||
// "Break string on '\n'" "false"
|
||||
|
||||
class A {
|
||||
String s = "Hello!\n\r";
|
||||
}
|
||||
|
||||
+21
-21
@@ -1,21 +1,21 @@
|
||||
// "Convert to 'new Color(0x10101)'" "true"
|
||||
|
||||
package java.awt;
|
||||
|
||||
class A {
|
||||
private Color color = new Color(0x10101);
|
||||
}
|
||||
|
||||
class Color {
|
||||
Color(int r, int g, int b) {
|
||||
}
|
||||
|
||||
Color(int r, int g, int b, int a) {
|
||||
}
|
||||
|
||||
Color(int rgb) {
|
||||
}
|
||||
|
||||
Color(int rgba, boolean hasAlpha) {
|
||||
}
|
||||
}
|
||||
// "Convert to 'new Color(0x10101)'" "true"
|
||||
|
||||
package java.awt;
|
||||
|
||||
class A {
|
||||
private Color color = new Color(0x10101);
|
||||
}
|
||||
|
||||
class Color {
|
||||
Color(int r, int g, int b) {
|
||||
}
|
||||
|
||||
Color(int r, int g, int b, int a) {
|
||||
}
|
||||
|
||||
Color(int rgb) {
|
||||
}
|
||||
|
||||
Color(int rgba, boolean hasAlpha) {
|
||||
}
|
||||
}
|
||||
|
||||
+21
-21
@@ -1,21 +1,21 @@
|
||||
// "Convert to 'new Color(0x10101)'" "true"
|
||||
|
||||
package java.awt;
|
||||
|
||||
class A {
|
||||
private Color color = new Color(257, 257,<caret> 257);
|
||||
}
|
||||
|
||||
class Color {
|
||||
Color(int r, int g, int b) {
|
||||
}
|
||||
|
||||
Color(int r, int g, int b, int a) {
|
||||
}
|
||||
|
||||
Color(int rgb) {
|
||||
}
|
||||
|
||||
Color(int rgba, boolean hasAlpha) {
|
||||
}
|
||||
}
|
||||
// "Convert to 'new Color(0x10101)'" "true"
|
||||
|
||||
package java.awt;
|
||||
|
||||
class A {
|
||||
private Color color = new Color(257, 257,<caret> 257);
|
||||
}
|
||||
|
||||
class Color {
|
||||
Color(int r, int g, int b) {
|
||||
}
|
||||
|
||||
Color(int r, int g, int b, int a) {
|
||||
}
|
||||
|
||||
Color(int rgb) {
|
||||
}
|
||||
|
||||
Color(int rgba, boolean hasAlpha) {
|
||||
}
|
||||
}
|
||||
|
||||
+269
-269
@@ -1,269 +1,269 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.JavaTestUtil;
|
||||
import com.intellij.codeInsight.lookup.LookupManager;
|
||||
import com.intellij.openapi.application.ApplicationManager;
|
||||
import com.intellij.openapi.fileEditor.FileDocumentManager;
|
||||
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
|
||||
import com.intellij.openapi.vfs.VirtualFile;
|
||||
import com.intellij.pom.java.LanguageLevel;
|
||||
import com.intellij.testFramework.TestDataPath;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@TestDataPath("$CONTENT_ROOT/testData")
|
||||
public class ClassNameCompletionTest extends LightFixtureCompletionTestCase {
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_7);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getBasePath() {
|
||||
return JavaTestUtil.getRelativeJavaTestDataPath() + "/codeInsight/completion/className/";
|
||||
}
|
||||
|
||||
public void testImportAfterNew() throws Exception {
|
||||
createClass("package pack; public class AAClass {}");
|
||||
createClass("package pack; public class WithInnerAClass{\n" +
|
||||
" public static class Inner{}\n" +
|
||||
"}");
|
||||
|
||||
String path = "/importAfterNew";
|
||||
|
||||
configureByFile(path + "/before1.java");
|
||||
checkResultByFile(path + "/after1.java");
|
||||
|
||||
configureByFile(path + "/before2.java");
|
||||
selectItem(myItems[0]);
|
||||
checkResultByFile(path + "/after2.java");
|
||||
}
|
||||
|
||||
private void createClass(String text) {
|
||||
myFixture.addClass(text);
|
||||
}
|
||||
|
||||
public void testAfterNewThrowable1() throws Exception {
|
||||
addClassesForAfterNewThrowable();
|
||||
String path = "/afterNewThrowable";
|
||||
|
||||
configureByFile(path + "/before1.java");
|
||||
myFixture.type('\n');
|
||||
checkResultByFile(path + "/after1.java");
|
||||
}
|
||||
|
||||
private void addClassesForAfterNewThrowable() throws IOException {
|
||||
createClass("public class OurException extends Throwable{}");
|
||||
createClass("public class OurNotException {\n" +
|
||||
" public static class InnerException extends Throwable{}\n" +
|
||||
" public static class InnerNonException{}\n" +
|
||||
"}");
|
||||
}
|
||||
|
||||
public void testAfterNewThrowable2() throws Exception {
|
||||
addClassesForAfterNewThrowable();
|
||||
String path = "/afterNewThrowable";
|
||||
|
||||
configureByFile(path + "/before2.java");
|
||||
myFixture.type('\n');
|
||||
checkResultByFile(path + "/after2.java");
|
||||
}
|
||||
|
||||
public void testExcessParensAfterNew() throws Exception { doTest(); }
|
||||
|
||||
public void testReuseParensAfterNew() throws Exception { doTest(); }
|
||||
|
||||
public void testBracesAfterNew() throws Exception { doTest(); }
|
||||
|
||||
public void testInPlainTextFile() throws Exception {
|
||||
configureByFile(getTestName(false) + ".txt");
|
||||
checkResultByFile(getTestName(false) + "_after.txt");
|
||||
}
|
||||
|
||||
public void testInPropertiesFile() throws Exception {
|
||||
myFixture.configureByText("a.properties", "abc = StrinBui<caret>");
|
||||
complete();
|
||||
myFixture.checkResult("abc = java.lang.StringBuilder<caret>");
|
||||
}
|
||||
|
||||
public void testDoubleStringBuffer() throws Exception {
|
||||
createClass("package java.lang; public class StringBuffer {}");
|
||||
doTest();
|
||||
assertNull(myItems);
|
||||
}
|
||||
|
||||
public void testReplaceReferenceExpressionWithTypeElement() throws Exception {
|
||||
createClass("package foo.bar; public class ABCDEF {}");
|
||||
doTest();
|
||||
}
|
||||
|
||||
public void testCamelHumpPrefix() throws Exception {
|
||||
String path = "/java/";
|
||||
configureByFile(path + getTestName(false) + ".java");
|
||||
complete();
|
||||
assertEquals(2, myItems.length);
|
||||
}
|
||||
|
||||
private void doTest() throws Exception {
|
||||
String path = "/java/";
|
||||
configureByFile(path + getTestName(false) + ".java");
|
||||
checkResultByFile(path + getTestName(false) + "_after.java");
|
||||
}
|
||||
|
||||
public void testNameCompletionJava() throws Exception {
|
||||
String path = "/nameCompletion/java";
|
||||
configureByFile(path + "/test1-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test1-result.java");
|
||||
configureByFile(path + "/test2-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test2-result.java");
|
||||
}
|
||||
|
||||
public void testImplementsFiltering1() throws Exception {
|
||||
final String path = "/nameCompletion/java";
|
||||
configureByFile(path + "/test4-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test4-result.java");
|
||||
}
|
||||
|
||||
public void testImplementsFiltering2() throws Exception {
|
||||
final String path = "/nameCompletion/java";
|
||||
configureByFile(path + "/test3-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test3-result.java");
|
||||
|
||||
configureByFile(path + "/implements2-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/implements2-result.java");
|
||||
|
||||
configureByFile(path + "/implements3-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/implements3-result.java");
|
||||
}
|
||||
|
||||
public void testAnnotationFiltering() throws Exception {
|
||||
createClass("@interface MyObjectType {}");
|
||||
|
||||
final String path = "/nameCompletion/java";
|
||||
configureByFile(path + "/test8-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test8-result.java");
|
||||
cleanupVfs();
|
||||
|
||||
configureByFile(path + "/test9-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test9-result.java");
|
||||
cleanupVfs();
|
||||
|
||||
configureByFile(path + "/test9_2-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test9_2-result.java");
|
||||
cleanupVfs();
|
||||
|
||||
configureByFile(path + "/test9_3-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test9_3-result.java");
|
||||
cleanupVfs();
|
||||
|
||||
configureByFile(path + "/test11-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test11-result.java");
|
||||
cleanupVfs();
|
||||
|
||||
configureByFile(path + "/test10-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test10-result.java");
|
||||
cleanupVfs();
|
||||
|
||||
configureByFile(path + "/test12-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test12-result.java");
|
||||
cleanupVfs();
|
||||
|
||||
configureByFile(path + "/test13-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test13-result.java");
|
||||
}
|
||||
|
||||
private void cleanupVfs() {
|
||||
ApplicationManager.getApplication().runWriteAction(new Runnable() {
|
||||
public void run() {
|
||||
FileDocumentManager.getInstance().saveAllDocuments();
|
||||
for (VirtualFile file : myFixture.getTempDirFixture().getFile("").getChildren()) {
|
||||
try {
|
||||
file.delete(this);
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void testInMethodCall() throws Exception {
|
||||
final String path = "/nameCompletion/java";
|
||||
configureByFile(path + "/methodCall-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/methodCall-result.java");
|
||||
}
|
||||
|
||||
public void testInMethodCallQualifier() throws Exception {
|
||||
final String path = "/nameCompletion/java";
|
||||
configureByFile(path + "/methodCall1-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/methodCall1-result.java");
|
||||
}
|
||||
|
||||
public void testInVariableDeclarationType() throws Exception {
|
||||
final String path = "/nameCompletion/java";
|
||||
configureByFile(path + "/varType-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/varType-result.java");
|
||||
}
|
||||
|
||||
public void testExtraSpace() throws Exception { doJavaTest(); }
|
||||
|
||||
public void testAnnotation() throws Exception { doJavaTest(); }
|
||||
|
||||
public void testInStaticImport() throws Exception { doJavaTest(); }
|
||||
|
||||
public void testInCommentWithPackagePrefix() throws Exception { doJavaTest(); }
|
||||
|
||||
private void doJavaTest() throws Exception {
|
||||
final String path = "/nameCompletion/java";
|
||||
myFixture.configureByFile(path + "/" + getTestName(false) + "-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/" + getTestName(false) + "-result.java");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void complete() {
|
||||
myItems = myFixture.complete(CompletionType.BASIC, 2);
|
||||
}
|
||||
|
||||
private void performAction() {
|
||||
complete();
|
||||
if (LookupManager.getActiveLookup(myFixture.getEditor()) != null) {
|
||||
myFixture.type('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.JavaTestUtil;
|
||||
import com.intellij.codeInsight.lookup.LookupManager;
|
||||
import com.intellij.openapi.application.ApplicationManager;
|
||||
import com.intellij.openapi.fileEditor.FileDocumentManager;
|
||||
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
|
||||
import com.intellij.openapi.vfs.VirtualFile;
|
||||
import com.intellij.pom.java.LanguageLevel;
|
||||
import com.intellij.testFramework.TestDataPath;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@TestDataPath("$CONTENT_ROOT/testData")
|
||||
public class ClassNameCompletionTest extends LightFixtureCompletionTestCase {
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_7);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getBasePath() {
|
||||
return JavaTestUtil.getRelativeJavaTestDataPath() + "/codeInsight/completion/className/";
|
||||
}
|
||||
|
||||
public void testImportAfterNew() throws Exception {
|
||||
createClass("package pack; public class AAClass {}");
|
||||
createClass("package pack; public class WithInnerAClass{\n" +
|
||||
" public static class Inner{}\n" +
|
||||
"}");
|
||||
|
||||
String path = "/importAfterNew";
|
||||
|
||||
configureByFile(path + "/before1.java");
|
||||
checkResultByFile(path + "/after1.java");
|
||||
|
||||
configureByFile(path + "/before2.java");
|
||||
selectItem(myItems[0]);
|
||||
checkResultByFile(path + "/after2.java");
|
||||
}
|
||||
|
||||
private void createClass(String text) {
|
||||
myFixture.addClass(text);
|
||||
}
|
||||
|
||||
public void testAfterNewThrowable1() throws Exception {
|
||||
addClassesForAfterNewThrowable();
|
||||
String path = "/afterNewThrowable";
|
||||
|
||||
configureByFile(path + "/before1.java");
|
||||
myFixture.type('\n');
|
||||
checkResultByFile(path + "/after1.java");
|
||||
}
|
||||
|
||||
private void addClassesForAfterNewThrowable() throws IOException {
|
||||
createClass("public class OurException extends Throwable{}");
|
||||
createClass("public class OurNotException {\n" +
|
||||
" public static class InnerException extends Throwable{}\n" +
|
||||
" public static class InnerNonException{}\n" +
|
||||
"}");
|
||||
}
|
||||
|
||||
public void testAfterNewThrowable2() throws Exception {
|
||||
addClassesForAfterNewThrowable();
|
||||
String path = "/afterNewThrowable";
|
||||
|
||||
configureByFile(path + "/before2.java");
|
||||
myFixture.type('\n');
|
||||
checkResultByFile(path + "/after2.java");
|
||||
}
|
||||
|
||||
public void testExcessParensAfterNew() throws Exception { doTest(); }
|
||||
|
||||
public void testReuseParensAfterNew() throws Exception { doTest(); }
|
||||
|
||||
public void testBracesAfterNew() throws Exception { doTest(); }
|
||||
|
||||
public void testInPlainTextFile() throws Exception {
|
||||
configureByFile(getTestName(false) + ".txt");
|
||||
checkResultByFile(getTestName(false) + "_after.txt");
|
||||
}
|
||||
|
||||
public void testInPropertiesFile() throws Exception {
|
||||
myFixture.configureByText("a.properties", "abc = StrinBui<caret>");
|
||||
complete();
|
||||
myFixture.checkResult("abc = java.lang.StringBuilder<caret>");
|
||||
}
|
||||
|
||||
public void testDoubleStringBuffer() throws Exception {
|
||||
createClass("package java.lang; public class StringBuffer {}");
|
||||
doTest();
|
||||
assertNull(myItems);
|
||||
}
|
||||
|
||||
public void testReplaceReferenceExpressionWithTypeElement() throws Exception {
|
||||
createClass("package foo.bar; public class ABCDEF {}");
|
||||
doTest();
|
||||
}
|
||||
|
||||
public void testCamelHumpPrefix() throws Exception {
|
||||
String path = "/java/";
|
||||
configureByFile(path + getTestName(false) + ".java");
|
||||
complete();
|
||||
assertEquals(2, myItems.length);
|
||||
}
|
||||
|
||||
private void doTest() throws Exception {
|
||||
String path = "/java/";
|
||||
configureByFile(path + getTestName(false) + ".java");
|
||||
checkResultByFile(path + getTestName(false) + "_after.java");
|
||||
}
|
||||
|
||||
public void testNameCompletionJava() throws Exception {
|
||||
String path = "/nameCompletion/java";
|
||||
configureByFile(path + "/test1-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test1-result.java");
|
||||
configureByFile(path + "/test2-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test2-result.java");
|
||||
}
|
||||
|
||||
public void testImplementsFiltering1() throws Exception {
|
||||
final String path = "/nameCompletion/java";
|
||||
configureByFile(path + "/test4-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test4-result.java");
|
||||
}
|
||||
|
||||
public void testImplementsFiltering2() throws Exception {
|
||||
final String path = "/nameCompletion/java";
|
||||
configureByFile(path + "/test3-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test3-result.java");
|
||||
|
||||
configureByFile(path + "/implements2-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/implements2-result.java");
|
||||
|
||||
configureByFile(path + "/implements3-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/implements3-result.java");
|
||||
}
|
||||
|
||||
public void testAnnotationFiltering() throws Exception {
|
||||
createClass("@interface MyObjectType {}");
|
||||
|
||||
final String path = "/nameCompletion/java";
|
||||
configureByFile(path + "/test8-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test8-result.java");
|
||||
cleanupVfs();
|
||||
|
||||
configureByFile(path + "/test9-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test9-result.java");
|
||||
cleanupVfs();
|
||||
|
||||
configureByFile(path + "/test9_2-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test9_2-result.java");
|
||||
cleanupVfs();
|
||||
|
||||
configureByFile(path + "/test9_3-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test9_3-result.java");
|
||||
cleanupVfs();
|
||||
|
||||
configureByFile(path + "/test11-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test11-result.java");
|
||||
cleanupVfs();
|
||||
|
||||
configureByFile(path + "/test10-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test10-result.java");
|
||||
cleanupVfs();
|
||||
|
||||
configureByFile(path + "/test12-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test12-result.java");
|
||||
cleanupVfs();
|
||||
|
||||
configureByFile(path + "/test13-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/test13-result.java");
|
||||
}
|
||||
|
||||
private void cleanupVfs() {
|
||||
ApplicationManager.getApplication().runWriteAction(new Runnable() {
|
||||
public void run() {
|
||||
FileDocumentManager.getInstance().saveAllDocuments();
|
||||
for (VirtualFile file : myFixture.getTempDirFixture().getFile("").getChildren()) {
|
||||
try {
|
||||
file.delete(this);
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void testInMethodCall() throws Exception {
|
||||
final String path = "/nameCompletion/java";
|
||||
configureByFile(path + "/methodCall-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/methodCall-result.java");
|
||||
}
|
||||
|
||||
public void testInMethodCallQualifier() throws Exception {
|
||||
final String path = "/nameCompletion/java";
|
||||
configureByFile(path + "/methodCall1-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/methodCall1-result.java");
|
||||
}
|
||||
|
||||
public void testInVariableDeclarationType() throws Exception {
|
||||
final String path = "/nameCompletion/java";
|
||||
configureByFile(path + "/varType-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/varType-result.java");
|
||||
}
|
||||
|
||||
public void testExtraSpace() throws Exception { doJavaTest(); }
|
||||
|
||||
public void testAnnotation() throws Exception { doJavaTest(); }
|
||||
|
||||
public void testInStaticImport() throws Exception { doJavaTest(); }
|
||||
|
||||
public void testInCommentWithPackagePrefix() throws Exception { doJavaTest(); }
|
||||
|
||||
private void doJavaTest() throws Exception {
|
||||
final String path = "/nameCompletion/java";
|
||||
myFixture.configureByFile(path + "/" + getTestName(false) + "-source.java");
|
||||
performAction();
|
||||
checkResultByFile(path + "/" + getTestName(false) + "-result.java");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void complete() {
|
||||
myItems = myFixture.complete(CompletionType.BASIC, 2);
|
||||
}
|
||||
|
||||
private void performAction() {
|
||||
complete();
|
||||
if (LookupManager.getActiveLookup(myFixture.getEditor()) != null) {
|
||||
myFixture.type('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+82
-82
@@ -1,82 +1,82 @@
|
||||
/*
|
||||
* Copyright (c) 2000-2005 by JetBrains s.r.o. All Rights Reserved.
|
||||
* Use is subject to license terms.
|
||||
*/
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.codeInsight.CodeInsightSettings;
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
import com.intellij.codeInsight.lookup.LookupManager;
|
||||
import com.intellij.codeInsight.lookup.impl.LookupImpl;
|
||||
import com.intellij.ide.ui.UISettings;
|
||||
import com.intellij.psi.statistics.StatisticsManager;
|
||||
import com.intellij.psi.statistics.impl.StatisticsManagerImpl;
|
||||
import com.intellij.testFramework.TestDataPath;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
@TestDataPath("$CONTENT_ROOT/testData")
|
||||
public abstract class CompletionSortingTestCase extends LightFixtureCompletionTestCase {
|
||||
private final CompletionType myType;
|
||||
|
||||
@SuppressWarnings({"JUnitTestCaseWithNonTrivialConstructors"})
|
||||
protected CompletionSortingTestCase(CompletionType type) {
|
||||
myType = type;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
((StatisticsManagerImpl)StatisticsManager.getInstance()).enableStatistics(getTestRootDisposable());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
LookupManager.getInstance(getProject()).hideActiveLookup();
|
||||
UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = false;
|
||||
CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = CodeInsightSettings.FIRST_LETTER;
|
||||
super.tearDown();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected abstract String getBasePath();
|
||||
|
||||
protected void checkPreferredItems(final int selected, @NonNls final String... expected) {
|
||||
invokeCompletion(getTestName(false) + ".java");
|
||||
assertPreferredItems(selected, expected);
|
||||
}
|
||||
|
||||
protected void assertPreferredItems(final int selected, @NonNls final String... expected) {
|
||||
myFixture.assertPreferredCompletionItems(selected, expected);
|
||||
}
|
||||
|
||||
protected LookupImpl invokeCompletion(final String path) {
|
||||
configureNoCompletion(path);
|
||||
myFixture.complete(myType);
|
||||
return getLookup();
|
||||
}
|
||||
|
||||
protected void configureNoCompletion(String path) {
|
||||
myFixture.configureFromExistingVirtualFile(
|
||||
myFixture.copyFileToProject(path, com.intellij.openapi.util.text.StringUtil.getShortName(path, '/')));
|
||||
}
|
||||
|
||||
protected static void incUseCount(final LookupImpl lookup, final int index) {
|
||||
imitateItemSelection(lookup, index);
|
||||
refreshSorting(lookup);
|
||||
}
|
||||
|
||||
protected static void refreshSorting(final LookupImpl lookup) {
|
||||
lookup.setSelectionTouched(false);
|
||||
lookup.resort(true);
|
||||
}
|
||||
|
||||
protected static void imitateItemSelection(final LookupImpl lookup, final int index) {
|
||||
final LookupElement item = lookup.getItems().get(index);
|
||||
lookup.setCurrentItem(item);
|
||||
CompletionLookupArranger.collectStatisticChanges(item, lookup);
|
||||
CompletionLookupArranger.applyLastCompletionStatisticsUpdate();
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright (c) 2000-2005 by JetBrains s.r.o. All Rights Reserved.
|
||||
* Use is subject to license terms.
|
||||
*/
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.codeInsight.CodeInsightSettings;
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
import com.intellij.codeInsight.lookup.LookupManager;
|
||||
import com.intellij.codeInsight.lookup.impl.LookupImpl;
|
||||
import com.intellij.ide.ui.UISettings;
|
||||
import com.intellij.psi.statistics.StatisticsManager;
|
||||
import com.intellij.psi.statistics.impl.StatisticsManagerImpl;
|
||||
import com.intellij.testFramework.TestDataPath;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
@TestDataPath("$CONTENT_ROOT/testData")
|
||||
public abstract class CompletionSortingTestCase extends LightFixtureCompletionTestCase {
|
||||
private final CompletionType myType;
|
||||
|
||||
@SuppressWarnings({"JUnitTestCaseWithNonTrivialConstructors"})
|
||||
protected CompletionSortingTestCase(CompletionType type) {
|
||||
myType = type;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
((StatisticsManagerImpl)StatisticsManager.getInstance()).enableStatistics(getTestRootDisposable());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
LookupManager.getInstance(getProject()).hideActiveLookup();
|
||||
UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = false;
|
||||
CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = CodeInsightSettings.FIRST_LETTER;
|
||||
super.tearDown();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected abstract String getBasePath();
|
||||
|
||||
protected void checkPreferredItems(final int selected, @NonNls final String... expected) {
|
||||
invokeCompletion(getTestName(false) + ".java");
|
||||
assertPreferredItems(selected, expected);
|
||||
}
|
||||
|
||||
protected void assertPreferredItems(final int selected, @NonNls final String... expected) {
|
||||
myFixture.assertPreferredCompletionItems(selected, expected);
|
||||
}
|
||||
|
||||
protected LookupImpl invokeCompletion(final String path) {
|
||||
configureNoCompletion(path);
|
||||
myFixture.complete(myType);
|
||||
return getLookup();
|
||||
}
|
||||
|
||||
protected void configureNoCompletion(String path) {
|
||||
myFixture.configureFromExistingVirtualFile(
|
||||
myFixture.copyFileToProject(path, com.intellij.openapi.util.text.StringUtil.getShortName(path, '/')));
|
||||
}
|
||||
|
||||
protected static void incUseCount(final LookupImpl lookup, final int index) {
|
||||
imitateItemSelection(lookup, index);
|
||||
refreshSorting(lookup);
|
||||
}
|
||||
|
||||
protected static void refreshSorting(final LookupImpl lookup) {
|
||||
lookup.setSelectionTouched(false);
|
||||
lookup.resort(true);
|
||||
}
|
||||
|
||||
protected static void imitateItemSelection(final LookupImpl lookup, final int index) {
|
||||
final LookupElement item = lookup.getItems().get(index);
|
||||
lookup.setCurrentItem(item);
|
||||
CompletionLookupArranger.collectStatisticChanges(item, lookup);
|
||||
CompletionLookupArranger.applyLastCompletionStatisticsUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
+211
-211
@@ -1,211 +1,211 @@
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
|
||||
import com.intellij.codeInsight.CodeInsightSettings
|
||||
import com.intellij.util.ArrayUtil
|
||||
import com.intellij.codeInsight.lookup.LookupElementPresentation
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public class GlobalMemberNameCompletionTest extends LightCodeInsightFixtureTestCase {
|
||||
|
||||
public void testMethodName() throws Exception {
|
||||
myFixture.addClass("""
|
||||
package foo;
|
||||
|
||||
public class Foo {
|
||||
public static int abcmethod() {}
|
||||
static void methodThatsNotVisible() {}
|
||||
}
|
||||
""")
|
||||
|
||||
doTest "class Bar {{ abcm<caret> }}", true, """import static foo.Foo.abcmethod;
|
||||
|
||||
class Bar {{ abcmethod()<caret> }}"""
|
||||
}
|
||||
|
||||
public void testFieldName() throws Exception {
|
||||
myFixture.addClass("""
|
||||
package foo;
|
||||
|
||||
public class Foo {
|
||||
public static int abcfield = 2
|
||||
static final int fieldThatsNotVisible = 3
|
||||
}
|
||||
""")
|
||||
|
||||
doTest "class Bar {{ abcf<caret> }}", true, """import static foo.Foo.abcfield;
|
||||
|
||||
class Bar {{ abcfield<caret> }}"""
|
||||
}
|
||||
|
||||
public void testFieldNameQualified() throws Exception {
|
||||
myFixture.addClass("""
|
||||
package foo;
|
||||
|
||||
public class Foo {
|
||||
public static int abcfield = 2
|
||||
static final int fieldThatsNotVisible = 3
|
||||
}
|
||||
""")
|
||||
|
||||
doTest "class Bar {{ abcf<caret> }}", false, """import foo.Foo;
|
||||
|
||||
class Bar {{ Foo.abcfield<caret> }}"""
|
||||
}
|
||||
|
||||
public void testFieldNamePresentation() {
|
||||
myFixture.addClass("""
|
||||
package foo;
|
||||
|
||||
public class Foo {
|
||||
public static int abcfield = 2
|
||||
static final int fieldThatsNotVisible = 3
|
||||
}
|
||||
""")
|
||||
myFixture.configureByText "a.java", "class Bar {{ abcf<caret> }}"
|
||||
def element = complete()[0]
|
||||
def presentation = LookupElementPresentation.renderElement(element)
|
||||
assert 'Foo.abcfield' == presentation.itemText
|
||||
assert ' (foo)' == presentation.tailText
|
||||
assert 'int' == presentation.typeText
|
||||
}
|
||||
|
||||
private LookupElement[] complete() {
|
||||
myFixture.complete(CompletionType.BASIC, 2)
|
||||
}
|
||||
|
||||
public void testQualifiedMethodName() throws Exception {
|
||||
myFixture.addClass("""
|
||||
package foo;
|
||||
|
||||
public class Foo {
|
||||
public static int abcmethod() {}
|
||||
}
|
||||
""")
|
||||
|
||||
doTest "class Bar {{ abcm<caret> }}", false, """import foo.Foo;
|
||||
|
||||
class Bar {{ Foo.abcmethod()<caret> }}"""
|
||||
}
|
||||
|
||||
public void testIfThereAreAlreadyStaticImportsWithThatClass() throws Exception {
|
||||
myFixture.addClass("""
|
||||
package foo;
|
||||
|
||||
public class Foo {
|
||||
public static int anotherMethod(int a) {}
|
||||
public static int abcmethod() {}
|
||||
void methodThatsNotVisible() {}
|
||||
}
|
||||
""")
|
||||
|
||||
doTest """import static foo.Foo.abcmethod;
|
||||
|
||||
class Bar {{ abcmethod(); anoMe<caret> }}""", false,
|
||||
"""import static foo.Foo.abcmethod;
|
||||
import static foo.Foo.anotherMethod;
|
||||
|
||||
class Bar {{ abcmethod(); anotherMethod(<caret>) }}"""
|
||||
}
|
||||
|
||||
|
||||
@Override protected void tearDown() {
|
||||
CodeInsightSettings.instance.EXCLUDED_PACKAGES = ArrayUtil.EMPTY_STRING_ARRAY
|
||||
super.tearDown()
|
||||
}
|
||||
|
||||
public void testExcludeClassFromCompletion() throws Exception {
|
||||
myFixture.addClass("""package foo;
|
||||
public class Foo {
|
||||
public static int abcmethod() {}
|
||||
}
|
||||
""")
|
||||
myFixture.addClass("""package foo;
|
||||
public class Excl {
|
||||
public static int abcmethod2() {}
|
||||
}
|
||||
""")
|
||||
|
||||
CodeInsightSettings.instance.EXCLUDED_PACKAGES = ["foo.Excl"] as String[]
|
||||
|
||||
doTest "class Bar {{ abcm<caret> }}", true, """import static foo.Foo.abcmethod;
|
||||
|
||||
class Bar {{ abcmethod()<caret> }}"""
|
||||
}
|
||||
|
||||
public void testExcludeMethodFromCompletion() throws Exception {
|
||||
myFixture.addClass("""package foo;
|
||||
public class Foo {
|
||||
public static int abcmethod1() {}
|
||||
public static int abcmethodExcluded() {}
|
||||
}
|
||||
""")
|
||||
|
||||
CodeInsightSettings.instance.EXCLUDED_PACKAGES = ["foo.Foo.abcmethodExcluded"] as String[]
|
||||
|
||||
doTest "class Bar {{ abcm<caret> }}", true, """import static foo.Foo.abcmethod1;
|
||||
|
||||
class Bar {{ abcmethod1()<caret> }}"""
|
||||
}
|
||||
|
||||
public void testMergeOverloads() throws Exception {
|
||||
myFixture.addClass("""package foo;
|
||||
public class Foo {
|
||||
public static int abcmethod(int a) {}
|
||||
public static int abcmethod(boolean a) {}
|
||||
public static int abcmethod1(boolean a) {}
|
||||
}
|
||||
""")
|
||||
|
||||
myFixture.configureByText("a.java", "class Bar {{ abcm<caret> }}")
|
||||
def element = complete()[0]
|
||||
|
||||
def tail = LookupElementPresentation.renderElement(element).tailFragments
|
||||
assert tail[0].text == '(...)'
|
||||
assert !tail[0].grayed
|
||||
assert tail[1].text == ' (foo)'
|
||||
assert tail[1].grayed
|
||||
|
||||
assertOrderedEquals myFixture.lookupElementStrings, "abcmethod", "abcmethod1"
|
||||
}
|
||||
|
||||
public void testMethodFromTheSameClass() {
|
||||
myFixture.configureByText("a.java", """
|
||||
class A {
|
||||
static void foo() {}
|
||||
|
||||
static void goo() {
|
||||
f<caret>
|
||||
}
|
||||
}
|
||||
""")
|
||||
def element = complete()[0]
|
||||
def presentation = LookupElementPresentation.renderElement(element)
|
||||
assert 'foo' == presentation.itemText
|
||||
myFixture.type '\n'
|
||||
myFixture.checkResult '''
|
||||
class A {
|
||||
static void foo() {}
|
||||
|
||||
static void goo() {
|
||||
foo();<caret>
|
||||
}
|
||||
}
|
||||
'''
|
||||
}
|
||||
|
||||
private void doTest(String input, boolean importStatic, String output) {
|
||||
myFixture.configureByText("a.java", input)
|
||||
|
||||
def item = assertOneElement(complete())
|
||||
if (importStatic) {
|
||||
item.'as'(StaticallyImportable).shouldBeImported = true
|
||||
}
|
||||
myFixture.type('\n')
|
||||
myFixture.checkResult output
|
||||
}
|
||||
|
||||
}
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
|
||||
import com.intellij.codeInsight.CodeInsightSettings
|
||||
import com.intellij.util.ArrayUtil
|
||||
import com.intellij.codeInsight.lookup.LookupElementPresentation
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public class GlobalMemberNameCompletionTest extends LightCodeInsightFixtureTestCase {
|
||||
|
||||
public void testMethodName() throws Exception {
|
||||
myFixture.addClass("""
|
||||
package foo;
|
||||
|
||||
public class Foo {
|
||||
public static int abcmethod() {}
|
||||
static void methodThatsNotVisible() {}
|
||||
}
|
||||
""")
|
||||
|
||||
doTest "class Bar {{ abcm<caret> }}", true, """import static foo.Foo.abcmethod;
|
||||
|
||||
class Bar {{ abcmethod()<caret> }}"""
|
||||
}
|
||||
|
||||
public void testFieldName() throws Exception {
|
||||
myFixture.addClass("""
|
||||
package foo;
|
||||
|
||||
public class Foo {
|
||||
public static int abcfield = 2
|
||||
static final int fieldThatsNotVisible = 3
|
||||
}
|
||||
""")
|
||||
|
||||
doTest "class Bar {{ abcf<caret> }}", true, """import static foo.Foo.abcfield;
|
||||
|
||||
class Bar {{ abcfield<caret> }}"""
|
||||
}
|
||||
|
||||
public void testFieldNameQualified() throws Exception {
|
||||
myFixture.addClass("""
|
||||
package foo;
|
||||
|
||||
public class Foo {
|
||||
public static int abcfield = 2
|
||||
static final int fieldThatsNotVisible = 3
|
||||
}
|
||||
""")
|
||||
|
||||
doTest "class Bar {{ abcf<caret> }}", false, """import foo.Foo;
|
||||
|
||||
class Bar {{ Foo.abcfield<caret> }}"""
|
||||
}
|
||||
|
||||
public void testFieldNamePresentation() {
|
||||
myFixture.addClass("""
|
||||
package foo;
|
||||
|
||||
public class Foo {
|
||||
public static int abcfield = 2
|
||||
static final int fieldThatsNotVisible = 3
|
||||
}
|
||||
""")
|
||||
myFixture.configureByText "a.java", "class Bar {{ abcf<caret> }}"
|
||||
def element = complete()[0]
|
||||
def presentation = LookupElementPresentation.renderElement(element)
|
||||
assert 'Foo.abcfield' == presentation.itemText
|
||||
assert ' (foo)' == presentation.tailText
|
||||
assert 'int' == presentation.typeText
|
||||
}
|
||||
|
||||
private LookupElement[] complete() {
|
||||
myFixture.complete(CompletionType.BASIC, 2)
|
||||
}
|
||||
|
||||
public void testQualifiedMethodName() throws Exception {
|
||||
myFixture.addClass("""
|
||||
package foo;
|
||||
|
||||
public class Foo {
|
||||
public static int abcmethod() {}
|
||||
}
|
||||
""")
|
||||
|
||||
doTest "class Bar {{ abcm<caret> }}", false, """import foo.Foo;
|
||||
|
||||
class Bar {{ Foo.abcmethod()<caret> }}"""
|
||||
}
|
||||
|
||||
public void testIfThereAreAlreadyStaticImportsWithThatClass() throws Exception {
|
||||
myFixture.addClass("""
|
||||
package foo;
|
||||
|
||||
public class Foo {
|
||||
public static int anotherMethod(int a) {}
|
||||
public static int abcmethod() {}
|
||||
void methodThatsNotVisible() {}
|
||||
}
|
||||
""")
|
||||
|
||||
doTest """import static foo.Foo.abcmethod;
|
||||
|
||||
class Bar {{ abcmethod(); anoMe<caret> }}""", false,
|
||||
"""import static foo.Foo.abcmethod;
|
||||
import static foo.Foo.anotherMethod;
|
||||
|
||||
class Bar {{ abcmethod(); anotherMethod(<caret>) }}"""
|
||||
}
|
||||
|
||||
|
||||
@Override protected void tearDown() {
|
||||
CodeInsightSettings.instance.EXCLUDED_PACKAGES = ArrayUtil.EMPTY_STRING_ARRAY
|
||||
super.tearDown()
|
||||
}
|
||||
|
||||
public void testExcludeClassFromCompletion() throws Exception {
|
||||
myFixture.addClass("""package foo;
|
||||
public class Foo {
|
||||
public static int abcmethod() {}
|
||||
}
|
||||
""")
|
||||
myFixture.addClass("""package foo;
|
||||
public class Excl {
|
||||
public static int abcmethod2() {}
|
||||
}
|
||||
""")
|
||||
|
||||
CodeInsightSettings.instance.EXCLUDED_PACKAGES = ["foo.Excl"] as String[]
|
||||
|
||||
doTest "class Bar {{ abcm<caret> }}", true, """import static foo.Foo.abcmethod;
|
||||
|
||||
class Bar {{ abcmethod()<caret> }}"""
|
||||
}
|
||||
|
||||
public void testExcludeMethodFromCompletion() throws Exception {
|
||||
myFixture.addClass("""package foo;
|
||||
public class Foo {
|
||||
public static int abcmethod1() {}
|
||||
public static int abcmethodExcluded() {}
|
||||
}
|
||||
""")
|
||||
|
||||
CodeInsightSettings.instance.EXCLUDED_PACKAGES = ["foo.Foo.abcmethodExcluded"] as String[]
|
||||
|
||||
doTest "class Bar {{ abcm<caret> }}", true, """import static foo.Foo.abcmethod1;
|
||||
|
||||
class Bar {{ abcmethod1()<caret> }}"""
|
||||
}
|
||||
|
||||
public void testMergeOverloads() throws Exception {
|
||||
myFixture.addClass("""package foo;
|
||||
public class Foo {
|
||||
public static int abcmethod(int a) {}
|
||||
public static int abcmethod(boolean a) {}
|
||||
public static int abcmethod1(boolean a) {}
|
||||
}
|
||||
""")
|
||||
|
||||
myFixture.configureByText("a.java", "class Bar {{ abcm<caret> }}")
|
||||
def element = complete()[0]
|
||||
|
||||
def tail = LookupElementPresentation.renderElement(element).tailFragments
|
||||
assert tail[0].text == '(...)'
|
||||
assert !tail[0].grayed
|
||||
assert tail[1].text == ' (foo)'
|
||||
assert tail[1].grayed
|
||||
|
||||
assertOrderedEquals myFixture.lookupElementStrings, "abcmethod", "abcmethod1"
|
||||
}
|
||||
|
||||
public void testMethodFromTheSameClass() {
|
||||
myFixture.configureByText("a.java", """
|
||||
class A {
|
||||
static void foo() {}
|
||||
|
||||
static void goo() {
|
||||
f<caret>
|
||||
}
|
||||
}
|
||||
""")
|
||||
def element = complete()[0]
|
||||
def presentation = LookupElementPresentation.renderElement(element)
|
||||
assert 'foo' == presentation.itemText
|
||||
myFixture.type '\n'
|
||||
myFixture.checkResult '''
|
||||
class A {
|
||||
static void foo() {}
|
||||
|
||||
static void goo() {
|
||||
foo();<caret>
|
||||
}
|
||||
}
|
||||
'''
|
||||
}
|
||||
|
||||
private void doTest(String input, boolean importStatic, String output) {
|
||||
myFixture.configureByText("a.java", input)
|
||||
|
||||
def item = assertOneElement(complete())
|
||||
if (importStatic) {
|
||||
item.'as'(StaticallyImportable).shouldBeImported = true
|
||||
}
|
||||
myFixture.type('\n')
|
||||
myFixture.checkResult output
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+113
-113
@@ -1,113 +1,113 @@
|
||||
/*
|
||||
* Copyright (c) 2000-2005 by JetBrains s.r.o. All Rights Reserved.
|
||||
* Use is subject to license terms.
|
||||
*/
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.JavaTestUtil;
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
import com.intellij.codeInsight.lookup.LookupManager;
|
||||
import com.intellij.codeInsight.lookup.impl.LookupImpl;
|
||||
import com.intellij.openapi.command.WriteCommandAction;
|
||||
import com.intellij.openapi.module.StdModuleTypes;
|
||||
import com.intellij.openapi.roots.ContentEntry;
|
||||
import com.intellij.openapi.roots.ModifiableRootModel;
|
||||
import com.intellij.openapi.roots.ModuleRootManager;
|
||||
import com.intellij.openapi.roots.SourceFolder;
|
||||
import com.intellij.openapi.vfs.LocalFileSystem;
|
||||
import com.intellij.openapi.vfs.VirtualFile;
|
||||
import com.intellij.psi.JavaPsiFacade;
|
||||
import com.intellij.testFramework.PsiTestUtil;
|
||||
import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public class HeavyNormalCompletionTest extends JavaCodeInsightFixtureTestCase {
|
||||
|
||||
@Override
|
||||
protected String getTestDataPath() {
|
||||
return JavaTestUtil.getJavaTestDataPath();
|
||||
}
|
||||
|
||||
public void testPackagePrefix() throws Throwable {
|
||||
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
|
||||
new WriteCommandAction.Simple(getProject()) {
|
||||
@Override
|
||||
protected void run() throws Throwable {
|
||||
final ModifiableRootModel model = ModuleRootManager.getInstance(myFixture.getModule()).getModifiableModel();
|
||||
model.getContentEntries()[0].getSourceFolders()[0].setPackagePrefix("foo.bar.goo");
|
||||
model.commit();
|
||||
}
|
||||
}.execute().throwException();
|
||||
|
||||
myFixture.completeBasic();
|
||||
myFixture.checkResultByFile("/codeInsight/completion/normal/" + getTestName(false) + "_after.java");
|
||||
assertTrue(JavaPsiFacade.getInstance(getProject()).findPackage("foo").isValid());
|
||||
assertTrue(JavaPsiFacade.getInstance(getProject()).findPackage("foo.bar").isValid());
|
||||
assertTrue(JavaPsiFacade.getInstance(getProject()).findPackage("foo.bar.goo").isValid());
|
||||
}
|
||||
|
||||
public void testPreferTestCases() throws Throwable {
|
||||
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
|
||||
new WriteCommandAction.Simple(getProject()) {
|
||||
@Override
|
||||
protected void run() throws Throwable {
|
||||
final ModifiableRootModel model = ModuleRootManager.getInstance(myFixture.getModule()).getModifiableModel();
|
||||
ContentEntry contentEntry = model.getContentEntries()[0];
|
||||
SourceFolder sourceFolder = contentEntry.getSourceFolders()[0];
|
||||
VirtualFile file = sourceFolder.getFile();
|
||||
contentEntry.removeSourceFolder(sourceFolder);
|
||||
contentEntry.addSourceFolder(file, true);
|
||||
model.commit();
|
||||
}
|
||||
}.execute().throwException();
|
||||
|
||||
myFixture.addClass("package foo; public class SomeTestCase {}");
|
||||
myFixture.addClass("package bar; public class SomeTestec {}");
|
||||
myFixture.addClass("package goo; public class SomeAnchor {}");
|
||||
|
||||
myFixture.completeBasic();
|
||||
myFixture.assertPreferredCompletionItems(0, "SomeTestCase", "SomeAnchor", "SomeTestec");
|
||||
}
|
||||
|
||||
public void testAllClassesWhenNothingIsFound() throws Throwable {
|
||||
myFixture.addClass("package foo.bar; public class AxBxCxDxEx {}");
|
||||
|
||||
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
|
||||
myFixture.completeBasic();
|
||||
myFixture.type('\n');
|
||||
myFixture.checkResultByFile("/codeInsight/completion/normal/" + getTestName(false) + "_after.java");
|
||||
}
|
||||
|
||||
public void testAllClassesOnSecondBasicCompletion() throws Throwable {
|
||||
myFixture.addClass("package foo.bar; public class AxBxCxDxEx {}");
|
||||
|
||||
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
|
||||
myFixture.complete(CompletionType.BASIC, 2);
|
||||
LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myFixture.getEditor());
|
||||
LookupElement[] myItems = lookup.getItems().toArray(LookupElement.EMPTY_ARRAY);
|
||||
assertEquals(2, myItems.length);
|
||||
assertEquals("AxBxCxDxEx", myItems[1].getLookupString());
|
||||
assertEquals("AyByCyDyEy", myItems[0].getLookupString());
|
||||
}
|
||||
|
||||
public void testMapsInvalidation() throws Exception {
|
||||
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
|
||||
assertInstanceOf(myFixture.getFile().getVirtualFile().getFileSystem(), LocalFileSystem.class); // otherwise the completion copy won't be preserved which is critical here
|
||||
myFixture.completeBasic();
|
||||
assertOrderedEquals(myFixture.getLookupElementStrings(), "getAaa", "getBbb");
|
||||
myFixture.getEditor().getCaretModel().moveToOffset(myFixture.getEditor().getCaretModel().getOffset() + 2);
|
||||
assertNull(myFixture.completeBasic());
|
||||
}
|
||||
|
||||
public void testQualifyInaccessibleClassName() throws Exception {
|
||||
PsiTestUtil.addModule(getProject(), StdModuleTypes.JAVA, "second", myFixture.getTempDirFixture().findOrCreateDir("second"));
|
||||
myFixture.addFileToProject("second/foo/bar/AxBxCxDxEx.java", "package foo.bar; class AxBxCxDxEx {}");
|
||||
|
||||
myFixture.configureByText("a.java", "class Main { ABCDE<caret> }");
|
||||
myFixture.complete(CompletionType.BASIC, 3);
|
||||
myFixture.checkResult("class Main { foo.bar.AxBxCxDxEx<caret> }");
|
||||
}
|
||||
|
||||
}
|
||||
/*
|
||||
* Copyright (c) 2000-2005 by JetBrains s.r.o. All Rights Reserved.
|
||||
* Use is subject to license terms.
|
||||
*/
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.JavaTestUtil;
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
import com.intellij.codeInsight.lookup.LookupManager;
|
||||
import com.intellij.codeInsight.lookup.impl.LookupImpl;
|
||||
import com.intellij.openapi.command.WriteCommandAction;
|
||||
import com.intellij.openapi.module.StdModuleTypes;
|
||||
import com.intellij.openapi.roots.ContentEntry;
|
||||
import com.intellij.openapi.roots.ModifiableRootModel;
|
||||
import com.intellij.openapi.roots.ModuleRootManager;
|
||||
import com.intellij.openapi.roots.SourceFolder;
|
||||
import com.intellij.openapi.vfs.LocalFileSystem;
|
||||
import com.intellij.openapi.vfs.VirtualFile;
|
||||
import com.intellij.psi.JavaPsiFacade;
|
||||
import com.intellij.testFramework.PsiTestUtil;
|
||||
import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public class HeavyNormalCompletionTest extends JavaCodeInsightFixtureTestCase {
|
||||
|
||||
@Override
|
||||
protected String getTestDataPath() {
|
||||
return JavaTestUtil.getJavaTestDataPath();
|
||||
}
|
||||
|
||||
public void testPackagePrefix() throws Throwable {
|
||||
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
|
||||
new WriteCommandAction.Simple(getProject()) {
|
||||
@Override
|
||||
protected void run() throws Throwable {
|
||||
final ModifiableRootModel model = ModuleRootManager.getInstance(myFixture.getModule()).getModifiableModel();
|
||||
model.getContentEntries()[0].getSourceFolders()[0].setPackagePrefix("foo.bar.goo");
|
||||
model.commit();
|
||||
}
|
||||
}.execute().throwException();
|
||||
|
||||
myFixture.completeBasic();
|
||||
myFixture.checkResultByFile("/codeInsight/completion/normal/" + getTestName(false) + "_after.java");
|
||||
assertTrue(JavaPsiFacade.getInstance(getProject()).findPackage("foo").isValid());
|
||||
assertTrue(JavaPsiFacade.getInstance(getProject()).findPackage("foo.bar").isValid());
|
||||
assertTrue(JavaPsiFacade.getInstance(getProject()).findPackage("foo.bar.goo").isValid());
|
||||
}
|
||||
|
||||
public void testPreferTestCases() throws Throwable {
|
||||
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
|
||||
new WriteCommandAction.Simple(getProject()) {
|
||||
@Override
|
||||
protected void run() throws Throwable {
|
||||
final ModifiableRootModel model = ModuleRootManager.getInstance(myFixture.getModule()).getModifiableModel();
|
||||
ContentEntry contentEntry = model.getContentEntries()[0];
|
||||
SourceFolder sourceFolder = contentEntry.getSourceFolders()[0];
|
||||
VirtualFile file = sourceFolder.getFile();
|
||||
contentEntry.removeSourceFolder(sourceFolder);
|
||||
contentEntry.addSourceFolder(file, true);
|
||||
model.commit();
|
||||
}
|
||||
}.execute().throwException();
|
||||
|
||||
myFixture.addClass("package foo; public class SomeTestCase {}");
|
||||
myFixture.addClass("package bar; public class SomeTestec {}");
|
||||
myFixture.addClass("package goo; public class SomeAnchor {}");
|
||||
|
||||
myFixture.completeBasic();
|
||||
myFixture.assertPreferredCompletionItems(0, "SomeTestCase", "SomeAnchor", "SomeTestec");
|
||||
}
|
||||
|
||||
public void testAllClassesWhenNothingIsFound() throws Throwable {
|
||||
myFixture.addClass("package foo.bar; public class AxBxCxDxEx {}");
|
||||
|
||||
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
|
||||
myFixture.completeBasic();
|
||||
myFixture.type('\n');
|
||||
myFixture.checkResultByFile("/codeInsight/completion/normal/" + getTestName(false) + "_after.java");
|
||||
}
|
||||
|
||||
public void testAllClassesOnSecondBasicCompletion() throws Throwable {
|
||||
myFixture.addClass("package foo.bar; public class AxBxCxDxEx {}");
|
||||
|
||||
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
|
||||
myFixture.complete(CompletionType.BASIC, 2);
|
||||
LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myFixture.getEditor());
|
||||
LookupElement[] myItems = lookup.getItems().toArray(LookupElement.EMPTY_ARRAY);
|
||||
assertEquals(2, myItems.length);
|
||||
assertEquals("AxBxCxDxEx", myItems[1].getLookupString());
|
||||
assertEquals("AyByCyDyEy", myItems[0].getLookupString());
|
||||
}
|
||||
|
||||
public void testMapsInvalidation() throws Exception {
|
||||
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
|
||||
assertInstanceOf(myFixture.getFile().getVirtualFile().getFileSystem(), LocalFileSystem.class); // otherwise the completion copy won't be preserved which is critical here
|
||||
myFixture.completeBasic();
|
||||
assertOrderedEquals(myFixture.getLookupElementStrings(), "getAaa", "getBbb");
|
||||
myFixture.getEditor().getCaretModel().moveToOffset(myFixture.getEditor().getCaretModel().getOffset() + 2);
|
||||
assertNull(myFixture.completeBasic());
|
||||
}
|
||||
|
||||
public void testQualifyInaccessibleClassName() throws Exception {
|
||||
PsiTestUtil.addModule(getProject(), StdModuleTypes.JAVA, "second", myFixture.getTempDirFixture().findOrCreateDir("second"));
|
||||
myFixture.addFileToProject("second/foo/bar/AxBxCxDxEx.java", "package foo.bar; class AxBxCxDxEx {}");
|
||||
|
||||
myFixture.configureByText("a.java", "class Main { ABCDE<caret> }");
|
||||
myFixture.complete(CompletionType.BASIC, 3);
|
||||
myFixture.checkResult("class Main { foo.bar.AxBxCxDxEx<caret> }");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+29
-29
@@ -1,30 +1,30 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.daemon.quickFix;
|
||||
|
||||
/**
|
||||
* @author Danila Ponomarenko
|
||||
*/
|
||||
public class BreakStringOnLineBreaksTest extends LightQuickFixTestCase {
|
||||
|
||||
public void test() throws Exception { doAllTests(); }
|
||||
|
||||
@Override
|
||||
protected String getBasePath() {
|
||||
return "/codeInsight/daemonCodeAnalyzer/quickFix/breakStringOnLineBreaks";
|
||||
}
|
||||
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.daemon.quickFix;
|
||||
|
||||
/**
|
||||
* @author Danila Ponomarenko
|
||||
*/
|
||||
public class BreakStringOnLineBreaksTest extends LightQuickFixTestCase {
|
||||
|
||||
public void test() throws Exception { doAllTests(); }
|
||||
|
||||
@Override
|
||||
protected String getBasePath() {
|
||||
return "/codeInsight/daemonCodeAnalyzer/quickFix/breakStringOnLineBreaks";
|
||||
}
|
||||
|
||||
}
|
||||
+123
-123
@@ -1,123 +1,123 @@
|
||||
/*
|
||||
* Copyright 2000-2011 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.codeInsight.daemon.DaemonAnalyzerTestCase;
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
import com.intellij.codeInsight.lookup.LookupManager;
|
||||
import com.intellij.codeInsight.lookup.impl.LookupImpl;
|
||||
import com.intellij.testFramework.PlatformTestCase;
|
||||
import com.intellij.util.Function;
|
||||
import com.intellij.util.containers.ContainerUtil;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author mike
|
||||
*/
|
||||
@PlatformTestCase.WrapInCommand
|
||||
public abstract class CompletionTestCase extends DaemonAnalyzerTestCase {
|
||||
protected String myPrefix;
|
||||
protected LookupElement[] myItems;
|
||||
private CompletionType myType = CompletionType.BASIC;
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
try {
|
||||
LookupManager.getInstance(myProject).hideActiveLookup();
|
||||
}
|
||||
finally {
|
||||
super.tearDown();
|
||||
}
|
||||
myItems = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configureByFile(String filePath) throws Exception {
|
||||
super.configureByFile(filePath);
|
||||
|
||||
complete();
|
||||
}
|
||||
|
||||
protected void configureByFileNoCompletion(String filePath) throws Exception {
|
||||
super.configureByFile(filePath);
|
||||
}
|
||||
|
||||
protected void complete() {
|
||||
complete(1);
|
||||
}
|
||||
|
||||
protected void complete(final int time) {
|
||||
new CodeCompletionHandlerBase(myType).invokeCompletion(myProject, myEditor, time);
|
||||
|
||||
LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor);
|
||||
myItems = lookup == null ? null : lookup.getItems().toArray(new LookupElement[lookup.getItems().size()]);
|
||||
myPrefix = lookup == null ? "" : lookup.itemPattern(lookup.getItems().get(0));
|
||||
}
|
||||
|
||||
public void setType(CompletionType type) {
|
||||
myType = type;
|
||||
}
|
||||
|
||||
protected void selectItem(LookupElement item, char ch) {
|
||||
final LookupImpl lookup = (LookupImpl)LookupManager.getInstance(myProject).getActiveLookup();
|
||||
assert lookup != null;
|
||||
lookup.setCurrentItem(item);
|
||||
lookup.finishLookup(ch);
|
||||
}
|
||||
|
||||
protected void selectItem(LookupElement item) {
|
||||
selectItem(item, (char)0);
|
||||
}
|
||||
|
||||
protected void doTestByCount(int finalCount, String... values) {
|
||||
int index = 0;
|
||||
if (myItems == null) {
|
||||
assertEquals(0, finalCount);
|
||||
return;
|
||||
}
|
||||
for (final LookupElement myItem : myItems) {
|
||||
for (String value : values) {
|
||||
if (value == null) {
|
||||
assertFalse("Unacceptable value reached", true);
|
||||
}
|
||||
if (value.equals(myItem.getLookupString())) {
|
||||
index++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(Arrays.toString(myItems), finalCount, index);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
protected LookupImpl getActiveLookup() {
|
||||
return (LookupImpl)LookupManager.getActiveLookup(myEditor);
|
||||
}
|
||||
|
||||
protected void assertStringItems(String... strings) {
|
||||
assertNotNull(myItems);
|
||||
List<String> actual = ContainerUtil.map(myItems, new Function<LookupElement, String>() {
|
||||
@Override
|
||||
public String fun(LookupElement element) {
|
||||
return element.getLookupString();
|
||||
}
|
||||
});
|
||||
assertOrderedEquals(actual, strings);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2011 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.codeInsight.daemon.DaemonAnalyzerTestCase;
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
import com.intellij.codeInsight.lookup.LookupManager;
|
||||
import com.intellij.codeInsight.lookup.impl.LookupImpl;
|
||||
import com.intellij.testFramework.PlatformTestCase;
|
||||
import com.intellij.util.Function;
|
||||
import com.intellij.util.containers.ContainerUtil;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author mike
|
||||
*/
|
||||
@PlatformTestCase.WrapInCommand
|
||||
public abstract class CompletionTestCase extends DaemonAnalyzerTestCase {
|
||||
protected String myPrefix;
|
||||
protected LookupElement[] myItems;
|
||||
private CompletionType myType = CompletionType.BASIC;
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
try {
|
||||
LookupManager.getInstance(myProject).hideActiveLookup();
|
||||
}
|
||||
finally {
|
||||
super.tearDown();
|
||||
}
|
||||
myItems = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configureByFile(String filePath) throws Exception {
|
||||
super.configureByFile(filePath);
|
||||
|
||||
complete();
|
||||
}
|
||||
|
||||
protected void configureByFileNoCompletion(String filePath) throws Exception {
|
||||
super.configureByFile(filePath);
|
||||
}
|
||||
|
||||
protected void complete() {
|
||||
complete(1);
|
||||
}
|
||||
|
||||
protected void complete(final int time) {
|
||||
new CodeCompletionHandlerBase(myType).invokeCompletion(myProject, myEditor, time);
|
||||
|
||||
LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor);
|
||||
myItems = lookup == null ? null : lookup.getItems().toArray(new LookupElement[lookup.getItems().size()]);
|
||||
myPrefix = lookup == null ? "" : lookup.itemPattern(lookup.getItems().get(0));
|
||||
}
|
||||
|
||||
public void setType(CompletionType type) {
|
||||
myType = type;
|
||||
}
|
||||
|
||||
protected void selectItem(LookupElement item, char ch) {
|
||||
final LookupImpl lookup = (LookupImpl)LookupManager.getInstance(myProject).getActiveLookup();
|
||||
assert lookup != null;
|
||||
lookup.setCurrentItem(item);
|
||||
lookup.finishLookup(ch);
|
||||
}
|
||||
|
||||
protected void selectItem(LookupElement item) {
|
||||
selectItem(item, (char)0);
|
||||
}
|
||||
|
||||
protected void doTestByCount(int finalCount, String... values) {
|
||||
int index = 0;
|
||||
if (myItems == null) {
|
||||
assertEquals(0, finalCount);
|
||||
return;
|
||||
}
|
||||
for (final LookupElement myItem : myItems) {
|
||||
for (String value : values) {
|
||||
if (value == null) {
|
||||
assertFalse("Unacceptable value reached", true);
|
||||
}
|
||||
if (value.equals(myItem.getLookupString())) {
|
||||
index++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(Arrays.toString(myItems), finalCount, index);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
protected LookupImpl getActiveLookup() {
|
||||
return (LookupImpl)LookupManager.getActiveLookup(myEditor);
|
||||
}
|
||||
|
||||
protected void assertStringItems(String... strings) {
|
||||
assertNotNull(myItems);
|
||||
List<String> actual = ContainerUtil.map(myItems, new Function<LookupElement, String>() {
|
||||
@Override
|
||||
public String fun(LookupElement element) {
|
||||
return element.getLookupString();
|
||||
}
|
||||
});
|
||||
assertOrderedEquals(actual, strings);
|
||||
}
|
||||
}
|
||||
|
||||
+137
-137
@@ -1,137 +1,137 @@
|
||||
/*
|
||||
* Copyright 2000-2011 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
import com.intellij.codeInsight.lookup.LookupManager;
|
||||
import com.intellij.codeInsight.lookup.impl.LookupImpl;
|
||||
import com.intellij.testFramework.LightCodeInsightTestCase;
|
||||
import com.intellij.util.containers.HashSet;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author mike
|
||||
*/
|
||||
public abstract class LightCompletionTestCase extends LightCodeInsightTestCase {
|
||||
protected String myPrefix;
|
||||
protected LookupElement[] myItems;
|
||||
private CompletionType myType = CompletionType.BASIC;
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
LookupManager.getInstance(getProject()).hideActiveLookup();
|
||||
super.tearDown();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configureByFile(@NotNull String filePath) {
|
||||
super.configureByFile(filePath);
|
||||
|
||||
complete();
|
||||
}
|
||||
|
||||
protected void configureByFileNoComplete(String filePath) throws Exception {
|
||||
super.configureByFile(filePath);
|
||||
}
|
||||
|
||||
protected void complete() {
|
||||
complete(1);
|
||||
}
|
||||
|
||||
protected void complete(final int time) {
|
||||
new CodeCompletionHandlerBase(myType).invokeCompletion(getProject(), getEditor(), time);
|
||||
|
||||
LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor);
|
||||
myItems = lookup == null ? null : lookup.getItems().toArray(LookupElement.EMPTY_ARRAY);
|
||||
myPrefix = lookup == null ? null : lookup.itemPattern(lookup.getItems().get(0));
|
||||
}
|
||||
|
||||
public void setType(CompletionType type) {
|
||||
myType = type;
|
||||
}
|
||||
|
||||
protected void selectItem(LookupElement item) {
|
||||
selectItem(item, (char)0);
|
||||
}
|
||||
|
||||
protected void selectItem(LookupElement item, char completionChar) {
|
||||
final LookupImpl lookup = (LookupImpl)LookupManager.getInstance(getProject()).getActiveLookup();
|
||||
lookup.setCurrentItem(item);
|
||||
if (completionChar == 0 || completionChar == '\n' || completionChar == '\t') {
|
||||
lookup.finishLookup(completionChar);
|
||||
} else {
|
||||
type(completionChar);
|
||||
}
|
||||
}
|
||||
|
||||
protected void testByCount(int finalCount, @NonNls String... values) {
|
||||
if (myItems == null) {
|
||||
assertEquals(finalCount, 0);
|
||||
return;
|
||||
}
|
||||
int index = 0;
|
||||
for (final LookupElement myItem : myItems) {
|
||||
for (String value : values) {
|
||||
if (value == null) {
|
||||
assertFalse("Unacceptable value reached: " + myItem.getLookupString(), true);
|
||||
}
|
||||
if (value.equals(myItem.getLookupString())) {
|
||||
index++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(finalCount, index);
|
||||
}
|
||||
|
||||
protected void assertStringItems(@NonNls String... items) {
|
||||
assertOrderedEquals(getLookupStrings(new ArrayList<String>()), items);
|
||||
}
|
||||
|
||||
protected void assertContainsItems(final String... expected) {
|
||||
final Set<String> actual = getLookupStrings(new HashSet<String>());
|
||||
for (String s : expected) {
|
||||
assertTrue("Expected '" + s + "' not found in " + actual,
|
||||
actual.contains(s));
|
||||
}
|
||||
}
|
||||
|
||||
protected void assertNotContainItems(final String... unexpected) {
|
||||
final Set<String> actual = getLookupStrings(new HashSet<String>());
|
||||
for (String s : unexpected) {
|
||||
assertFalse("Unexpected '" + s + "' presented in " + actual,
|
||||
actual.contains(s));
|
||||
}
|
||||
}
|
||||
|
||||
private <T extends Collection<String>> T getLookupStrings(T actual) {
|
||||
if (myItems != null) {
|
||||
for (LookupElement lookupElement : myItems) {
|
||||
actual.add(lookupElement.getLookupString());
|
||||
}
|
||||
}
|
||||
return actual;
|
||||
}
|
||||
|
||||
protected static LookupImpl getLookup() {
|
||||
return (LookupImpl)LookupManager.getActiveLookup(myEditor);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2011 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
import com.intellij.codeInsight.lookup.LookupManager;
|
||||
import com.intellij.codeInsight.lookup.impl.LookupImpl;
|
||||
import com.intellij.testFramework.LightCodeInsightTestCase;
|
||||
import com.intellij.util.containers.HashSet;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author mike
|
||||
*/
|
||||
public abstract class LightCompletionTestCase extends LightCodeInsightTestCase {
|
||||
protected String myPrefix;
|
||||
protected LookupElement[] myItems;
|
||||
private CompletionType myType = CompletionType.BASIC;
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
LookupManager.getInstance(getProject()).hideActiveLookup();
|
||||
super.tearDown();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configureByFile(@NotNull String filePath) {
|
||||
super.configureByFile(filePath);
|
||||
|
||||
complete();
|
||||
}
|
||||
|
||||
protected void configureByFileNoComplete(String filePath) throws Exception {
|
||||
super.configureByFile(filePath);
|
||||
}
|
||||
|
||||
protected void complete() {
|
||||
complete(1);
|
||||
}
|
||||
|
||||
protected void complete(final int time) {
|
||||
new CodeCompletionHandlerBase(myType).invokeCompletion(getProject(), getEditor(), time);
|
||||
|
||||
LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor);
|
||||
myItems = lookup == null ? null : lookup.getItems().toArray(LookupElement.EMPTY_ARRAY);
|
||||
myPrefix = lookup == null ? null : lookup.itemPattern(lookup.getItems().get(0));
|
||||
}
|
||||
|
||||
public void setType(CompletionType type) {
|
||||
myType = type;
|
||||
}
|
||||
|
||||
protected void selectItem(LookupElement item) {
|
||||
selectItem(item, (char)0);
|
||||
}
|
||||
|
||||
protected void selectItem(LookupElement item, char completionChar) {
|
||||
final LookupImpl lookup = (LookupImpl)LookupManager.getInstance(getProject()).getActiveLookup();
|
||||
lookup.setCurrentItem(item);
|
||||
if (completionChar == 0 || completionChar == '\n' || completionChar == '\t') {
|
||||
lookup.finishLookup(completionChar);
|
||||
} else {
|
||||
type(completionChar);
|
||||
}
|
||||
}
|
||||
|
||||
protected void testByCount(int finalCount, @NonNls String... values) {
|
||||
if (myItems == null) {
|
||||
assertEquals(finalCount, 0);
|
||||
return;
|
||||
}
|
||||
int index = 0;
|
||||
for (final LookupElement myItem : myItems) {
|
||||
for (String value : values) {
|
||||
if (value == null) {
|
||||
assertFalse("Unacceptable value reached: " + myItem.getLookupString(), true);
|
||||
}
|
||||
if (value.equals(myItem.getLookupString())) {
|
||||
index++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(finalCount, index);
|
||||
}
|
||||
|
||||
protected void assertStringItems(@NonNls String... items) {
|
||||
assertOrderedEquals(getLookupStrings(new ArrayList<String>()), items);
|
||||
}
|
||||
|
||||
protected void assertContainsItems(final String... expected) {
|
||||
final Set<String> actual = getLookupStrings(new HashSet<String>());
|
||||
for (String s : expected) {
|
||||
assertTrue("Expected '" + s + "' not found in " + actual,
|
||||
actual.contains(s));
|
||||
}
|
||||
}
|
||||
|
||||
protected void assertNotContainItems(final String... unexpected) {
|
||||
final Set<String> actual = getLookupStrings(new HashSet<String>());
|
||||
for (String s : unexpected) {
|
||||
assertFalse("Unexpected '" + s + "' presented in " + actual,
|
||||
actual.contains(s));
|
||||
}
|
||||
}
|
||||
|
||||
private <T extends Collection<String>> T getLookupStrings(T actual) {
|
||||
if (myItems != null) {
|
||||
for (LookupElement lookupElement : myItems) {
|
||||
actual.add(lookupElement.getLookupString());
|
||||
}
|
||||
}
|
||||
return actual;
|
||||
}
|
||||
|
||||
protected static LookupImpl getLookup() {
|
||||
return (LookupImpl)LookupManager.getActiveLookup(myEditor);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,241 +1,241 @@
|
||||
package org.jetbrains.jps.javac;
|
||||
|
||||
import com.intellij.openapi.util.io.FileUtilRt;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.jetbrains.jps.incremental.Utils;
|
||||
|
||||
import javax.tools.*;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author Eugene Zhuravlev
|
||||
* Date: 9/24/11
|
||||
*/
|
||||
class JavacFileManager extends ForwardingJavaFileManager<StandardJavaFileManager> implements StandardJavaFileManager{
|
||||
|
||||
private final Context myContext;
|
||||
private Map<File, Set<File>> myOutputsMap = Collections.emptyMap();
|
||||
|
||||
interface Context {
|
||||
boolean isCanceled();
|
||||
|
||||
StandardJavaFileManager getStandardFileManager();
|
||||
|
||||
void consumeOutputFile(@NotNull OutputFileObject obj);
|
||||
|
||||
void reportMessage(final Diagnostic.Kind kind, String message);
|
||||
}
|
||||
|
||||
public JavacFileManager(Context context) {
|
||||
super(context.getStandardFileManager());
|
||||
myContext = context;
|
||||
}
|
||||
|
||||
public void setOutputDirectories(final Map<File, Set<File>> outputDirToSrcRoots) throws IOException{
|
||||
for (File outputDir : outputDirToSrcRoots.keySet()) {
|
||||
// this will validate output dirs
|
||||
setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(outputDir));
|
||||
}
|
||||
myOutputsMap = outputDirToSrcRoots;
|
||||
}
|
||||
|
||||
public void setLocation(Location location, Iterable<? extends File> path) throws IOException{
|
||||
getStdManager().setLocation(location, path);
|
||||
}
|
||||
|
||||
public Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(Iterable<? extends File> files) {
|
||||
return getStdManager().getJavaFileObjectsFromFiles(files);
|
||||
}
|
||||
|
||||
public Iterable<? extends JavaFileObject> getJavaFileObjects(File... files) {
|
||||
return getStdManager().getJavaFileObjects(files);
|
||||
}
|
||||
|
||||
public Iterable<? extends JavaFileObject> getJavaFileObjectsFromStrings(Iterable<String> names) {
|
||||
return getStdManager().getJavaFileObjectsFromStrings(names);
|
||||
}
|
||||
|
||||
public Iterable<? extends JavaFileObject> getJavaFileObjects(String... names) {
|
||||
return getStdManager().getJavaFileObjects(names);
|
||||
}
|
||||
|
||||
public Iterable<? extends File> getLocation(Location location) {
|
||||
return getStdManager().getLocation(location);
|
||||
}
|
||||
|
||||
public boolean isSameFile(FileObject a, FileObject b) {
|
||||
if (a instanceof OutputFileObject || b instanceof OutputFileObject) {
|
||||
return a.equals(b);
|
||||
}
|
||||
return super.isSameFile(a, b);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException {
|
||||
checkCanceled();
|
||||
final FileObject fo = super.getFileForInput(location, packageName, relativeName);
|
||||
if (fo == null) {
|
||||
// workaround javac bug (missing null-check): throwing exception here instead of returning null
|
||||
throw new FileNotFoundException("Resource does not exist : " + location + '/' + packageName + '/' + relativeName);
|
||||
}
|
||||
return fo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JavaFileObject getJavaFileForInput(Location location, String className, JavaFileObject.Kind kind) throws IOException {
|
||||
checkCanceled();
|
||||
final JavaFileObject fo = super.getJavaFileForInput(location, className, kind);
|
||||
if (fo == null) {
|
||||
// workaround javac bug (missing null-check): throwing exception here instead of returning null
|
||||
throw new FileNotFoundException("Java resource does not exist : " + location + '/' + kind + '/' + className);
|
||||
}
|
||||
return fo;
|
||||
}
|
||||
|
||||
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) throws IOException {
|
||||
if (kind != JavaFileObject.Kind.SOURCE && kind != JavaFileObject.Kind.CLASS) {
|
||||
throw new IllegalArgumentException("Invalid kind " + kind);
|
||||
}
|
||||
return getFileForOutput(location, kind, externalizeFileName(className, kind), className, sibling);
|
||||
}
|
||||
|
||||
public FileObject getFileForOutput(Location location, String packageName, String relativeName, FileObject sibling) throws IOException {
|
||||
final StringBuilder name = new StringBuilder();
|
||||
if (packageName.isEmpty()) {
|
||||
name.append(relativeName);
|
||||
}
|
||||
else {
|
||||
name.append(externalizeFileName(packageName)).append(File.separatorChar).append(relativeName);
|
||||
}
|
||||
final String fileName = name.toString();
|
||||
return getFileForOutput(location, getKind(fileName), fileName, null, sibling);
|
||||
}
|
||||
|
||||
private OutputFileObject getFileForOutput(Location location, JavaFileObject.Kind kind, String fileName, @Nullable String className, FileObject sibling) throws IOException {
|
||||
checkCanceled();
|
||||
|
||||
JavaFileObject src = null;
|
||||
if (sibling instanceof JavaFileObject) {
|
||||
final JavaFileObject javaFileObject = (JavaFileObject)sibling;
|
||||
if (javaFileObject.getKind() == JavaFileObject.Kind.SOURCE) {
|
||||
src = javaFileObject;
|
||||
}
|
||||
}
|
||||
|
||||
File dir = getSingleOutputDirectory(location, src);
|
||||
|
||||
if (location == StandardLocation.CLASS_OUTPUT) {
|
||||
if (dir == null) {
|
||||
throw new IOException("Output directory is not specified");
|
||||
}
|
||||
}
|
||||
else if (location == StandardLocation.SOURCE_OUTPUT) {
|
||||
if (dir == null) {
|
||||
dir = getSingleOutputDirectory(StandardLocation.CLASS_OUTPUT, src);
|
||||
if (dir == null) {
|
||||
throw new IOException("Neither class output directory nor source output are specified");
|
||||
}
|
||||
}
|
||||
}
|
||||
final File file = (dir == null? new File(fileName).getAbsoluteFile() : new File(dir, fileName));
|
||||
return new OutputFileObject(myContext, dir, fileName, file, kind, className, src != null? src.toUri() : null);
|
||||
}
|
||||
|
||||
private File getSingleOutputDirectory(final Location loc, final JavaFileObject sourceFile) {
|
||||
if (loc == StandardLocation.CLASS_OUTPUT) {
|
||||
if (myOutputsMap.size() > 1 && sourceFile != null) {
|
||||
// multiple outputs case
|
||||
final File outputDir = findOutputDir(Utils.convertToFile(sourceFile.toUri()));
|
||||
if (outputDir != null) {
|
||||
return outputDir;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final Iterable<? extends File> location = getStdManager().getLocation(loc);
|
||||
if (location != null) {
|
||||
final Iterator<? extends File> it = location.iterator();
|
||||
if (it.hasNext()) {
|
||||
return it.next();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private File findOutputDir(File src) {
|
||||
File file = FileUtilRt.getParentFile(src);
|
||||
while (file != null) {
|
||||
for (Map.Entry<File, Set<File>> entry : myOutputsMap.entrySet()) {
|
||||
if (entry.getValue().contains(file)) {
|
||||
return entry.getKey();
|
||||
}
|
||||
}
|
||||
file = FileUtilRt.getParentFile(file);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private StandardJavaFileManager getStdManager() {
|
||||
return fileManager;
|
||||
}
|
||||
|
||||
public Iterable<? extends JavaFileObject> toJavaFileObjects(Iterable<? extends File> files) {
|
||||
return getStdManager().getJavaFileObjectsFromFiles(files);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
super.close();
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
finally {
|
||||
myOutputsMap = Collections.emptyMap();
|
||||
}
|
||||
}
|
||||
|
||||
private static JavaFileObject.Kind getKind(String name) {
|
||||
if (name.endsWith(JavaFileObject.Kind.CLASS.extension)){
|
||||
return JavaFileObject.Kind.CLASS;
|
||||
}
|
||||
if (name.endsWith(JavaFileObject.Kind.SOURCE.extension)) {
|
||||
return JavaFileObject.Kind.SOURCE;
|
||||
}
|
||||
if (name.endsWith(JavaFileObject.Kind.HTML.extension)) {
|
||||
return JavaFileObject.Kind.HTML;
|
||||
}
|
||||
return JavaFileObject.Kind.OTHER;
|
||||
}
|
||||
|
||||
private static String externalizeFileName(CharSequence cs, JavaFileObject.Kind kind) {
|
||||
return externalizeFileName(cs) + kind.extension;
|
||||
}
|
||||
|
||||
private static String externalizeFileName(CharSequence name) {
|
||||
return name.toString().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
private int myChecksCounter = 0;
|
||||
|
||||
private void checkCanceled() {
|
||||
final int counter = (myChecksCounter + 1) % 10;
|
||||
myChecksCounter = counter;
|
||||
if (counter == 0 && myContext.isCanceled()) {
|
||||
throw new CompilationCanceledException();
|
||||
}
|
||||
}
|
||||
|
||||
public Context getContext() {
|
||||
return myContext;
|
||||
}
|
||||
}
|
||||
package org.jetbrains.jps.javac;
|
||||
|
||||
import com.intellij.openapi.util.io.FileUtilRt;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.jetbrains.jps.incremental.Utils;
|
||||
|
||||
import javax.tools.*;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author Eugene Zhuravlev
|
||||
* Date: 9/24/11
|
||||
*/
|
||||
class JavacFileManager extends ForwardingJavaFileManager<StandardJavaFileManager> implements StandardJavaFileManager{
|
||||
|
||||
private final Context myContext;
|
||||
private Map<File, Set<File>> myOutputsMap = Collections.emptyMap();
|
||||
|
||||
interface Context {
|
||||
boolean isCanceled();
|
||||
|
||||
StandardJavaFileManager getStandardFileManager();
|
||||
|
||||
void consumeOutputFile(@NotNull OutputFileObject obj);
|
||||
|
||||
void reportMessage(final Diagnostic.Kind kind, String message);
|
||||
}
|
||||
|
||||
public JavacFileManager(Context context) {
|
||||
super(context.getStandardFileManager());
|
||||
myContext = context;
|
||||
}
|
||||
|
||||
public void setOutputDirectories(final Map<File, Set<File>> outputDirToSrcRoots) throws IOException{
|
||||
for (File outputDir : outputDirToSrcRoots.keySet()) {
|
||||
// this will validate output dirs
|
||||
setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(outputDir));
|
||||
}
|
||||
myOutputsMap = outputDirToSrcRoots;
|
||||
}
|
||||
|
||||
public void setLocation(Location location, Iterable<? extends File> path) throws IOException{
|
||||
getStdManager().setLocation(location, path);
|
||||
}
|
||||
|
||||
public Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(Iterable<? extends File> files) {
|
||||
return getStdManager().getJavaFileObjectsFromFiles(files);
|
||||
}
|
||||
|
||||
public Iterable<? extends JavaFileObject> getJavaFileObjects(File... files) {
|
||||
return getStdManager().getJavaFileObjects(files);
|
||||
}
|
||||
|
||||
public Iterable<? extends JavaFileObject> getJavaFileObjectsFromStrings(Iterable<String> names) {
|
||||
return getStdManager().getJavaFileObjectsFromStrings(names);
|
||||
}
|
||||
|
||||
public Iterable<? extends JavaFileObject> getJavaFileObjects(String... names) {
|
||||
return getStdManager().getJavaFileObjects(names);
|
||||
}
|
||||
|
||||
public Iterable<? extends File> getLocation(Location location) {
|
||||
return getStdManager().getLocation(location);
|
||||
}
|
||||
|
||||
public boolean isSameFile(FileObject a, FileObject b) {
|
||||
if (a instanceof OutputFileObject || b instanceof OutputFileObject) {
|
||||
return a.equals(b);
|
||||
}
|
||||
return super.isSameFile(a, b);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException {
|
||||
checkCanceled();
|
||||
final FileObject fo = super.getFileForInput(location, packageName, relativeName);
|
||||
if (fo == null) {
|
||||
// workaround javac bug (missing null-check): throwing exception here instead of returning null
|
||||
throw new FileNotFoundException("Resource does not exist : " + location + '/' + packageName + '/' + relativeName);
|
||||
}
|
||||
return fo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JavaFileObject getJavaFileForInput(Location location, String className, JavaFileObject.Kind kind) throws IOException {
|
||||
checkCanceled();
|
||||
final JavaFileObject fo = super.getJavaFileForInput(location, className, kind);
|
||||
if (fo == null) {
|
||||
// workaround javac bug (missing null-check): throwing exception here instead of returning null
|
||||
throw new FileNotFoundException("Java resource does not exist : " + location + '/' + kind + '/' + className);
|
||||
}
|
||||
return fo;
|
||||
}
|
||||
|
||||
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) throws IOException {
|
||||
if (kind != JavaFileObject.Kind.SOURCE && kind != JavaFileObject.Kind.CLASS) {
|
||||
throw new IllegalArgumentException("Invalid kind " + kind);
|
||||
}
|
||||
return getFileForOutput(location, kind, externalizeFileName(className, kind), className, sibling);
|
||||
}
|
||||
|
||||
public FileObject getFileForOutput(Location location, String packageName, String relativeName, FileObject sibling) throws IOException {
|
||||
final StringBuilder name = new StringBuilder();
|
||||
if (packageName.isEmpty()) {
|
||||
name.append(relativeName);
|
||||
}
|
||||
else {
|
||||
name.append(externalizeFileName(packageName)).append(File.separatorChar).append(relativeName);
|
||||
}
|
||||
final String fileName = name.toString();
|
||||
return getFileForOutput(location, getKind(fileName), fileName, null, sibling);
|
||||
}
|
||||
|
||||
private OutputFileObject getFileForOutput(Location location, JavaFileObject.Kind kind, String fileName, @Nullable String className, FileObject sibling) throws IOException {
|
||||
checkCanceled();
|
||||
|
||||
JavaFileObject src = null;
|
||||
if (sibling instanceof JavaFileObject) {
|
||||
final JavaFileObject javaFileObject = (JavaFileObject)sibling;
|
||||
if (javaFileObject.getKind() == JavaFileObject.Kind.SOURCE) {
|
||||
src = javaFileObject;
|
||||
}
|
||||
}
|
||||
|
||||
File dir = getSingleOutputDirectory(location, src);
|
||||
|
||||
if (location == StandardLocation.CLASS_OUTPUT) {
|
||||
if (dir == null) {
|
||||
throw new IOException("Output directory is not specified");
|
||||
}
|
||||
}
|
||||
else if (location == StandardLocation.SOURCE_OUTPUT) {
|
||||
if (dir == null) {
|
||||
dir = getSingleOutputDirectory(StandardLocation.CLASS_OUTPUT, src);
|
||||
if (dir == null) {
|
||||
throw new IOException("Neither class output directory nor source output are specified");
|
||||
}
|
||||
}
|
||||
}
|
||||
final File file = (dir == null? new File(fileName).getAbsoluteFile() : new File(dir, fileName));
|
||||
return new OutputFileObject(myContext, dir, fileName, file, kind, className, src != null? src.toUri() : null);
|
||||
}
|
||||
|
||||
private File getSingleOutputDirectory(final Location loc, final JavaFileObject sourceFile) {
|
||||
if (loc == StandardLocation.CLASS_OUTPUT) {
|
||||
if (myOutputsMap.size() > 1 && sourceFile != null) {
|
||||
// multiple outputs case
|
||||
final File outputDir = findOutputDir(Utils.convertToFile(sourceFile.toUri()));
|
||||
if (outputDir != null) {
|
||||
return outputDir;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final Iterable<? extends File> location = getStdManager().getLocation(loc);
|
||||
if (location != null) {
|
||||
final Iterator<? extends File> it = location.iterator();
|
||||
if (it.hasNext()) {
|
||||
return it.next();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private File findOutputDir(File src) {
|
||||
File file = FileUtilRt.getParentFile(src);
|
||||
while (file != null) {
|
||||
for (Map.Entry<File, Set<File>> entry : myOutputsMap.entrySet()) {
|
||||
if (entry.getValue().contains(file)) {
|
||||
return entry.getKey();
|
||||
}
|
||||
}
|
||||
file = FileUtilRt.getParentFile(file);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private StandardJavaFileManager getStdManager() {
|
||||
return fileManager;
|
||||
}
|
||||
|
||||
public Iterable<? extends JavaFileObject> toJavaFileObjects(Iterable<? extends File> files) {
|
||||
return getStdManager().getJavaFileObjectsFromFiles(files);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
super.close();
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
finally {
|
||||
myOutputsMap = Collections.emptyMap();
|
||||
}
|
||||
}
|
||||
|
||||
private static JavaFileObject.Kind getKind(String name) {
|
||||
if (name.endsWith(JavaFileObject.Kind.CLASS.extension)){
|
||||
return JavaFileObject.Kind.CLASS;
|
||||
}
|
||||
if (name.endsWith(JavaFileObject.Kind.SOURCE.extension)) {
|
||||
return JavaFileObject.Kind.SOURCE;
|
||||
}
|
||||
if (name.endsWith(JavaFileObject.Kind.HTML.extension)) {
|
||||
return JavaFileObject.Kind.HTML;
|
||||
}
|
||||
return JavaFileObject.Kind.OTHER;
|
||||
}
|
||||
|
||||
private static String externalizeFileName(CharSequence cs, JavaFileObject.Kind kind) {
|
||||
return externalizeFileName(cs) + kind.extension;
|
||||
}
|
||||
|
||||
private static String externalizeFileName(CharSequence name) {
|
||||
return name.toString().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
private int myChecksCounter = 0;
|
||||
|
||||
private void checkCanceled() {
|
||||
final int counter = (myChecksCounter + 1) % 10;
|
||||
myChecksCounter = counter;
|
||||
if (counter == 0 && myContext.isCanceled()) {
|
||||
throw new CompilationCanceledException();
|
||||
}
|
||||
}
|
||||
|
||||
public Context getContext() {
|
||||
return myContext;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,128 +1,128 @@
|
||||
package org.jetbrains.jps.javac;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.jetbrains.jps.incremental.BinaryContent;
|
||||
import org.jetbrains.jps.incremental.Utils;
|
||||
|
||||
import javax.tools.*;
|
||||
import java.io.*;
|
||||
import java.net.URI;
|
||||
|
||||
/**
|
||||
* @author Eugene Zhuravlev
|
||||
* Date: 9/24/11
|
||||
*/
|
||||
public final class OutputFileObject extends SimpleJavaFileObject {
|
||||
@Nullable
|
||||
private final JavacFileManager.Context myContext;
|
||||
@Nullable
|
||||
private final File myOutputRoot;
|
||||
private final String myRelativePath;
|
||||
private final File myFile;
|
||||
@Nullable
|
||||
private final String myClassName;
|
||||
@Nullable private final URI mySourceUri;
|
||||
private volatile BinaryContent myContent;
|
||||
private final File mySourceFile;
|
||||
|
||||
public OutputFileObject(@NotNull JavacFileManager.Context context, @Nullable File outputRoot, String relativePath, @NotNull File file, @NotNull Kind kind, @Nullable String className, @Nullable final URI sourceUri) {
|
||||
this(context, outputRoot, relativePath, file, kind, className, sourceUri, null);
|
||||
}
|
||||
|
||||
public OutputFileObject(@Nullable JavacFileManager.Context context, @Nullable File outputRoot, String relativePath, @NotNull File file, @NotNull Kind kind, @Nullable String className, @Nullable final URI srcUri, @Nullable BinaryContent content) {
|
||||
super(Utils.toURI(file.getPath()), kind);
|
||||
myContext = context;
|
||||
mySourceUri = srcUri;
|
||||
myContent = content;
|
||||
myOutputRoot = outputRoot;
|
||||
myRelativePath = relativePath;
|
||||
myFile = file;
|
||||
myClassName = className != null? className.replace('/', '.') : null;
|
||||
mySourceFile = srcUri != null? Utils.convertToFile(srcUri) : null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public File getOutputRoot() {
|
||||
return myOutputRoot;
|
||||
}
|
||||
|
||||
public String getRelativePath() {
|
||||
return myRelativePath;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public File getFile() {
|
||||
return myFile;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getClassName() {
|
||||
return myClassName;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public File getSourceFile() {
|
||||
return mySourceFile;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public URI getSourceUri() {
|
||||
return mySourceUri;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ByteArrayOutputStream openOutputStream() {
|
||||
return new ByteArrayOutputStream() {
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
try {
|
||||
super.close();
|
||||
}
|
||||
finally {
|
||||
myContent = new BinaryContent(buf, 0, size());
|
||||
if (myContext != null) {
|
||||
myContext.consumeOutputFile(OutputFileObject.this);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream openInputStream() throws IOException {
|
||||
final BinaryContent bytes = myContent;
|
||||
if (bytes != null) {
|
||||
return new ByteArrayInputStream(bytes.getBuffer(), bytes.getOffset(), bytes.getLength());
|
||||
}
|
||||
return new BufferedInputStream(new FileInputStream(myFile));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
|
||||
final BinaryContent content = myContent;
|
||||
if (content == null) {
|
||||
throw new FileNotFoundException(toUri().getPath());
|
||||
}
|
||||
return new String(content.getBuffer(), content.getOffset(), content.getLength());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public BinaryContent getContent() {
|
||||
return myContent;
|
||||
}
|
||||
|
||||
public void updateContent(@NotNull byte[] updatedContent) {
|
||||
myContent = new BinaryContent(updatedContent, 0, updatedContent.length);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return toUri().hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return obj instanceof JavaFileObject && toUri().equals(((JavaFileObject)obj).toUri());
|
||||
}
|
||||
}
|
||||
package org.jetbrains.jps.javac;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.jetbrains.jps.incremental.BinaryContent;
|
||||
import org.jetbrains.jps.incremental.Utils;
|
||||
|
||||
import javax.tools.*;
|
||||
import java.io.*;
|
||||
import java.net.URI;
|
||||
|
||||
/**
|
||||
* @author Eugene Zhuravlev
|
||||
* Date: 9/24/11
|
||||
*/
|
||||
public final class OutputFileObject extends SimpleJavaFileObject {
|
||||
@Nullable
|
||||
private final JavacFileManager.Context myContext;
|
||||
@Nullable
|
||||
private final File myOutputRoot;
|
||||
private final String myRelativePath;
|
||||
private final File myFile;
|
||||
@Nullable
|
||||
private final String myClassName;
|
||||
@Nullable private final URI mySourceUri;
|
||||
private volatile BinaryContent myContent;
|
||||
private final File mySourceFile;
|
||||
|
||||
public OutputFileObject(@NotNull JavacFileManager.Context context, @Nullable File outputRoot, String relativePath, @NotNull File file, @NotNull Kind kind, @Nullable String className, @Nullable final URI sourceUri) {
|
||||
this(context, outputRoot, relativePath, file, kind, className, sourceUri, null);
|
||||
}
|
||||
|
||||
public OutputFileObject(@Nullable JavacFileManager.Context context, @Nullable File outputRoot, String relativePath, @NotNull File file, @NotNull Kind kind, @Nullable String className, @Nullable final URI srcUri, @Nullable BinaryContent content) {
|
||||
super(Utils.toURI(file.getPath()), kind);
|
||||
myContext = context;
|
||||
mySourceUri = srcUri;
|
||||
myContent = content;
|
||||
myOutputRoot = outputRoot;
|
||||
myRelativePath = relativePath;
|
||||
myFile = file;
|
||||
myClassName = className != null? className.replace('/', '.') : null;
|
||||
mySourceFile = srcUri != null? Utils.convertToFile(srcUri) : null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public File getOutputRoot() {
|
||||
return myOutputRoot;
|
||||
}
|
||||
|
||||
public String getRelativePath() {
|
||||
return myRelativePath;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public File getFile() {
|
||||
return myFile;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getClassName() {
|
||||
return myClassName;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public File getSourceFile() {
|
||||
return mySourceFile;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public URI getSourceUri() {
|
||||
return mySourceUri;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ByteArrayOutputStream openOutputStream() {
|
||||
return new ByteArrayOutputStream() {
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
try {
|
||||
super.close();
|
||||
}
|
||||
finally {
|
||||
myContent = new BinaryContent(buf, 0, size());
|
||||
if (myContext != null) {
|
||||
myContext.consumeOutputFile(OutputFileObject.this);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream openInputStream() throws IOException {
|
||||
final BinaryContent bytes = myContent;
|
||||
if (bytes != null) {
|
||||
return new ByteArrayInputStream(bytes.getBuffer(), bytes.getOffset(), bytes.getLength());
|
||||
}
|
||||
return new BufferedInputStream(new FileInputStream(myFile));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
|
||||
final BinaryContent content = myContent;
|
||||
if (content == null) {
|
||||
throw new FileNotFoundException(toUri().getPath());
|
||||
}
|
||||
return new String(content.getBuffer(), content.getOffset(), content.getLength());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public BinaryContent getContent() {
|
||||
return myContent;
|
||||
}
|
||||
|
||||
public void updateContent(@NotNull byte[] updatedContent) {
|
||||
myContent = new BinaryContent(updatedContent, 0, updatedContent.length);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return toUri().hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return obj instanceof JavaFileObject && toUri().equals(((JavaFileObject)obj).toUri());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,81 +1,81 @@
|
||||
package org.jetbrains.ether;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* @author Eugene Zhuravlev
|
||||
* Date: 6/29/12
|
||||
*/
|
||||
public class LogParser {
|
||||
|
||||
private static final String COMPILING_START_STR = "incremental.java.JavaBuilder - Compiling";
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
final String logPath = args[0];
|
||||
|
||||
long totalTime = 0L;
|
||||
int totalFileCount = 0;
|
||||
final BufferedReader reader = new BufferedReader(new FileReader(new File(logPath)));
|
||||
try {
|
||||
String line = reader.readLine();
|
||||
while (line != null) {
|
||||
if (line.contains(COMPILING_START_STR)) {
|
||||
final long startTime = getTime(line);
|
||||
final String nextLine = reader.readLine();
|
||||
if (nextLine != null && nextLine.contains("- Dependency analysis found")) {
|
||||
final long endTime = getTime(nextLine);
|
||||
totalTime += (endTime - startTime);
|
||||
final int index = line.indexOf(COMPILING_START_STR);
|
||||
if (index > 0) {
|
||||
final StringBuilder buf = new StringBuilder();
|
||||
for (int idx = index + COMPILING_START_STR.length(); idx < line.length(); idx++) {
|
||||
final char ch = line.charAt(idx);
|
||||
if (ch == ' ' || ch == '\t') {
|
||||
continue;
|
||||
}
|
||||
if (!Character.isDigit(ch)) {
|
||||
break;
|
||||
}
|
||||
buf.append(ch);
|
||||
}
|
||||
if (buf.length() > 0) {
|
||||
final int fileCount = Integer.parseInt(buf.toString());
|
||||
totalFileCount += fileCount;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
line = reader.readLine();
|
||||
}
|
||||
}
|
||||
finally {
|
||||
reader.close();
|
||||
}
|
||||
|
||||
long millis = totalTime % 1000;
|
||||
long seconds = totalTime / 1000;
|
||||
long minutes = seconds / 60;
|
||||
seconds = seconds % 60;
|
||||
|
||||
System.out.println("Files compiled: " + totalFileCount);
|
||||
System.out.println("Total time spent compiling java " + minutes + " min " + seconds + " sec " + millis + " ms");
|
||||
}
|
||||
|
||||
|
||||
private static final int HOURS_START = 11;
|
||||
private static final int MINUTES_START = HOURS_START + 3;
|
||||
private static final int SECONDS_START = MINUTES_START + 3;
|
||||
private static final int MILLIS_START = SECONDS_START + 3;
|
||||
|
||||
private static long getTime(String line) {
|
||||
final int hours = Integer.parseInt(line.substring(HOURS_START, HOURS_START + 2));
|
||||
final int minutes = Integer.parseInt(line.substring(MINUTES_START, MINUTES_START + 2));
|
||||
final int seconds = Integer.parseInt(line.substring(SECONDS_START, SECONDS_START + 2));
|
||||
final int millis = Integer.parseInt(line.substring(MILLIS_START, MILLIS_START + 3));
|
||||
return millis + seconds * 1000 + minutes * 60000 + hours * 3600000;
|
||||
}
|
||||
|
||||
}
|
||||
package org.jetbrains.ether;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* @author Eugene Zhuravlev
|
||||
* Date: 6/29/12
|
||||
*/
|
||||
public class LogParser {
|
||||
|
||||
private static final String COMPILING_START_STR = "incremental.java.JavaBuilder - Compiling";
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
final String logPath = args[0];
|
||||
|
||||
long totalTime = 0L;
|
||||
int totalFileCount = 0;
|
||||
final BufferedReader reader = new BufferedReader(new FileReader(new File(logPath)));
|
||||
try {
|
||||
String line = reader.readLine();
|
||||
while (line != null) {
|
||||
if (line.contains(COMPILING_START_STR)) {
|
||||
final long startTime = getTime(line);
|
||||
final String nextLine = reader.readLine();
|
||||
if (nextLine != null && nextLine.contains("- Dependency analysis found")) {
|
||||
final long endTime = getTime(nextLine);
|
||||
totalTime += (endTime - startTime);
|
||||
final int index = line.indexOf(COMPILING_START_STR);
|
||||
if (index > 0) {
|
||||
final StringBuilder buf = new StringBuilder();
|
||||
for (int idx = index + COMPILING_START_STR.length(); idx < line.length(); idx++) {
|
||||
final char ch = line.charAt(idx);
|
||||
if (ch == ' ' || ch == '\t') {
|
||||
continue;
|
||||
}
|
||||
if (!Character.isDigit(ch)) {
|
||||
break;
|
||||
}
|
||||
buf.append(ch);
|
||||
}
|
||||
if (buf.length() > 0) {
|
||||
final int fileCount = Integer.parseInt(buf.toString());
|
||||
totalFileCount += fileCount;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
line = reader.readLine();
|
||||
}
|
||||
}
|
||||
finally {
|
||||
reader.close();
|
||||
}
|
||||
|
||||
long millis = totalTime % 1000;
|
||||
long seconds = totalTime / 1000;
|
||||
long minutes = seconds / 60;
|
||||
seconds = seconds % 60;
|
||||
|
||||
System.out.println("Files compiled: " + totalFileCount);
|
||||
System.out.println("Total time spent compiling java " + minutes + " min " + seconds + " sec " + millis + " ms");
|
||||
}
|
||||
|
||||
|
||||
private static final int HOURS_START = 11;
|
||||
private static final int MINUTES_START = HOURS_START + 3;
|
||||
private static final int SECONDS_START = MINUTES_START + 3;
|
||||
private static final int MILLIS_START = SECONDS_START + 3;
|
||||
|
||||
private static long getTime(String line) {
|
||||
final int hours = Integer.parseInt(line.substring(HOURS_START, HOURS_START + 2));
|
||||
final int minutes = Integer.parseInt(line.substring(MINUTES_START, MINUTES_START + 2));
|
||||
final int seconds = Integer.parseInt(line.substring(SECONDS_START, SECONDS_START + 2));
|
||||
final int millis = Integer.parseInt(line.substring(MILLIS_START, MILLIS_START + 3));
|
||||
return millis + seconds * 1000 + minutes * 60000 + hours * 3600000;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+10
-10
@@ -1,10 +1,10 @@
|
||||
Copyright (c) 2008, Nathan Sweet
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of Esoteric Software nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
Copyright (c) 2008, Nathan Sweet
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of Esoteric Software nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
package com.intellij.openapi.application;
|
||||
|
||||
public abstract class AccessToken {
|
||||
protected void acquired() {
|
||||
}
|
||||
|
||||
protected void released() {
|
||||
}
|
||||
|
||||
public abstract void finish();
|
||||
|
||||
public static final AccessToken EMPTY_ACCESS_TOKEN = new AccessToken() {
|
||||
@Override
|
||||
public void finish() {}
|
||||
};
|
||||
}
|
||||
package com.intellij.openapi.application;
|
||||
|
||||
public abstract class AccessToken {
|
||||
protected void acquired() {
|
||||
}
|
||||
|
||||
protected void released() {
|
||||
}
|
||||
|
||||
public abstract void finish();
|
||||
|
||||
public static final AccessToken EMPTY_ACCESS_TOKEN = new AccessToken() {
|
||||
@Override
|
||||
public void finish() {}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,232 +1,232 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.stubs;
|
||||
|
||||
import com.intellij.openapi.diagnostic.LogUtil;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.util.LowMemoryWatcher;
|
||||
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream;
|
||||
import com.intellij.util.containers.SLRUCache;
|
||||
import com.intellij.util.io.AbstractStringEnumerator;
|
||||
import com.intellij.util.io.DataInputOutputUtil;
|
||||
import com.intellij.util.io.IOUtil;
|
||||
import gnu.trove.TIntObjectHashMap;
|
||||
import gnu.trove.TObjectIntHashMap;
|
||||
import jsr166e.SequenceLock;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
|
||||
/**
|
||||
* Author: dmitrylomov
|
||||
*/
|
||||
public class StubSerializationHelper {
|
||||
|
||||
private final static Logger LOG = Logger.getInstance(StubSerializationHelper.class);
|
||||
private AbstractStringEnumerator myNameStorage;
|
||||
|
||||
protected final TIntObjectHashMap<ObjectStubSerializer> myIdToSerializer = new TIntObjectHashMap<ObjectStubSerializer>();
|
||||
protected final TObjectIntHashMap<ObjectStubSerializer> mySerializerToId = new TObjectIntHashMap<ObjectStubSerializer>();
|
||||
|
||||
public StubSerializationHelper(AbstractStringEnumerator nameStorage) {
|
||||
myNameStorage = nameStorage;
|
||||
}
|
||||
|
||||
public void assignId(@NotNull final ObjectStubSerializer serializer) throws IOException {
|
||||
final int id = persistentId(serializer);
|
||||
final ObjectStubSerializer old = myIdToSerializer.put(id, serializer);
|
||||
assert old == null : "ID: " + serializer.getExternalId() + " is not unique; Already registered serializer with this ID: " + old.getClass().getName();
|
||||
|
||||
final int oldId = mySerializerToId.put(serializer, id);
|
||||
assert oldId == 0 : "Serializer " + serializer + " is already registered; Old ID:" + oldId;
|
||||
}
|
||||
|
||||
private int persistentId(@NotNull final ObjectStubSerializer serializer) throws IOException {
|
||||
if (myNameStorage == null) {
|
||||
throw new IOException("SerializationManager's name storage failed to initialize");
|
||||
}
|
||||
return myNameStorage.enumerate(serializer.getExternalId());
|
||||
}
|
||||
|
||||
private void doSerialize(final Stub rootStub, final StubOutputStream stream) throws IOException {
|
||||
final ObjectStubSerializer serializer = StubSerializationUtil.getSerializer(rootStub);
|
||||
|
||||
DataInputOutputUtil.writeINT(stream, getClassId(serializer));
|
||||
serializer.serialize(rootStub, stream);
|
||||
|
||||
final List<? extends Stub> children = rootStub.getChildrenStubs();
|
||||
final int childrenSize = children.size();
|
||||
DataInputOutputUtil.writeINT(stream, childrenSize);
|
||||
for (int i = 0; i < childrenSize; ++i) {
|
||||
doSerialize(children.get(i), stream);
|
||||
}
|
||||
}
|
||||
|
||||
public void serialize(Stub rootStub, OutputStream stream) throws IOException {
|
||||
BufferExposingByteArrayOutputStream out = new BufferExposingByteArrayOutputStream();
|
||||
FileLocalStringEnumerator storage = new FileLocalStringEnumerator();
|
||||
StubOutputStream stubOutputStream = new StubOutputStream(out, storage);
|
||||
|
||||
doSerialize(rootStub, stubOutputStream);
|
||||
DataOutputStream resultStream = new DataOutputStream(stream);
|
||||
DataInputOutputUtil.writeINT(resultStream, storage.myStrings.size());
|
||||
byte[] buffer = IOUtil.allocReadWriteUTFBuffer();
|
||||
for(String s:storage.myStrings) {
|
||||
IOUtil.writeUTFFast(buffer, resultStream, s);
|
||||
}
|
||||
resultStream.write(out.getInternalBuffer(), 0, out.size());
|
||||
}
|
||||
|
||||
private int getClassId(final ObjectStubSerializer serializer) {
|
||||
final int idValue = mySerializerToId.get(serializer);
|
||||
assert idValue != 0: "No ID found for serializer " + LogUtil.objectAndClass(serializer);
|
||||
return idValue;
|
||||
}
|
||||
|
||||
private static class RecentStringInterner {
|
||||
private final int myStripeMask;
|
||||
private final SLRUCache<String, String>[] myInterns;
|
||||
private final Lock[] myStripeLocks;
|
||||
private final LowMemoryWatcher myClearingCallback;
|
||||
|
||||
private RecentStringInterner(int capacity) {
|
||||
final int stripes = 16;
|
||||
myInterns = new SLRUCache[stripes];
|
||||
myStripeLocks = new Lock[myInterns.length];
|
||||
for(int i = 0; i < myInterns.length; ++i) {
|
||||
myInterns[i] = new SLRUCache<String, String>(capacity / stripes, capacity / stripes) {
|
||||
@NotNull
|
||||
@Override
|
||||
public String createValue(String key) {
|
||||
return key;
|
||||
}
|
||||
};
|
||||
myStripeLocks[i] = new SequenceLock();
|
||||
}
|
||||
|
||||
assert Integer.highestOneBit(stripes) == stripes;
|
||||
myStripeMask = stripes - 1;
|
||||
myClearingCallback = LowMemoryWatcher.register(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
clear();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
String get(String s) {
|
||||
final int stripe = Math.abs(s.hashCode()) & myStripeMask;
|
||||
try {
|
||||
myStripeLocks[stripe].lock();
|
||||
return myInterns[stripe].get(s);
|
||||
} finally {
|
||||
myStripeLocks[stripe].unlock();
|
||||
}
|
||||
}
|
||||
|
||||
void clear() {
|
||||
for(int i = 0; i < myInterns.length; ++i) {
|
||||
myStripeLocks[i].lock();
|
||||
myInterns[i].clear();
|
||||
myStripeLocks[i].unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final RecentStringInterner myStringInterner = new RecentStringInterner(8192);
|
||||
|
||||
public Stub deserialize(InputStream stream) throws IOException, SerializerNotFoundException {
|
||||
FileLocalStringEnumerator storage = new FileLocalStringEnumerator();
|
||||
StubInputStream inputStream = new StubInputStream(stream, storage);
|
||||
final int size = DataInputOutputUtil.readINT(inputStream);
|
||||
byte[] buffer = IOUtil.allocReadWriteUTFBuffer();
|
||||
|
||||
int i = 1;
|
||||
while(i <= size) {
|
||||
String s = myStringInterner.get(IOUtil.readUTFFast(buffer, inputStream));
|
||||
storage.myStrings.add(s);
|
||||
storage.myEnumerates.put(s, i);
|
||||
++i;
|
||||
}
|
||||
return deserialize(inputStream, null);
|
||||
}
|
||||
|
||||
private Stub deserialize(StubInputStream stream, @Nullable Stub parentStub) throws IOException, SerializerNotFoundException {
|
||||
final int id = DataInputOutputUtil.readINT(stream);
|
||||
final ObjectStubSerializer serializer = getClassById(id);
|
||||
if (serializer == null) {
|
||||
throw new SerializerNotFoundException("No serializer registered for stub: ID=" + id + "; parent stub class=" + (parentStub != null? parentStub.getClass().getName() : "null"));
|
||||
}
|
||||
|
||||
Stub stub = serializer.deserialize(stream, parentStub);
|
||||
int childCount = DataInputOutputUtil.readINT(stream);
|
||||
for (int i = 0; i < childCount; i++) {
|
||||
deserialize(stream, stub);
|
||||
}
|
||||
return stub;
|
||||
}
|
||||
|
||||
|
||||
private ObjectStubSerializer getClassById(int id) {
|
||||
return myIdToSerializer.get(id);
|
||||
}
|
||||
|
||||
private static class FileLocalStringEnumerator implements AbstractStringEnumerator {
|
||||
private final TObjectIntHashMap<String> myEnumerates = new TObjectIntHashMap<String>();
|
||||
private final ArrayList<String> myStrings = new ArrayList<String>();
|
||||
|
||||
@Override
|
||||
public int enumerate(@Nullable String value) throws IOException {
|
||||
if (value == null) return 0;
|
||||
int i = myEnumerates.get(value);
|
||||
if (i == 0) {
|
||||
myEnumerates.put(value, i = myStrings.size() + 1);
|
||||
myStrings.add(value);
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String valueOf(int idx) throws IOException {
|
||||
if (idx == 0) return null;
|
||||
return myStrings.get(idx - 1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void markCorrupted() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDirty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void force() {
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.psi.stubs;
|
||||
|
||||
import com.intellij.openapi.diagnostic.LogUtil;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.util.LowMemoryWatcher;
|
||||
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream;
|
||||
import com.intellij.util.containers.SLRUCache;
|
||||
import com.intellij.util.io.AbstractStringEnumerator;
|
||||
import com.intellij.util.io.DataInputOutputUtil;
|
||||
import com.intellij.util.io.IOUtil;
|
||||
import gnu.trove.TIntObjectHashMap;
|
||||
import gnu.trove.TObjectIntHashMap;
|
||||
import jsr166e.SequenceLock;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
|
||||
/**
|
||||
* Author: dmitrylomov
|
||||
*/
|
||||
public class StubSerializationHelper {
|
||||
|
||||
private final static Logger LOG = Logger.getInstance(StubSerializationHelper.class);
|
||||
private AbstractStringEnumerator myNameStorage;
|
||||
|
||||
protected final TIntObjectHashMap<ObjectStubSerializer> myIdToSerializer = new TIntObjectHashMap<ObjectStubSerializer>();
|
||||
protected final TObjectIntHashMap<ObjectStubSerializer> mySerializerToId = new TObjectIntHashMap<ObjectStubSerializer>();
|
||||
|
||||
public StubSerializationHelper(AbstractStringEnumerator nameStorage) {
|
||||
myNameStorage = nameStorage;
|
||||
}
|
||||
|
||||
public void assignId(@NotNull final ObjectStubSerializer serializer) throws IOException {
|
||||
final int id = persistentId(serializer);
|
||||
final ObjectStubSerializer old = myIdToSerializer.put(id, serializer);
|
||||
assert old == null : "ID: " + serializer.getExternalId() + " is not unique; Already registered serializer with this ID: " + old.getClass().getName();
|
||||
|
||||
final int oldId = mySerializerToId.put(serializer, id);
|
||||
assert oldId == 0 : "Serializer " + serializer + " is already registered; Old ID:" + oldId;
|
||||
}
|
||||
|
||||
private int persistentId(@NotNull final ObjectStubSerializer serializer) throws IOException {
|
||||
if (myNameStorage == null) {
|
||||
throw new IOException("SerializationManager's name storage failed to initialize");
|
||||
}
|
||||
return myNameStorage.enumerate(serializer.getExternalId());
|
||||
}
|
||||
|
||||
private void doSerialize(final Stub rootStub, final StubOutputStream stream) throws IOException {
|
||||
final ObjectStubSerializer serializer = StubSerializationUtil.getSerializer(rootStub);
|
||||
|
||||
DataInputOutputUtil.writeINT(stream, getClassId(serializer));
|
||||
serializer.serialize(rootStub, stream);
|
||||
|
||||
final List<? extends Stub> children = rootStub.getChildrenStubs();
|
||||
final int childrenSize = children.size();
|
||||
DataInputOutputUtil.writeINT(stream, childrenSize);
|
||||
for (int i = 0; i < childrenSize; ++i) {
|
||||
doSerialize(children.get(i), stream);
|
||||
}
|
||||
}
|
||||
|
||||
public void serialize(Stub rootStub, OutputStream stream) throws IOException {
|
||||
BufferExposingByteArrayOutputStream out = new BufferExposingByteArrayOutputStream();
|
||||
FileLocalStringEnumerator storage = new FileLocalStringEnumerator();
|
||||
StubOutputStream stubOutputStream = new StubOutputStream(out, storage);
|
||||
|
||||
doSerialize(rootStub, stubOutputStream);
|
||||
DataOutputStream resultStream = new DataOutputStream(stream);
|
||||
DataInputOutputUtil.writeINT(resultStream, storage.myStrings.size());
|
||||
byte[] buffer = IOUtil.allocReadWriteUTFBuffer();
|
||||
for(String s:storage.myStrings) {
|
||||
IOUtil.writeUTFFast(buffer, resultStream, s);
|
||||
}
|
||||
resultStream.write(out.getInternalBuffer(), 0, out.size());
|
||||
}
|
||||
|
||||
private int getClassId(final ObjectStubSerializer serializer) {
|
||||
final int idValue = mySerializerToId.get(serializer);
|
||||
assert idValue != 0: "No ID found for serializer " + LogUtil.objectAndClass(serializer);
|
||||
return idValue;
|
||||
}
|
||||
|
||||
private static class RecentStringInterner {
|
||||
private final int myStripeMask;
|
||||
private final SLRUCache<String, String>[] myInterns;
|
||||
private final Lock[] myStripeLocks;
|
||||
private final LowMemoryWatcher myClearingCallback;
|
||||
|
||||
private RecentStringInterner(int capacity) {
|
||||
final int stripes = 16;
|
||||
myInterns = new SLRUCache[stripes];
|
||||
myStripeLocks = new Lock[myInterns.length];
|
||||
for(int i = 0; i < myInterns.length; ++i) {
|
||||
myInterns[i] = new SLRUCache<String, String>(capacity / stripes, capacity / stripes) {
|
||||
@NotNull
|
||||
@Override
|
||||
public String createValue(String key) {
|
||||
return key;
|
||||
}
|
||||
};
|
||||
myStripeLocks[i] = new SequenceLock();
|
||||
}
|
||||
|
||||
assert Integer.highestOneBit(stripes) == stripes;
|
||||
myStripeMask = stripes - 1;
|
||||
myClearingCallback = LowMemoryWatcher.register(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
clear();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
String get(String s) {
|
||||
final int stripe = Math.abs(s.hashCode()) & myStripeMask;
|
||||
try {
|
||||
myStripeLocks[stripe].lock();
|
||||
return myInterns[stripe].get(s);
|
||||
} finally {
|
||||
myStripeLocks[stripe].unlock();
|
||||
}
|
||||
}
|
||||
|
||||
void clear() {
|
||||
for(int i = 0; i < myInterns.length; ++i) {
|
||||
myStripeLocks[i].lock();
|
||||
myInterns[i].clear();
|
||||
myStripeLocks[i].unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final RecentStringInterner myStringInterner = new RecentStringInterner(8192);
|
||||
|
||||
public Stub deserialize(InputStream stream) throws IOException, SerializerNotFoundException {
|
||||
FileLocalStringEnumerator storage = new FileLocalStringEnumerator();
|
||||
StubInputStream inputStream = new StubInputStream(stream, storage);
|
||||
final int size = DataInputOutputUtil.readINT(inputStream);
|
||||
byte[] buffer = IOUtil.allocReadWriteUTFBuffer();
|
||||
|
||||
int i = 1;
|
||||
while(i <= size) {
|
||||
String s = myStringInterner.get(IOUtil.readUTFFast(buffer, inputStream));
|
||||
storage.myStrings.add(s);
|
||||
storage.myEnumerates.put(s, i);
|
||||
++i;
|
||||
}
|
||||
return deserialize(inputStream, null);
|
||||
}
|
||||
|
||||
private Stub deserialize(StubInputStream stream, @Nullable Stub parentStub) throws IOException, SerializerNotFoundException {
|
||||
final int id = DataInputOutputUtil.readINT(stream);
|
||||
final ObjectStubSerializer serializer = getClassById(id);
|
||||
if (serializer == null) {
|
||||
throw new SerializerNotFoundException("No serializer registered for stub: ID=" + id + "; parent stub class=" + (parentStub != null? parentStub.getClass().getName() : "null"));
|
||||
}
|
||||
|
||||
Stub stub = serializer.deserialize(stream, parentStub);
|
||||
int childCount = DataInputOutputUtil.readINT(stream);
|
||||
for (int i = 0; i < childCount; i++) {
|
||||
deserialize(stream, stub);
|
||||
}
|
||||
return stub;
|
||||
}
|
||||
|
||||
|
||||
private ObjectStubSerializer getClassById(int id) {
|
||||
return myIdToSerializer.get(id);
|
||||
}
|
||||
|
||||
private static class FileLocalStringEnumerator implements AbstractStringEnumerator {
|
||||
private final TObjectIntHashMap<String> myEnumerates = new TObjectIntHashMap<String>();
|
||||
private final ArrayList<String> myStrings = new ArrayList<String>();
|
||||
|
||||
@Override
|
||||
public int enumerate(@Nullable String value) throws IOException {
|
||||
if (value == null) return 0;
|
||||
int i = myEnumerates.get(value);
|
||||
if (i == 0) {
|
||||
myEnumerates.put(value, i = myStrings.size() + 1);
|
||||
myStrings.add(value);
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String valueOf(int idx) throws IOException {
|
||||
if (idx == 0) return null;
|
||||
return myStrings.get(idx - 1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void markCorrupted() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDirty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void force() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,155 +1,155 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.mock;
|
||||
|
||||
import com.intellij.openapi.Disposable;
|
||||
import com.intellij.openapi.components.ExtensionAreas;
|
||||
import com.intellij.openapi.components.ProjectComponent;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.extensions.ExtensionPointName;
|
||||
import com.intellij.openapi.extensions.Extensions;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.util.Condition;
|
||||
import com.intellij.openapi.util.Disposer;
|
||||
import com.intellij.openapi.vfs.VirtualFile;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.picocontainer.PicoContainer;
|
||||
|
||||
/**
|
||||
* @author yole
|
||||
*/
|
||||
public class MockProject extends MockComponentManager implements Project {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.mock.MockProject");
|
||||
private VirtualFile myBaseDir;
|
||||
|
||||
public MockProject(PicoContainer parent, @NotNull Disposable parentDisposable) {
|
||||
super(parent, parentDisposable);
|
||||
Extensions.instantiateArea(ExtensionAreas.IDEA_PROJECT, this, null);
|
||||
Disposer.register(parentDisposable, new Disposable() {
|
||||
@Override
|
||||
public void dispose() {
|
||||
Extensions.disposeArea(MockProject.this);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDefault() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public Condition getDisposed() {
|
||||
return new Condition() {
|
||||
@Override
|
||||
public boolean value(final Object o) {
|
||||
return isDisposed();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOpen() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInitialized() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VirtualFile getProjectFile() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getName() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
@NonNls
|
||||
public String getPresentableUrl() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
@NonNls
|
||||
public String getLocationHash() {
|
||||
return "mock";
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
@NonNls
|
||||
public String getLocation() {
|
||||
throw new UnsupportedOperationException("Method getLocation not implemented in " + getClass());
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getProjectFilePath() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public VirtualFile getWorkspaceFile() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void setBaseDir(VirtualFile baseDir) {
|
||||
myBaseDir = baseDir;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public VirtualFile getBaseDir() {
|
||||
return myBaseDir;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBasePath() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T[] getExtensions(final ExtensionPointName<T> extensionPointName) {
|
||||
return Extensions.getArea(this).getExtensionPoint(extensionPointName).getExtensions();
|
||||
}
|
||||
|
||||
public void projectOpened() {
|
||||
final ProjectComponent[] components = getComponents(ProjectComponent.class);
|
||||
for (ProjectComponent component : components) {
|
||||
try {
|
||||
component.projectOpened();
|
||||
}
|
||||
catch (Throwable e) {
|
||||
LOG.error(component.toString(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.mock;
|
||||
|
||||
import com.intellij.openapi.Disposable;
|
||||
import com.intellij.openapi.components.ExtensionAreas;
|
||||
import com.intellij.openapi.components.ProjectComponent;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.extensions.ExtensionPointName;
|
||||
import com.intellij.openapi.extensions.Extensions;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.util.Condition;
|
||||
import com.intellij.openapi.util.Disposer;
|
||||
import com.intellij.openapi.vfs.VirtualFile;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.picocontainer.PicoContainer;
|
||||
|
||||
/**
|
||||
* @author yole
|
||||
*/
|
||||
public class MockProject extends MockComponentManager implements Project {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.mock.MockProject");
|
||||
private VirtualFile myBaseDir;
|
||||
|
||||
public MockProject(PicoContainer parent, @NotNull Disposable parentDisposable) {
|
||||
super(parent, parentDisposable);
|
||||
Extensions.instantiateArea(ExtensionAreas.IDEA_PROJECT, this, null);
|
||||
Disposer.register(parentDisposable, new Disposable() {
|
||||
@Override
|
||||
public void dispose() {
|
||||
Extensions.disposeArea(MockProject.this);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDefault() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public Condition getDisposed() {
|
||||
return new Condition() {
|
||||
@Override
|
||||
public boolean value(final Object o) {
|
||||
return isDisposed();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOpen() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInitialized() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public VirtualFile getProjectFile() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getName() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
@NonNls
|
||||
public String getPresentableUrl() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
@NonNls
|
||||
public String getLocationHash() {
|
||||
return "mock";
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
@NonNls
|
||||
public String getLocation() {
|
||||
throw new UnsupportedOperationException("Method getLocation not implemented in " + getClass());
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getProjectFilePath() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public VirtualFile getWorkspaceFile() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void setBaseDir(VirtualFile baseDir) {
|
||||
myBaseDir = baseDir;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public VirtualFile getBaseDir() {
|
||||
return myBaseDir;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBasePath() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T[] getExtensions(final ExtensionPointName<T> extensionPointName) {
|
||||
return Extensions.getArea(this).getExtensionPoint(extensionPointName).getExtensions();
|
||||
}
|
||||
|
||||
public void projectOpened() {
|
||||
final ProjectComponent[] components = getComponents(ProjectComponent.class);
|
||||
for (ProjectComponent component : components) {
|
||||
try {
|
||||
component.projectOpened();
|
||||
}
|
||||
catch (Throwable e) {
|
||||
LOG.error(component.toString(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+102
-102
@@ -1,102 +1,102 @@
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.openapi.application.impl;
|
||||
|
||||
import com.intellij.openapi.application.ModalityState;
|
||||
import com.intellij.openapi.progress.ProgressIndicator;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class ModalityStateEx extends ModalityState {
|
||||
private static final WeakReference[] EMPTY_REFS_ARRAY = new WeakReference[0];
|
||||
|
||||
private final WeakReference[] myModalEntities;
|
||||
|
||||
public ModalityStateEx() {
|
||||
this(EMPTY_REFS_ARRAY);
|
||||
}
|
||||
|
||||
public ModalityStateEx(@NotNull Object[] modalEntities) {
|
||||
if (modalEntities.length > 0) {
|
||||
myModalEntities = new WeakReference[modalEntities.length];
|
||||
for (int i = 0; i < modalEntities.length; i++) {
|
||||
Object entity = modalEntities[i];
|
||||
myModalEntities[i] = new WeakReference<Object>(entity);
|
||||
}
|
||||
}
|
||||
else{
|
||||
myModalEntities = EMPTY_REFS_ARRAY;
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ModalityState appendProgress(@NotNull ProgressIndicator progress){
|
||||
return appendEntity(progress);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
ModalityStateEx appendEntity(@NotNull Object anEntity){
|
||||
ArrayList<Object> list = new ArrayList<Object>();
|
||||
for (WeakReference modalEntity : myModalEntities) {
|
||||
Object entity = modalEntity.get();
|
||||
if (entity == null) continue;
|
||||
list.add(entity);
|
||||
}
|
||||
list.add(anEntity);
|
||||
return new ModalityStateEx(list.toArray());
|
||||
}
|
||||
|
||||
private static boolean contains(WeakReference[] array, Object o){
|
||||
for (WeakReference reference : array) {
|
||||
Object o1 = reference.get();
|
||||
if (o1 == null) continue;
|
||||
if (o1.equals(o)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean dominates(@NotNull ModalityState anotherState){
|
||||
if (anotherState == ModalityState.any()) return false;
|
||||
|
||||
for (WeakReference modalEntity : myModalEntities) {
|
||||
Object entity = modalEntity.get();
|
||||
if (entity == null) continue;
|
||||
if (!contains(((ModalityStateEx)anotherState).myModalEntities, entity)) return true; // I have entity which is absent in anotherState
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean contains(Object modalEntity) {
|
||||
return contains(myModalEntities, modalEntity);
|
||||
}
|
||||
|
||||
@NonNls
|
||||
public String toString() {
|
||||
if (myModalEntities.length == 0) return "ModalityState.NON_MODAL";
|
||||
@NonNls StringBuilder buffer = new StringBuilder();
|
||||
buffer.append("ModalityState:");
|
||||
for (int i = 0; i < myModalEntities.length; i++) {
|
||||
Object entity = myModalEntities[i].get();
|
||||
if (i > 0) buffer.append(", ");
|
||||
buffer.append(entity);
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.openapi.application.impl;
|
||||
|
||||
import com.intellij.openapi.application.ModalityState;
|
||||
import com.intellij.openapi.progress.ProgressIndicator;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class ModalityStateEx extends ModalityState {
|
||||
private static final WeakReference[] EMPTY_REFS_ARRAY = new WeakReference[0];
|
||||
|
||||
private final WeakReference[] myModalEntities;
|
||||
|
||||
public ModalityStateEx() {
|
||||
this(EMPTY_REFS_ARRAY);
|
||||
}
|
||||
|
||||
public ModalityStateEx(@NotNull Object[] modalEntities) {
|
||||
if (modalEntities.length > 0) {
|
||||
myModalEntities = new WeakReference[modalEntities.length];
|
||||
for (int i = 0; i < modalEntities.length; i++) {
|
||||
Object entity = modalEntities[i];
|
||||
myModalEntities[i] = new WeakReference<Object>(entity);
|
||||
}
|
||||
}
|
||||
else{
|
||||
myModalEntities = EMPTY_REFS_ARRAY;
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ModalityState appendProgress(@NotNull ProgressIndicator progress){
|
||||
return appendEntity(progress);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
ModalityStateEx appendEntity(@NotNull Object anEntity){
|
||||
ArrayList<Object> list = new ArrayList<Object>();
|
||||
for (WeakReference modalEntity : myModalEntities) {
|
||||
Object entity = modalEntity.get();
|
||||
if (entity == null) continue;
|
||||
list.add(entity);
|
||||
}
|
||||
list.add(anEntity);
|
||||
return new ModalityStateEx(list.toArray());
|
||||
}
|
||||
|
||||
private static boolean contains(WeakReference[] array, Object o){
|
||||
for (WeakReference reference : array) {
|
||||
Object o1 = reference.get();
|
||||
if (o1 == null) continue;
|
||||
if (o1.equals(o)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean dominates(@NotNull ModalityState anotherState){
|
||||
if (anotherState == ModalityState.any()) return false;
|
||||
|
||||
for (WeakReference modalEntity : myModalEntities) {
|
||||
Object entity = modalEntity.get();
|
||||
if (entity == null) continue;
|
||||
if (!contains(((ModalityStateEx)anotherState).myModalEntities, entity)) return true; // I have entity which is absent in anotherState
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean contains(Object modalEntity) {
|
||||
return contains(myModalEntities, modalEntity);
|
||||
}
|
||||
|
||||
@NonNls
|
||||
public String toString() {
|
||||
if (myModalEntities.length == 0) return "ModalityState.NON_MODAL";
|
||||
@NonNls StringBuilder buffer = new StringBuilder();
|
||||
buffer.append("ModalityState:");
|
||||
for (int i = 0; i < myModalEntities.length; i++) {
|
||||
Object entity = myModalEntities[i].get();
|
||||
if (i > 0) buffer.append(", ");
|
||||
buffer.append(entity);
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
}
|
||||
|
||||
+118
-118
@@ -1,118 +1,118 @@
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.openapi.editor.ex.util;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* Expands {@link SegmentArray} contract in providing ability to attach additional <code>'short'</code> variable to target segment,
|
||||
* i.e. holds mappings like {@code 'index <-> (data, (start; end))'}.
|
||||
* <p/>
|
||||
* Not thread-safe.
|
||||
*/
|
||||
public class SegmentArrayWithData extends SegmentArray {
|
||||
private short[] myData;
|
||||
|
||||
public SegmentArrayWithData() {
|
||||
myData = new short[INITIAL_SIZE];
|
||||
}
|
||||
|
||||
public void setElementAt(int i, int startOffset, int endOffset, int data) {
|
||||
if (data < 0 && data > Short.MAX_VALUE) throw new IndexOutOfBoundsException("data out of short range" + data);
|
||||
super.setElementAt(i, startOffset, endOffset);
|
||||
myData = reallocateArray(myData, i+1);
|
||||
myData[i] = (short)data;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(int startIndex, int endIndex) {
|
||||
myData = remove(myData, startIndex, endIndex);
|
||||
super.remove(startIndex, endIndex);
|
||||
}
|
||||
|
||||
public void replace(int startIndex, int endIndex, @NotNull SegmentArrayWithData newData) {
|
||||
int oldLen = endIndex - startIndex;
|
||||
int newLen = newData.getSegmentCount();
|
||||
|
||||
int delta = newLen - oldLen;
|
||||
if (delta < 0) {
|
||||
remove(endIndex + delta, endIndex);
|
||||
}
|
||||
else if (delta > 0) {
|
||||
SegmentArrayWithData deltaData = new SegmentArrayWithData();
|
||||
for (int i = oldLen; i < newLen; i++) {
|
||||
deltaData.setElementAt(i - oldLen, newData.getSegmentStart(i), newData.getSegmentEnd(i), newData.getSegmentData(i));
|
||||
}
|
||||
insert(deltaData, startIndex + oldLen);
|
||||
}
|
||||
|
||||
int common = Math.min(newLen, oldLen);
|
||||
replace(startIndex, newData, common);
|
||||
}
|
||||
|
||||
|
||||
protected void replace(int startOffset, @NotNull SegmentArrayWithData data, int len) {
|
||||
System.arraycopy(data.myData, 0, myData, startOffset, len);
|
||||
super.replace(startOffset, data, len);
|
||||
}
|
||||
|
||||
public void insert(@NotNull SegmentArrayWithData segmentArray, int startIndex) {
|
||||
myData = insert(myData, segmentArray.myData, startIndex, segmentArray.getSegmentCount());
|
||||
super.insert(segmentArray, startIndex);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private short[] insert(@NotNull short[] array, @NotNull short[] insertArray, int startIndex, int insertLength) {
|
||||
short[] newArray = reallocateArray(array, mySegmentCount + insertLength);
|
||||
if (startIndex < mySegmentCount) {
|
||||
System.arraycopy(newArray, startIndex, newArray, startIndex + insertLength, mySegmentCount - startIndex);
|
||||
}
|
||||
System.arraycopy(insertArray, 0, newArray, startIndex, insertLength);
|
||||
return newArray;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private short[] remove(@NotNull short[] array, int startIndex, int endIndex) {
|
||||
if (endIndex < mySegmentCount) {
|
||||
System.arraycopy(array, endIndex, array, startIndex, mySegmentCount - endIndex);
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
public short getSegmentData(int index) {
|
||||
if(index < 0 || index >= mySegmentCount) {
|
||||
throw new IndexOutOfBoundsException("Wrong index: " + index);
|
||||
}
|
||||
return myData[index];
|
||||
}
|
||||
|
||||
public void setSegmentData(int index, int data) {
|
||||
if(index < 0 || index >= mySegmentCount) throw new IndexOutOfBoundsException("Wrong index: " + index);
|
||||
if (data < 0 && data > Short.MAX_VALUE) throw new IndexOutOfBoundsException("data out of short range" + data);
|
||||
myData[index] = (short)data;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private static short[] reallocateArray(@NotNull short[] array, int index) {
|
||||
if (index < array.length) return array;
|
||||
|
||||
short[] newArray = new short[calcCapacity(array.length, index)];
|
||||
System.arraycopy(array, 0, newArray, 0, array.length);
|
||||
return newArray;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.openapi.editor.ex.util;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* Expands {@link SegmentArray} contract in providing ability to attach additional <code>'short'</code> variable to target segment,
|
||||
* i.e. holds mappings like {@code 'index <-> (data, (start; end))'}.
|
||||
* <p/>
|
||||
* Not thread-safe.
|
||||
*/
|
||||
public class SegmentArrayWithData extends SegmentArray {
|
||||
private short[] myData;
|
||||
|
||||
public SegmentArrayWithData() {
|
||||
myData = new short[INITIAL_SIZE];
|
||||
}
|
||||
|
||||
public void setElementAt(int i, int startOffset, int endOffset, int data) {
|
||||
if (data < 0 && data > Short.MAX_VALUE) throw new IndexOutOfBoundsException("data out of short range" + data);
|
||||
super.setElementAt(i, startOffset, endOffset);
|
||||
myData = reallocateArray(myData, i+1);
|
||||
myData[i] = (short)data;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(int startIndex, int endIndex) {
|
||||
myData = remove(myData, startIndex, endIndex);
|
||||
super.remove(startIndex, endIndex);
|
||||
}
|
||||
|
||||
public void replace(int startIndex, int endIndex, @NotNull SegmentArrayWithData newData) {
|
||||
int oldLen = endIndex - startIndex;
|
||||
int newLen = newData.getSegmentCount();
|
||||
|
||||
int delta = newLen - oldLen;
|
||||
if (delta < 0) {
|
||||
remove(endIndex + delta, endIndex);
|
||||
}
|
||||
else if (delta > 0) {
|
||||
SegmentArrayWithData deltaData = new SegmentArrayWithData();
|
||||
for (int i = oldLen; i < newLen; i++) {
|
||||
deltaData.setElementAt(i - oldLen, newData.getSegmentStart(i), newData.getSegmentEnd(i), newData.getSegmentData(i));
|
||||
}
|
||||
insert(deltaData, startIndex + oldLen);
|
||||
}
|
||||
|
||||
int common = Math.min(newLen, oldLen);
|
||||
replace(startIndex, newData, common);
|
||||
}
|
||||
|
||||
|
||||
protected void replace(int startOffset, @NotNull SegmentArrayWithData data, int len) {
|
||||
System.arraycopy(data.myData, 0, myData, startOffset, len);
|
||||
super.replace(startOffset, data, len);
|
||||
}
|
||||
|
||||
public void insert(@NotNull SegmentArrayWithData segmentArray, int startIndex) {
|
||||
myData = insert(myData, segmentArray.myData, startIndex, segmentArray.getSegmentCount());
|
||||
super.insert(segmentArray, startIndex);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private short[] insert(@NotNull short[] array, @NotNull short[] insertArray, int startIndex, int insertLength) {
|
||||
short[] newArray = reallocateArray(array, mySegmentCount + insertLength);
|
||||
if (startIndex < mySegmentCount) {
|
||||
System.arraycopy(newArray, startIndex, newArray, startIndex + insertLength, mySegmentCount - startIndex);
|
||||
}
|
||||
System.arraycopy(insertArray, 0, newArray, startIndex, insertLength);
|
||||
return newArray;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private short[] remove(@NotNull short[] array, int startIndex, int endIndex) {
|
||||
if (endIndex < mySegmentCount) {
|
||||
System.arraycopy(array, endIndex, array, startIndex, mySegmentCount - endIndex);
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
public short getSegmentData(int index) {
|
||||
if(index < 0 || index >= mySegmentCount) {
|
||||
throw new IndexOutOfBoundsException("Wrong index: " + index);
|
||||
}
|
||||
return myData[index];
|
||||
}
|
||||
|
||||
public void setSegmentData(int index, int data) {
|
||||
if(index < 0 || index >= mySegmentCount) throw new IndexOutOfBoundsException("Wrong index: " + index);
|
||||
if (data < 0 && data > Short.MAX_VALUE) throw new IndexOutOfBoundsException("data out of short range" + data);
|
||||
myData[index] = (short)data;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private static short[] reallocateArray(@NotNull short[] array, int index) {
|
||||
if (index < array.length) return array;
|
||||
|
||||
short[] newArray = new short[calcCapacity(array.length, index)];
|
||||
System.arraycopy(array, 0, newArray, 0, array.length);
|
||||
return newArray;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,74 +1,74 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<application>
|
||||
<component name="FeatureUsageStatistics" first-run="1317813552917" have-been-shown="false" show-in-other="true" show-in-compilation="true">
|
||||
<feature id="navigation.goto.inspection" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="refactoring.move.moveInner" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.popup.camelprefix" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.variable.name" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.goto.implementation" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="diagram.show.popup" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.quickdefinition.lookup" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="ui.horizontal.scrolling" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="diagram.show.diff" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.quickjavadoc.ctrln" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.javadoc.external" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="tag.name.completion" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="ui.recentchanges" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="diagram.show" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="refactoring.introduceVariable" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="ui.tree.speedsearch" count="5" last-shown="0" last-used="1317813527648" average-frequency="2666" shown-count="0" />
|
||||
<feature id="navigation.popup.class" count="21" last-shown="0" last-used="1317817356090" average-frequency="174691" shown-count="0" />
|
||||
<feature id="navigation.popup.wildcards" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.smarttype.casting" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.goto.declaration" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.basic" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.second.smarttype.array.member" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.second.smarttype.aslist" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="find.recent.search" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="dir.diff" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.second.smarttype.chain" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.popup.file.structure" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.highlight.throws" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.finishBySmartEnter" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.surroundwith.expression" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="refactoring.rename" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.finishByExclamation" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="ant.quickfix.CreateProperty" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.smarttype.afternew" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.global.member.name" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.finishByDotEtc" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.complete.statement" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="db.diff" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.surroundwith.statement" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.finishByControlEnter" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.second.basic" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.quickjavadoc.lookup" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.comment.line" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.popup.file" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="refactoring.copyClass" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="switcher" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.goto.usages" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.second.smarttype.toar" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.popup.symbol" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.popup.action" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="refactoring.introduceVariable.incompleteStatement" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="find.completion" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.replace" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.select.word" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.comment.block" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.cancelByControlArrows" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.highlight.implements" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.quickdefinition" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="ui.scheme.quickswitch" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="jar.diff" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.recent.files" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.highlight.return" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.smarttype.general" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.camelHumps" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.overrideimplement" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="ant.quickfix.CreateTarget" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.quickjavadoc" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.select.in" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
</component>
|
||||
</application>
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<application>
|
||||
<component name="FeatureUsageStatistics" first-run="1317813552917" have-been-shown="false" show-in-other="true" show-in-compilation="true">
|
||||
<feature id="navigation.goto.inspection" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="refactoring.move.moveInner" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.popup.camelprefix" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.variable.name" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.goto.implementation" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="diagram.show.popup" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.quickdefinition.lookup" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="ui.horizontal.scrolling" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="diagram.show.diff" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.quickjavadoc.ctrln" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.javadoc.external" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="tag.name.completion" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="ui.recentchanges" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="diagram.show" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="refactoring.introduceVariable" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="ui.tree.speedsearch" count="5" last-shown="0" last-used="1317813527648" average-frequency="2666" shown-count="0" />
|
||||
<feature id="navigation.popup.class" count="21" last-shown="0" last-used="1317817356090" average-frequency="174691" shown-count="0" />
|
||||
<feature id="navigation.popup.wildcards" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.smarttype.casting" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.goto.declaration" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.basic" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.second.smarttype.array.member" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.second.smarttype.aslist" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="find.recent.search" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="dir.diff" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.second.smarttype.chain" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.popup.file.structure" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.highlight.throws" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.finishBySmartEnter" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.surroundwith.expression" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="refactoring.rename" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.finishByExclamation" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="ant.quickfix.CreateProperty" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.smarttype.afternew" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.global.member.name" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.finishByDotEtc" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.complete.statement" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="db.diff" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.surroundwith.statement" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.finishByControlEnter" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.second.basic" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.quickjavadoc.lookup" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.comment.line" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.popup.file" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="refactoring.copyClass" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="switcher" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.goto.usages" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.second.smarttype.toar" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.popup.symbol" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.popup.action" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="refactoring.introduceVariable.incompleteStatement" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="find.completion" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.replace" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.select.word" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.comment.block" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.cancelByControlArrows" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.highlight.implements" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.quickdefinition" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="ui.scheme.quickswitch" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="jar.diff" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.recent.files" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.highlight.return" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.smarttype.general" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="editing.completion.camelHumps" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.overrideimplement" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="ant.quickfix.CreateTarget" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="codeassists.quickjavadoc" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
<feature id="navigation.select.in" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
|
||||
</component>
|
||||
</application>
|
||||
|
||||
|
||||
+109
-109
@@ -1,109 +1,109 @@
|
||||
/*
|
||||
* Copyright 2000-2009 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.completion;
|
||||
|
||||
import com.intellij.codeInsight.lookup.Lookup;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import com.intellij.psi.PsiElement;
|
||||
import com.intellij.psi.PsiFile;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public final class CompletionParameters {
|
||||
private final PsiElement myPosition;
|
||||
private final PsiFile myOriginalFile;
|
||||
private final CompletionType myCompletionType;
|
||||
private final Lookup myLookup;
|
||||
private final int myOffset;
|
||||
private final int myInvocationCount;
|
||||
|
||||
CompletionParameters(@NotNull final PsiElement position, @NotNull final PsiFile originalFile,
|
||||
final CompletionType completionType, int offset, final int invocationCount, Lookup lookup) {
|
||||
assert offset >= position.getTextRange().getStartOffset();
|
||||
myPosition = position;
|
||||
assert position.isValid();
|
||||
myOriginalFile = originalFile;
|
||||
myCompletionType = completionType;
|
||||
myOffset = offset;
|
||||
myInvocationCount = invocationCount;
|
||||
myLookup = lookup;
|
||||
}
|
||||
|
||||
public CompletionParameters delegateToClassName() {
|
||||
return withType(CompletionType.CLASS_NAME).withInvocationCount(myInvocationCount - 1);
|
||||
}
|
||||
|
||||
public CompletionParameters withType(CompletionType type) {
|
||||
return new CompletionParameters(myPosition, myOriginalFile, type, myOffset, myInvocationCount, myLookup);
|
||||
}
|
||||
|
||||
public CompletionParameters withInvocationCount(int newCount) {
|
||||
return new CompletionParameters(myPosition, myOriginalFile, myCompletionType, myOffset, newCount, myLookup);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public PsiElement getPosition() {
|
||||
return myPosition;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Lookup getLookup() {
|
||||
return myLookup;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public PsiElement getOriginalPosition() {
|
||||
return myOriginalFile.findElementAt(myPosition.getTextRange().getStartOffset());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public PsiFile getOriginalFile() {
|
||||
return myOriginalFile;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public CompletionType getCompletionType() {
|
||||
return myCompletionType;
|
||||
}
|
||||
|
||||
public int getOffset() {
|
||||
return myOffset;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return
|
||||
* 0 for autopopup
|
||||
* 1 for explicitly invoked completion
|
||||
* >1 for next completion invocations when one lookup is already active
|
||||
*/
|
||||
public int getInvocationCount() {
|
||||
return myInvocationCount;
|
||||
}
|
||||
|
||||
public boolean isAutoPopup() {
|
||||
return myInvocationCount == 0;
|
||||
}
|
||||
|
||||
public CompletionParameters withPosition(PsiElement element, int offset) {
|
||||
return new CompletionParameters(element, myOriginalFile, myCompletionType, offset, myInvocationCount, myLookup);
|
||||
}
|
||||
|
||||
public boolean isExtendedCompletion() {
|
||||
return myCompletionType == CompletionType.BASIC && myInvocationCount >= 2;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 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.completion;
|
||||
|
||||
import com.intellij.codeInsight.lookup.Lookup;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import com.intellij.psi.PsiElement;
|
||||
import com.intellij.psi.PsiFile;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public final class CompletionParameters {
|
||||
private final PsiElement myPosition;
|
||||
private final PsiFile myOriginalFile;
|
||||
private final CompletionType myCompletionType;
|
||||
private final Lookup myLookup;
|
||||
private final int myOffset;
|
||||
private final int myInvocationCount;
|
||||
|
||||
CompletionParameters(@NotNull final PsiElement position, @NotNull final PsiFile originalFile,
|
||||
final CompletionType completionType, int offset, final int invocationCount, Lookup lookup) {
|
||||
assert offset >= position.getTextRange().getStartOffset();
|
||||
myPosition = position;
|
||||
assert position.isValid();
|
||||
myOriginalFile = originalFile;
|
||||
myCompletionType = completionType;
|
||||
myOffset = offset;
|
||||
myInvocationCount = invocationCount;
|
||||
myLookup = lookup;
|
||||
}
|
||||
|
||||
public CompletionParameters delegateToClassName() {
|
||||
return withType(CompletionType.CLASS_NAME).withInvocationCount(myInvocationCount - 1);
|
||||
}
|
||||
|
||||
public CompletionParameters withType(CompletionType type) {
|
||||
return new CompletionParameters(myPosition, myOriginalFile, type, myOffset, myInvocationCount, myLookup);
|
||||
}
|
||||
|
||||
public CompletionParameters withInvocationCount(int newCount) {
|
||||
return new CompletionParameters(myPosition, myOriginalFile, myCompletionType, myOffset, newCount, myLookup);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public PsiElement getPosition() {
|
||||
return myPosition;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Lookup getLookup() {
|
||||
return myLookup;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public PsiElement getOriginalPosition() {
|
||||
return myOriginalFile.findElementAt(myPosition.getTextRange().getStartOffset());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public PsiFile getOriginalFile() {
|
||||
return myOriginalFile;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public CompletionType getCompletionType() {
|
||||
return myCompletionType;
|
||||
}
|
||||
|
||||
public int getOffset() {
|
||||
return myOffset;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return
|
||||
* 0 for autopopup
|
||||
* 1 for explicitly invoked completion
|
||||
* >1 for next completion invocations when one lookup is already active
|
||||
*/
|
||||
public int getInvocationCount() {
|
||||
return myInvocationCount;
|
||||
}
|
||||
|
||||
public boolean isAutoPopup() {
|
||||
return myInvocationCount == 0;
|
||||
}
|
||||
|
||||
public CompletionParameters withPosition(PsiElement element, int offset) {
|
||||
return new CompletionParameters(element, myOriginalFile, myCompletionType, offset, myInvocationCount, myLookup);
|
||||
}
|
||||
|
||||
public boolean isExtendedCompletion() {
|
||||
return myCompletionType == CompletionType.BASIC && myInvocationCount >= 2;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public enum CompletionType {
|
||||
BASIC,
|
||||
SMART,
|
||||
|
||||
/**
|
||||
* Only to be passed to {@link CompletionService#getVariantsFromContributors(CompletionParameters, CompletionContributor, com.intellij.util.Consumer)}
|
||||
* to invoke special class-name providers for various file types where those class names are applicable (e.g. xml, txt, properties, custom)
|
||||
*/
|
||||
CLASS_NAME
|
||||
}
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public enum CompletionType {
|
||||
BASIC,
|
||||
SMART,
|
||||
|
||||
/**
|
||||
* Only to be passed to {@link CompletionService#getVariantsFromContributors(CompletionParameters, CompletionContributor, com.intellij.util.Consumer)}
|
||||
* to invoke special class-name providers for various file types where those class names are applicable (e.g. xml, txt, properties, custom)
|
||||
*/
|
||||
CLASS_NAME
|
||||
}
|
||||
|
||||
+66
-66
@@ -1,66 +1,66 @@
|
||||
/*
|
||||
* Copyright 2000-2011 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.lang.LanguageParserDefinitions;
|
||||
import com.intellij.lang.ParserDefinition;
|
||||
import com.intellij.patterns.PlatformPatterns;
|
||||
import com.intellij.psi.PsiElement;
|
||||
import com.intellij.psi.PsiErrorElement;
|
||||
import com.intellij.psi.PsiFile;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.psi.util.PsiUtilBase;
|
||||
import com.intellij.util.ThreeState;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public class SkipAutopopupInStrings extends CompletionConfidence {
|
||||
@NotNull
|
||||
@Override
|
||||
public ThreeState shouldFocusLookup(@NotNull CompletionParameters parameters) {
|
||||
return ThreeState.UNSURE;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public ThreeState shouldSkipAutopopup(@NotNull PsiElement contextElement, @NotNull PsiFile psiFile, int offset) {
|
||||
if (isInStringLiteral(contextElement)) {
|
||||
return ThreeState.YES;
|
||||
}
|
||||
|
||||
return ThreeState.UNSURE;
|
||||
}
|
||||
|
||||
public static boolean isInStringLiteral(PsiElement element) {
|
||||
ParserDefinition definition = LanguageParserDefinitions.INSTANCE.forLanguage(PsiUtilBase.findLanguageFromElement(element));
|
||||
if (definition == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return isStringLiteral(element, definition) || isStringLiteral(element.getParent(), definition) ||
|
||||
isStringLiteralWithError(element, definition) || isStringLiteralWithError(element.getParent(), definition);
|
||||
}
|
||||
|
||||
private static boolean isStringLiteral(PsiElement element, ParserDefinition definition) {
|
||||
return PlatformPatterns.psiElement().withElementType(definition.getStringLiteralElements()).accepts(element);
|
||||
}
|
||||
|
||||
private static boolean isStringLiteralWithError(PsiElement element, ParserDefinition definition) {
|
||||
return isStringLiteral(element, definition) && PsiTreeUtil.nextLeaf(element) instanceof PsiErrorElement;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2011 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.completion;
|
||||
|
||||
import com.intellij.lang.LanguageParserDefinitions;
|
||||
import com.intellij.lang.ParserDefinition;
|
||||
import com.intellij.patterns.PlatformPatterns;
|
||||
import com.intellij.psi.PsiElement;
|
||||
import com.intellij.psi.PsiErrorElement;
|
||||
import com.intellij.psi.PsiFile;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.psi.util.PsiUtilBase;
|
||||
import com.intellij.util.ThreeState;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public class SkipAutopopupInStrings extends CompletionConfidence {
|
||||
@NotNull
|
||||
@Override
|
||||
public ThreeState shouldFocusLookup(@NotNull CompletionParameters parameters) {
|
||||
return ThreeState.UNSURE;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public ThreeState shouldSkipAutopopup(@NotNull PsiElement contextElement, @NotNull PsiFile psiFile, int offset) {
|
||||
if (isInStringLiteral(contextElement)) {
|
||||
return ThreeState.YES;
|
||||
}
|
||||
|
||||
return ThreeState.UNSURE;
|
||||
}
|
||||
|
||||
public static boolean isInStringLiteral(PsiElement element) {
|
||||
ParserDefinition definition = LanguageParserDefinitions.INSTANCE.forLanguage(PsiUtilBase.findLanguageFromElement(element));
|
||||
if (definition == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return isStringLiteral(element, definition) || isStringLiteral(element.getParent(), definition) ||
|
||||
isStringLiteralWithError(element, definition) || isStringLiteralWithError(element.getParent(), definition);
|
||||
}
|
||||
|
||||
private static boolean isStringLiteral(PsiElement element, ParserDefinition definition) {
|
||||
return PlatformPatterns.psiElement().withElementType(definition.getStringLiteralElements()).accepts(element);
|
||||
}
|
||||
|
||||
private static boolean isStringLiteralWithError(PsiElement element, ParserDefinition definition) {
|
||||
return isStringLiteral(element, definition) && PsiTreeUtil.nextLeaf(element) instanceof PsiErrorElement;
|
||||
}
|
||||
}
|
||||
|
||||
+96
-96
@@ -1,96 +1,96 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.intention.impl;
|
||||
|
||||
import com.intellij.codeInsight.intention.HighPriorityAction;
|
||||
import com.intellij.codeInsight.intention.IntentionAction;
|
||||
import com.intellij.codeInsight.intention.LowPriorityAction;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.psi.PsiFile;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* @author Danila Ponomarenko
|
||||
*/
|
||||
public abstract class PriorityIntentionActionWrapper implements IntentionAction {
|
||||
private IntentionAction action;
|
||||
|
||||
private PriorityIntentionActionWrapper(@NotNull IntentionAction action) {
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getText() {
|
||||
return action.getText();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getFamilyName() {
|
||||
return action.getFamilyName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
|
||||
return action.isAvailable(project, editor, file);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
|
||||
action.invoke(project, editor, file);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean startInWriteAction() {
|
||||
return action.startInWriteAction();
|
||||
}
|
||||
|
||||
private static class HighPriorityIntentionActionWrapper extends PriorityIntentionActionWrapper implements HighPriorityAction {
|
||||
protected HighPriorityIntentionActionWrapper(@NotNull IntentionAction action) {
|
||||
super(action);
|
||||
}
|
||||
}
|
||||
|
||||
private static class NormalPriorityIntentionActionWrapper extends PriorityIntentionActionWrapper {
|
||||
protected NormalPriorityIntentionActionWrapper(@NotNull IntentionAction action) {
|
||||
super(action);
|
||||
}
|
||||
}
|
||||
|
||||
private static class LowPriorityIntentionActionWrapper extends PriorityIntentionActionWrapper implements LowPriorityAction {
|
||||
protected LowPriorityIntentionActionWrapper(@NotNull IntentionAction action) {
|
||||
super(action);
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static IntentionAction highPriority(@NotNull IntentionAction action) {
|
||||
return new HighPriorityIntentionActionWrapper(action);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static IntentionAction normalPriority(@NotNull IntentionAction action) {
|
||||
return new NormalPriorityIntentionActionWrapper(action);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static IntentionAction lowPriority(@NotNull IntentionAction action) {
|
||||
return new LowPriorityIntentionActionWrapper(action);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.intention.impl;
|
||||
|
||||
import com.intellij.codeInsight.intention.HighPriorityAction;
|
||||
import com.intellij.codeInsight.intention.IntentionAction;
|
||||
import com.intellij.codeInsight.intention.LowPriorityAction;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.psi.PsiFile;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* @author Danila Ponomarenko
|
||||
*/
|
||||
public abstract class PriorityIntentionActionWrapper implements IntentionAction {
|
||||
private IntentionAction action;
|
||||
|
||||
private PriorityIntentionActionWrapper(@NotNull IntentionAction action) {
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getText() {
|
||||
return action.getText();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getFamilyName() {
|
||||
return action.getFamilyName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
|
||||
return action.isAvailable(project, editor, file);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
|
||||
action.invoke(project, editor, file);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean startInWriteAction() {
|
||||
return action.startInWriteAction();
|
||||
}
|
||||
|
||||
private static class HighPriorityIntentionActionWrapper extends PriorityIntentionActionWrapper implements HighPriorityAction {
|
||||
protected HighPriorityIntentionActionWrapper(@NotNull IntentionAction action) {
|
||||
super(action);
|
||||
}
|
||||
}
|
||||
|
||||
private static class NormalPriorityIntentionActionWrapper extends PriorityIntentionActionWrapper {
|
||||
protected NormalPriorityIntentionActionWrapper(@NotNull IntentionAction action) {
|
||||
super(action);
|
||||
}
|
||||
}
|
||||
|
||||
private static class LowPriorityIntentionActionWrapper extends PriorityIntentionActionWrapper implements LowPriorityAction {
|
||||
protected LowPriorityIntentionActionWrapper(@NotNull IntentionAction action) {
|
||||
super(action);
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static IntentionAction highPriority(@NotNull IntentionAction action) {
|
||||
return new HighPriorityIntentionActionWrapper(action);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static IntentionAction normalPriority(@NotNull IntentionAction action) {
|
||||
return new NormalPriorityIntentionActionWrapper(action);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static IntentionAction lowPriority(@NotNull IntentionAction action) {
|
||||
return new LowPriorityIntentionActionWrapper(action);
|
||||
}
|
||||
}
|
||||
|
||||
+85
-85
@@ -1,85 +1,85 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.intention.impl;
|
||||
|
||||
import com.intellij.codeInsight.intention.HighPriorityAction;
|
||||
import com.intellij.codeInsight.intention.LowPriorityAction;
|
||||
import com.intellij.codeInspection.LocalQuickFix;
|
||||
import com.intellij.codeInspection.ProblemDescriptor;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* @author Danila Ponomarenko
|
||||
*/
|
||||
public abstract class PriorityLocalQuickFixWrapper implements LocalQuickFix {
|
||||
private final LocalQuickFix fix;
|
||||
|
||||
private PriorityLocalQuickFixWrapper(@NotNull LocalQuickFix fix) {
|
||||
this.fix = fix;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getName() {
|
||||
return fix.getName();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getFamilyName() {
|
||||
return fix.getFamilyName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
|
||||
fix.applyFix(project, descriptor);
|
||||
}
|
||||
|
||||
private static class HighPriorityLocalQuickFixWrapper extends PriorityLocalQuickFixWrapper implements HighPriorityAction {
|
||||
protected HighPriorityLocalQuickFixWrapper(@NotNull LocalQuickFix fix) {
|
||||
super(fix);
|
||||
}
|
||||
}
|
||||
|
||||
private static class NormalPriorityLocalQuickFixWrapper extends PriorityLocalQuickFixWrapper {
|
||||
protected NormalPriorityLocalQuickFixWrapper(@NotNull LocalQuickFix fix) {
|
||||
super(fix);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class LowPriorityLocalQuickFixWrapper extends PriorityLocalQuickFixWrapper implements LowPriorityAction {
|
||||
protected LowPriorityLocalQuickFixWrapper(@NotNull LocalQuickFix fix) {
|
||||
super(fix);
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static LocalQuickFix highPriority(@NotNull LocalQuickFix fix) {
|
||||
return new HighPriorityLocalQuickFixWrapper(fix);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static LocalQuickFix normalPriority(@NotNull LocalQuickFix fix) {
|
||||
return new NormalPriorityLocalQuickFixWrapper(fix);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static LocalQuickFix lowPriority(@NotNull LocalQuickFix fix) {
|
||||
return new LowPriorityLocalQuickFixWrapper(fix);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInsight.intention.impl;
|
||||
|
||||
import com.intellij.codeInsight.intention.HighPriorityAction;
|
||||
import com.intellij.codeInsight.intention.LowPriorityAction;
|
||||
import com.intellij.codeInspection.LocalQuickFix;
|
||||
import com.intellij.codeInspection.ProblemDescriptor;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* @author Danila Ponomarenko
|
||||
*/
|
||||
public abstract class PriorityLocalQuickFixWrapper implements LocalQuickFix {
|
||||
private final LocalQuickFix fix;
|
||||
|
||||
private PriorityLocalQuickFixWrapper(@NotNull LocalQuickFix fix) {
|
||||
this.fix = fix;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getName() {
|
||||
return fix.getName();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getFamilyName() {
|
||||
return fix.getFamilyName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
|
||||
fix.applyFix(project, descriptor);
|
||||
}
|
||||
|
||||
private static class HighPriorityLocalQuickFixWrapper extends PriorityLocalQuickFixWrapper implements HighPriorityAction {
|
||||
protected HighPriorityLocalQuickFixWrapper(@NotNull LocalQuickFix fix) {
|
||||
super(fix);
|
||||
}
|
||||
}
|
||||
|
||||
private static class NormalPriorityLocalQuickFixWrapper extends PriorityLocalQuickFixWrapper {
|
||||
protected NormalPriorityLocalQuickFixWrapper(@NotNull LocalQuickFix fix) {
|
||||
super(fix);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class LowPriorityLocalQuickFixWrapper extends PriorityLocalQuickFixWrapper implements LowPriorityAction {
|
||||
protected LowPriorityLocalQuickFixWrapper(@NotNull LocalQuickFix fix) {
|
||||
super(fix);
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static LocalQuickFix highPriority(@NotNull LocalQuickFix fix) {
|
||||
return new HighPriorityLocalQuickFixWrapper(fix);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static LocalQuickFix normalPriority(@NotNull LocalQuickFix fix) {
|
||||
return new NormalPriorityLocalQuickFixWrapper(fix);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static LocalQuickFix lowPriority(@NotNull LocalQuickFix fix) {
|
||||
return new LowPriorityLocalQuickFixWrapper(fix);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,52 +1,52 @@
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInspection;
|
||||
|
||||
import com.intellij.openapi.project.Project;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* Common base interface for quick fixes provided by local and global inspections.
|
||||
*
|
||||
* @author anna
|
||||
* @since 6.0
|
||||
* @see CommonProblemDescriptor#getFixes()
|
||||
*/
|
||||
public interface QuickFix<D extends CommonProblemDescriptor> {
|
||||
QuickFix[] EMPTY_ARRAY = new QuickFix[0];
|
||||
/**
|
||||
* Returns the name of the quick fix.
|
||||
*
|
||||
* @return the name of the quick fix.
|
||||
*/
|
||||
@NotNull
|
||||
String getName();
|
||||
|
||||
/**
|
||||
* @return text to appear in "Apply Fix" popup when multiple Quick Fixes exist (in the results of batch code inspection). For example,
|
||||
* if the name of the quickfix is "Create template <filename>", the return value of getFamilyName() should be "Create template".
|
||||
* If the name of the quickfix does not depend on a specific element, simply return getName().
|
||||
*/
|
||||
@NotNull String getFamilyName();
|
||||
|
||||
/**
|
||||
* Called to apply the fix.
|
||||
*
|
||||
* @param project {@link com.intellij.openapi.project.Project}
|
||||
* @param descriptor problem reported by the tool which provided this quick fix action
|
||||
*/
|
||||
void applyFix(@NotNull Project project, @NotNull D descriptor);
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.codeInspection;
|
||||
|
||||
import com.intellij.openapi.project.Project;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* Common base interface for quick fixes provided by local and global inspections.
|
||||
*
|
||||
* @author anna
|
||||
* @since 6.0
|
||||
* @see CommonProblemDescriptor#getFixes()
|
||||
*/
|
||||
public interface QuickFix<D extends CommonProblemDescriptor> {
|
||||
QuickFix[] EMPTY_ARRAY = new QuickFix[0];
|
||||
/**
|
||||
* Returns the name of the quick fix.
|
||||
*
|
||||
* @return the name of the quick fix.
|
||||
*/
|
||||
@NotNull
|
||||
String getName();
|
||||
|
||||
/**
|
||||
* @return text to appear in "Apply Fix" popup when multiple Quick Fixes exist (in the results of batch code inspection). For example,
|
||||
* if the name of the quickfix is "Create template <filename>", the return value of getFamilyName() should be "Create template".
|
||||
* If the name of the quickfix does not depend on a specific element, simply return getName().
|
||||
*/
|
||||
@NotNull String getFamilyName();
|
||||
|
||||
/**
|
||||
* Called to apply the fix.
|
||||
*
|
||||
* @param project {@link com.intellij.openapi.project.Project}
|
||||
* @param descriptor problem reported by the tool which provided this quick fix action
|
||||
*/
|
||||
void applyFix(@NotNull Project project, @NotNull D descriptor);
|
||||
}
|
||||
|
||||
@@ -1,92 +1,92 @@
|
||||
/*
|
||||
* Copyright 2000-2009 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Created by IntelliJ IDEA.
|
||||
* User: Vladislav.Kaznacheev
|
||||
* Date: Jul 4, 2007
|
||||
* Time: 12:33:18 AM
|
||||
*/
|
||||
package com.intellij.execution;
|
||||
|
||||
import com.intellij.execution.configurations.RunConfiguration;
|
||||
import com.intellij.execution.runners.ExecutionEnvironment;
|
||||
import com.intellij.openapi.actionSystem.DataContext;
|
||||
import com.intellij.openapi.extensions.ExtensionPointName;
|
||||
import com.intellij.openapi.extensions.Extensions;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.util.Key;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
public abstract class BeforeRunTaskProvider<T extends BeforeRunTask> {
|
||||
public static final ExtensionPointName<BeforeRunTaskProvider<BeforeRunTask>> EXTENSION_POINT_NAME = new ExtensionPointName<BeforeRunTaskProvider<BeforeRunTask>>("com.intellij.stepsBeforeRunProvider");
|
||||
|
||||
public static final String RUNNER_ID = "RunnerId";
|
||||
|
||||
public abstract Key<T> getId();
|
||||
|
||||
public abstract String getName();
|
||||
|
||||
@Nullable
|
||||
public Icon getIcon() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public abstract String getDescription(T task);
|
||||
|
||||
|
||||
@Nullable
|
||||
public Icon getTaskIcon(T task) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public abstract boolean isConfigurable();
|
||||
|
||||
/**
|
||||
* @return 'before run' task for the configuration or null, if the task from this provider is not applicable to the specified configuration
|
||||
*/
|
||||
@Nullable
|
||||
public abstract T createTask(final RunConfiguration runConfiguration);
|
||||
|
||||
/**
|
||||
* @return <code>true</code> if task configuration is changed
|
||||
*/
|
||||
public abstract boolean configureTask(final RunConfiguration runConfiguration, T task);
|
||||
|
||||
public abstract boolean canExecuteTask(RunConfiguration configuration, T task);
|
||||
|
||||
public abstract boolean executeTask(DataContext context, RunConfiguration configuration, ExecutionEnvironment env, T task);
|
||||
|
||||
/**
|
||||
*
|
||||
* @return <code>true</code> if at most one task may be configured
|
||||
*/
|
||||
public boolean isSingleton() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static <T extends BeforeRunTask> BeforeRunTaskProvider<T> getProvider(Project project, Key<T> key) {
|
||||
BeforeRunTaskProvider<BeforeRunTask>[] providers = Extensions.getExtensions(BeforeRunTaskProvider.EXTENSION_POINT_NAME, project);
|
||||
for (BeforeRunTaskProvider<BeforeRunTask> provider : providers) {
|
||||
if (provider.getId() == key)
|
||||
return (BeforeRunTaskProvider<T>)provider;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Created by IntelliJ IDEA.
|
||||
* User: Vladislav.Kaznacheev
|
||||
* Date: Jul 4, 2007
|
||||
* Time: 12:33:18 AM
|
||||
*/
|
||||
package com.intellij.execution;
|
||||
|
||||
import com.intellij.execution.configurations.RunConfiguration;
|
||||
import com.intellij.execution.runners.ExecutionEnvironment;
|
||||
import com.intellij.openapi.actionSystem.DataContext;
|
||||
import com.intellij.openapi.extensions.ExtensionPointName;
|
||||
import com.intellij.openapi.extensions.Extensions;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.util.Key;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
public abstract class BeforeRunTaskProvider<T extends BeforeRunTask> {
|
||||
public static final ExtensionPointName<BeforeRunTaskProvider<BeforeRunTask>> EXTENSION_POINT_NAME = new ExtensionPointName<BeforeRunTaskProvider<BeforeRunTask>>("com.intellij.stepsBeforeRunProvider");
|
||||
|
||||
public static final String RUNNER_ID = "RunnerId";
|
||||
|
||||
public abstract Key<T> getId();
|
||||
|
||||
public abstract String getName();
|
||||
|
||||
@Nullable
|
||||
public Icon getIcon() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public abstract String getDescription(T task);
|
||||
|
||||
|
||||
@Nullable
|
||||
public Icon getTaskIcon(T task) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public abstract boolean isConfigurable();
|
||||
|
||||
/**
|
||||
* @return 'before run' task for the configuration or null, if the task from this provider is not applicable to the specified configuration
|
||||
*/
|
||||
@Nullable
|
||||
public abstract T createTask(final RunConfiguration runConfiguration);
|
||||
|
||||
/**
|
||||
* @return <code>true</code> if task configuration is changed
|
||||
*/
|
||||
public abstract boolean configureTask(final RunConfiguration runConfiguration, T task);
|
||||
|
||||
public abstract boolean canExecuteTask(RunConfiguration configuration, T task);
|
||||
|
||||
public abstract boolean executeTask(DataContext context, RunConfiguration configuration, ExecutionEnvironment env, T task);
|
||||
|
||||
/**
|
||||
*
|
||||
* @return <code>true</code> if at most one task may be configured
|
||||
*/
|
||||
public boolean isSingleton() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static <T extends BeforeRunTask> BeforeRunTaskProvider<T> getProvider(Project project, Key<T> key) {
|
||||
BeforeRunTaskProvider<BeforeRunTask>[] providers = Extensions.getExtensions(BeforeRunTaskProvider.EXTENSION_POINT_NAME, project);
|
||||
for (BeforeRunTaskProvider<BeforeRunTask> provider : providers) {
|
||||
if (provider.getId() == key)
|
||||
return (BeforeRunTaskProvider<T>)provider;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,48 +1,48 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.execution;
|
||||
|
||||
import com.intellij.ide.IdeBundle;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
public class DefaultExecutionTarget extends ExecutionTarget {
|
||||
public static final ExecutionTarget INSTANCE = new DefaultExecutionTarget();
|
||||
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getId() {
|
||||
return "default_target";
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getDisplayName() {
|
||||
return IdeBundle.message("node.default");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Icon getIcon() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canRun(@NotNull RunnerAndConfigurationSettings configuration) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.execution;
|
||||
|
||||
import com.intellij.ide.IdeBundle;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
public class DefaultExecutionTarget extends ExecutionTarget {
|
||||
public static final ExecutionTarget INSTANCE = new DefaultExecutionTarget();
|
||||
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getId() {
|
||||
return "default_target";
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getDisplayName() {
|
||||
return IdeBundle.message("node.default");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Icon getIcon() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canRun(@NotNull RunnerAndConfigurationSettings configuration) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,50 +1,50 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.intellij.execution;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
public abstract class ExecutionTarget {
|
||||
@NotNull
|
||||
public abstract String getId();
|
||||
|
||||
@NotNull
|
||||
public abstract String getDisplayName();
|
||||
|
||||
@Nullable
|
||||
public abstract Icon getIcon();
|
||||
|
||||
public abstract boolean canRun(@NotNull RunnerAndConfigurationSettings configuration);
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return obj == this || (getClass().isInstance(obj) && getId().equals(((ExecutionTarget)obj).getId()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return getId().hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getId();
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.intellij.execution;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
public abstract class ExecutionTarget {
|
||||
@NotNull
|
||||
public abstract String getId();
|
||||
|
||||
@NotNull
|
||||
public abstract String getDisplayName();
|
||||
|
||||
@Nullable
|
||||
public abstract Icon getIcon();
|
||||
|
||||
public abstract boolean canRun(@NotNull RunnerAndConfigurationSettings configuration);
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return obj == this || (getClass().isInstance(obj) && getId().equals(((ExecutionTarget)obj).getId()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return getId().hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getId();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.execution;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public interface ExecutionTargetListener {
|
||||
void activeTargetChanged(@NotNull ExecutionTarget newTarget);
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.execution;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public interface ExecutionTargetListener {
|
||||
void activeTargetChanged(@NotNull ExecutionTarget newTarget);
|
||||
}
|
||||
|
||||
@@ -1,73 +1,73 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.execution;
|
||||
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.util.messages.Topic;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public abstract class ExecutionTargetManager {
|
||||
public static final Topic<ExecutionTargetListener> TOPIC = Topic.create("ExecutionTarget topic", ExecutionTargetListener.class);
|
||||
|
||||
|
||||
@NotNull
|
||||
public static ExecutionTargetManager getInstance(@NotNull Project project) {
|
||||
return project.getComponent(ExecutionTargetManager.class);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ExecutionTarget getActiveTarget(@NotNull Project project) {
|
||||
return getInstance(project).getActiveTarget();
|
||||
}
|
||||
|
||||
public static void setActiveTarget(@NotNull Project project, @NotNull ExecutionTarget target) {
|
||||
getInstance(project).setActiveTarget(target);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static List<ExecutionTarget> getTargetsFor(@NotNull Project project, @Nullable RunnerAndConfigurationSettings settings) {
|
||||
return getInstance(project).getTargetsFor(settings);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static List<ExecutionTarget> getTargetsToChooseFor(@NotNull Project project, @Nullable RunnerAndConfigurationSettings settings) {
|
||||
List<ExecutionTarget> result = getInstance(project).getTargetsFor(settings);
|
||||
if (result.size() == 1 && DefaultExecutionTarget.INSTANCE.equals(result.get(0))) return Collections.emptyList();
|
||||
return result;
|
||||
}
|
||||
|
||||
public static boolean canRun(@Nullable RunnerAndConfigurationSettings settings, @Nullable ExecutionTarget target) {
|
||||
return settings != null && target != null && settings.canRunOn(target) && target.canRun(settings);
|
||||
}
|
||||
|
||||
public static void update(@NotNull Project project) {
|
||||
getInstance(project).update();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public abstract ExecutionTarget getActiveTarget();
|
||||
|
||||
public abstract void setActiveTarget(@NotNull ExecutionTarget target);
|
||||
|
||||
@NotNull
|
||||
public abstract List<ExecutionTarget> getTargetsFor(@Nullable RunnerAndConfigurationSettings settings);
|
||||
|
||||
public abstract void update();
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.execution;
|
||||
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.util.messages.Topic;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public abstract class ExecutionTargetManager {
|
||||
public static final Topic<ExecutionTargetListener> TOPIC = Topic.create("ExecutionTarget topic", ExecutionTargetListener.class);
|
||||
|
||||
|
||||
@NotNull
|
||||
public static ExecutionTargetManager getInstance(@NotNull Project project) {
|
||||
return project.getComponent(ExecutionTargetManager.class);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static ExecutionTarget getActiveTarget(@NotNull Project project) {
|
||||
return getInstance(project).getActiveTarget();
|
||||
}
|
||||
|
||||
public static void setActiveTarget(@NotNull Project project, @NotNull ExecutionTarget target) {
|
||||
getInstance(project).setActiveTarget(target);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static List<ExecutionTarget> getTargetsFor(@NotNull Project project, @Nullable RunnerAndConfigurationSettings settings) {
|
||||
return getInstance(project).getTargetsFor(settings);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static List<ExecutionTarget> getTargetsToChooseFor(@NotNull Project project, @Nullable RunnerAndConfigurationSettings settings) {
|
||||
List<ExecutionTarget> result = getInstance(project).getTargetsFor(settings);
|
||||
if (result.size() == 1 && DefaultExecutionTarget.INSTANCE.equals(result.get(0))) return Collections.emptyList();
|
||||
return result;
|
||||
}
|
||||
|
||||
public static boolean canRun(@Nullable RunnerAndConfigurationSettings settings, @Nullable ExecutionTarget target) {
|
||||
return settings != null && target != null && settings.canRunOn(target) && target.canRun(settings);
|
||||
}
|
||||
|
||||
public static void update(@NotNull Project project) {
|
||||
getInstance(project).update();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public abstract ExecutionTarget getActiveTarget();
|
||||
|
||||
public abstract void setActiveTarget(@NotNull ExecutionTarget target);
|
||||
|
||||
@NotNull
|
||||
public abstract List<ExecutionTarget> getTargetsFor(@Nullable RunnerAndConfigurationSettings settings);
|
||||
|
||||
public abstract void update();
|
||||
}
|
||||
|
||||
@@ -1,31 +1,31 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.intellij.execution;
|
||||
|
||||
import com.intellij.openapi.extensions.ExtensionPointName;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public abstract class ExecutionTargetProvider {
|
||||
public static final ExtensionPointName<ExecutionTargetProvider> EXTENSION_NAME =
|
||||
ExtensionPointName.create("com.intellij.executionTargetProvider");
|
||||
|
||||
@NotNull
|
||||
public abstract List<ExecutionTarget> getTargets(@NotNull Project project, @NotNull RunnerAndConfigurationSettings configuration);
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.intellij.execution;
|
||||
|
||||
import com.intellij.openapi.extensions.ExtensionPointName;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public abstract class ExecutionTargetProvider {
|
||||
public static final ExtensionPointName<ExecutionTargetProvider> EXTENSION_NAME =
|
||||
ExtensionPointName.create("com.intellij.executionTargetProvider");
|
||||
|
||||
@NotNull
|
||||
public abstract List<ExecutionTarget> getTargets(@NotNull Project project, @NotNull RunnerAndConfigurationSettings configuration);
|
||||
}
|
||||
|
||||
@@ -1,72 +1,72 @@
|
||||
/*
|
||||
* Copyright 2000-2009 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.execution;
|
||||
|
||||
import com.intellij.execution.configurations.*;
|
||||
import com.intellij.execution.runners.ProgramRunner;
|
||||
import com.intellij.openapi.util.Factory;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* User: anna
|
||||
* Date: Jan 25, 2005
|
||||
*/
|
||||
public interface RunnerAndConfigurationSettings {
|
||||
@Nullable
|
||||
ConfigurationFactory getFactory();
|
||||
|
||||
boolean isTemplate();
|
||||
|
||||
boolean isTemporary();
|
||||
|
||||
RunConfiguration getConfiguration();
|
||||
|
||||
void setName(String name);
|
||||
|
||||
String getName();
|
||||
|
||||
@NotNull
|
||||
RunnerSettings getRunnerSettings(@NotNull ProgramRunner runner);
|
||||
|
||||
@NotNull
|
||||
ConfigurationPerRunnerSettings getConfigurationSettings(@NotNull ProgramRunner runner);
|
||||
|
||||
@Nullable
|
||||
ConfigurationType getType();
|
||||
|
||||
void checkSettings() throws RuntimeConfigurationException;
|
||||
|
||||
void checkSettings(@Nullable Executor executor) throws RuntimeConfigurationException;
|
||||
|
||||
boolean canRunOn(@NotNull ExecutionTarget target);
|
||||
|
||||
void setTemporary(boolean temporary);
|
||||
|
||||
Factory<RunnerAndConfigurationSettings> createFactory();
|
||||
|
||||
void setEditBeforeRun(boolean b);
|
||||
|
||||
boolean isEditBeforeRun();
|
||||
|
||||
void setSingleton(boolean singleton);
|
||||
|
||||
boolean isSingleton();
|
||||
|
||||
void setFolderName(@Nullable String folderName);
|
||||
|
||||
@Nullable String getFolderName();
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 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.execution;
|
||||
|
||||
import com.intellij.execution.configurations.*;
|
||||
import com.intellij.execution.runners.ProgramRunner;
|
||||
import com.intellij.openapi.util.Factory;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* User: anna
|
||||
* Date: Jan 25, 2005
|
||||
*/
|
||||
public interface RunnerAndConfigurationSettings {
|
||||
@Nullable
|
||||
ConfigurationFactory getFactory();
|
||||
|
||||
boolean isTemplate();
|
||||
|
||||
boolean isTemporary();
|
||||
|
||||
RunConfiguration getConfiguration();
|
||||
|
||||
void setName(String name);
|
||||
|
||||
String getName();
|
||||
|
||||
@NotNull
|
||||
RunnerSettings getRunnerSettings(@NotNull ProgramRunner runner);
|
||||
|
||||
@NotNull
|
||||
ConfigurationPerRunnerSettings getConfigurationSettings(@NotNull ProgramRunner runner);
|
||||
|
||||
@Nullable
|
||||
ConfigurationType getType();
|
||||
|
||||
void checkSettings() throws RuntimeConfigurationException;
|
||||
|
||||
void checkSettings(@Nullable Executor executor) throws RuntimeConfigurationException;
|
||||
|
||||
boolean canRunOn(@NotNull ExecutionTarget target);
|
||||
|
||||
void setTemporary(boolean temporary);
|
||||
|
||||
Factory<RunnerAndConfigurationSettings> createFactory();
|
||||
|
||||
void setEditBeforeRun(boolean b);
|
||||
|
||||
boolean isEditBeforeRun();
|
||||
|
||||
void setSingleton(boolean singleton);
|
||||
|
||||
boolean isSingleton();
|
||||
|
||||
void setFolderName(@Nullable String folderName);
|
||||
|
||||
@Nullable String getFolderName();
|
||||
}
|
||||
|
||||
+152
-152
@@ -1,152 +1,152 @@
|
||||
/*
|
||||
* Copyright 2000-2009 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.execution.configurations;
|
||||
|
||||
import com.intellij.execution.*;
|
||||
import com.intellij.execution.executors.DefaultRunExecutor;
|
||||
import com.intellij.execution.filters.TextConsoleBuilder;
|
||||
import com.intellij.execution.process.ProcessHandler;
|
||||
import com.intellij.execution.runners.ExecutionEnvironment;
|
||||
import com.intellij.execution.runners.ProgramRunner;
|
||||
import com.intellij.execution.ui.ConsoleView;
|
||||
import com.intellij.icons.AllIcons;
|
||||
import com.intellij.openapi.actionSystem.AnAction;
|
||||
import com.intellij.openapi.actionSystem.AnActionEvent;
|
||||
import com.intellij.openapi.actionSystem.Presentation;
|
||||
import com.intellij.openapi.actionSystem.ToggleAction;
|
||||
import com.intellij.openapi.application.ApplicationManager;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.project.DumbAware;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public abstract class CommandLineState implements RunnableState {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.execution.configurations.CommandLineState");
|
||||
private TextConsoleBuilder myConsoleBuilder;
|
||||
|
||||
private final ExecutionEnvironment myEnvironment;
|
||||
|
||||
protected CommandLineState(ExecutionEnvironment environment) {
|
||||
myEnvironment = environment;
|
||||
}
|
||||
|
||||
public ExecutionEnvironment getEnvironment() {
|
||||
return myEnvironment;
|
||||
}
|
||||
|
||||
public RunnerSettings getRunnerSettings() {
|
||||
return myEnvironment.getRunnerSettings();
|
||||
}
|
||||
|
||||
public ConfigurationPerRunnerSettings getConfigurationSettings() {
|
||||
return myEnvironment.getConfigurationSettings();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ExecutionTarget getExecutionTarget() {
|
||||
return myEnvironment.getExecutionTarget();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ExecutionResult execute(@NotNull final Executor executor, @NotNull final ProgramRunner runner) throws ExecutionException {
|
||||
final ProcessHandler processHandler = startProcess();
|
||||
final ConsoleView console = createConsole(executor);
|
||||
if (console != null) {
|
||||
console.attachToProcess(processHandler);
|
||||
}
|
||||
return new DefaultExecutionResult(console, processHandler, createActions(console, processHandler, executor));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
protected ConsoleView createConsole(@NotNull final Executor executor) throws ExecutionException {
|
||||
final TextConsoleBuilder builder = getConsoleBuilder();
|
||||
|
||||
return builder != null ? builder.getConsole()
|
||||
: null;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
protected abstract ProcessHandler startProcess() throws ExecutionException;
|
||||
|
||||
protected AnAction[] createActions(final ConsoleView console, final ProcessHandler processHandler) {
|
||||
return createActions(console, processHandler, null);
|
||||
}
|
||||
|
||||
protected AnAction[] createActions(final ConsoleView console, final ProcessHandler processHandler, Executor executor) {
|
||||
if (console == null || !console.canPause() || (executor != null && !DefaultRunExecutor.EXECUTOR_ID.equals(executor.getId()))) {
|
||||
return new AnAction[0];
|
||||
}
|
||||
return new AnAction[]{new PauseOutputAction(console, processHandler)};
|
||||
}
|
||||
|
||||
public TextConsoleBuilder getConsoleBuilder() {
|
||||
return myConsoleBuilder;
|
||||
}
|
||||
|
||||
public void setConsoleBuilder(final TextConsoleBuilder consoleBuilder) {
|
||||
myConsoleBuilder = consoleBuilder;
|
||||
}
|
||||
|
||||
protected static class PauseOutputAction extends ToggleAction implements DumbAware{
|
||||
private final ConsoleView myConsole;
|
||||
private final ProcessHandler myProcessHandler;
|
||||
|
||||
public PauseOutputAction(final ConsoleView console, final ProcessHandler processHandler) {
|
||||
super(ExecutionBundle.message("run.configuration.pause.output.action.name"), null, AllIcons.Actions.Pause);
|
||||
myConsole = console;
|
||||
myProcessHandler = processHandler;
|
||||
}
|
||||
|
||||
public boolean isSelected(final AnActionEvent event) {
|
||||
return myConsole.isOutputPaused();
|
||||
}
|
||||
|
||||
public void setSelected(final AnActionEvent event, final boolean flag) {
|
||||
myConsole.setOutputPaused(flag);
|
||||
ApplicationManager.getApplication().invokeLater(new Runnable() {
|
||||
public void run() {
|
||||
update(event);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void update(final AnActionEvent event) {
|
||||
super.update(event);
|
||||
final Presentation presentation = event.getPresentation();
|
||||
final boolean isRunning = myProcessHandler != null && !myProcessHandler.isProcessTerminated();
|
||||
if (isRunning) {
|
||||
presentation.setEnabled(true);
|
||||
}
|
||||
else {
|
||||
if (!myConsole.canPause()) {
|
||||
presentation.setEnabled(false);
|
||||
return;
|
||||
}
|
||||
if (!myConsole.hasDeferredOutput()) {
|
||||
presentation.setEnabled(false);
|
||||
}
|
||||
else {
|
||||
presentation.setEnabled(true);
|
||||
myConsole.performWhenNoDeferredOutput(new Runnable() {
|
||||
public void run() {
|
||||
update(event);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 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.execution.configurations;
|
||||
|
||||
import com.intellij.execution.*;
|
||||
import com.intellij.execution.executors.DefaultRunExecutor;
|
||||
import com.intellij.execution.filters.TextConsoleBuilder;
|
||||
import com.intellij.execution.process.ProcessHandler;
|
||||
import com.intellij.execution.runners.ExecutionEnvironment;
|
||||
import com.intellij.execution.runners.ProgramRunner;
|
||||
import com.intellij.execution.ui.ConsoleView;
|
||||
import com.intellij.icons.AllIcons;
|
||||
import com.intellij.openapi.actionSystem.AnAction;
|
||||
import com.intellij.openapi.actionSystem.AnActionEvent;
|
||||
import com.intellij.openapi.actionSystem.Presentation;
|
||||
import com.intellij.openapi.actionSystem.ToggleAction;
|
||||
import com.intellij.openapi.application.ApplicationManager;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.project.DumbAware;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public abstract class CommandLineState implements RunnableState {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.execution.configurations.CommandLineState");
|
||||
private TextConsoleBuilder myConsoleBuilder;
|
||||
|
||||
private final ExecutionEnvironment myEnvironment;
|
||||
|
||||
protected CommandLineState(ExecutionEnvironment environment) {
|
||||
myEnvironment = environment;
|
||||
}
|
||||
|
||||
public ExecutionEnvironment getEnvironment() {
|
||||
return myEnvironment;
|
||||
}
|
||||
|
||||
public RunnerSettings getRunnerSettings() {
|
||||
return myEnvironment.getRunnerSettings();
|
||||
}
|
||||
|
||||
public ConfigurationPerRunnerSettings getConfigurationSettings() {
|
||||
return myEnvironment.getConfigurationSettings();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ExecutionTarget getExecutionTarget() {
|
||||
return myEnvironment.getExecutionTarget();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ExecutionResult execute(@NotNull final Executor executor, @NotNull final ProgramRunner runner) throws ExecutionException {
|
||||
final ProcessHandler processHandler = startProcess();
|
||||
final ConsoleView console = createConsole(executor);
|
||||
if (console != null) {
|
||||
console.attachToProcess(processHandler);
|
||||
}
|
||||
return new DefaultExecutionResult(console, processHandler, createActions(console, processHandler, executor));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
protected ConsoleView createConsole(@NotNull final Executor executor) throws ExecutionException {
|
||||
final TextConsoleBuilder builder = getConsoleBuilder();
|
||||
|
||||
return builder != null ? builder.getConsole()
|
||||
: null;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
protected abstract ProcessHandler startProcess() throws ExecutionException;
|
||||
|
||||
protected AnAction[] createActions(final ConsoleView console, final ProcessHandler processHandler) {
|
||||
return createActions(console, processHandler, null);
|
||||
}
|
||||
|
||||
protected AnAction[] createActions(final ConsoleView console, final ProcessHandler processHandler, Executor executor) {
|
||||
if (console == null || !console.canPause() || (executor != null && !DefaultRunExecutor.EXECUTOR_ID.equals(executor.getId()))) {
|
||||
return new AnAction[0];
|
||||
}
|
||||
return new AnAction[]{new PauseOutputAction(console, processHandler)};
|
||||
}
|
||||
|
||||
public TextConsoleBuilder getConsoleBuilder() {
|
||||
return myConsoleBuilder;
|
||||
}
|
||||
|
||||
public void setConsoleBuilder(final TextConsoleBuilder consoleBuilder) {
|
||||
myConsoleBuilder = consoleBuilder;
|
||||
}
|
||||
|
||||
protected static class PauseOutputAction extends ToggleAction implements DumbAware{
|
||||
private final ConsoleView myConsole;
|
||||
private final ProcessHandler myProcessHandler;
|
||||
|
||||
public PauseOutputAction(final ConsoleView console, final ProcessHandler processHandler) {
|
||||
super(ExecutionBundle.message("run.configuration.pause.output.action.name"), null, AllIcons.Actions.Pause);
|
||||
myConsole = console;
|
||||
myProcessHandler = processHandler;
|
||||
}
|
||||
|
||||
public boolean isSelected(final AnActionEvent event) {
|
||||
return myConsole.isOutputPaused();
|
||||
}
|
||||
|
||||
public void setSelected(final AnActionEvent event, final boolean flag) {
|
||||
myConsole.setOutputPaused(flag);
|
||||
ApplicationManager.getApplication().invokeLater(new Runnable() {
|
||||
public void run() {
|
||||
update(event);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void update(final AnActionEvent event) {
|
||||
super.update(event);
|
||||
final Presentation presentation = event.getPresentation();
|
||||
final boolean isRunning = myProcessHandler != null && !myProcessHandler.isProcessTerminated();
|
||||
if (isRunning) {
|
||||
presentation.setEnabled(true);
|
||||
}
|
||||
else {
|
||||
if (!myConsole.canPause()) {
|
||||
presentation.setEnabled(false);
|
||||
return;
|
||||
}
|
||||
if (!myConsole.hasDeferredOutput()) {
|
||||
presentation.setEnabled(false);
|
||||
}
|
||||
else {
|
||||
presentation.setEnabled(true);
|
||||
myConsole.performWhenNoDeferredOutput(new Runnable() {
|
||||
public void run() {
|
||||
update(event);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+274
-274
@@ -1,274 +1,274 @@
|
||||
/*
|
||||
* Copyright 2000-2009 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.execution.configurations;
|
||||
|
||||
import com.intellij.diagnostic.logging.LogConsole;
|
||||
import com.intellij.execution.ExecutionTarget;
|
||||
import com.intellij.execution.process.ProcessHandler;
|
||||
import com.intellij.execution.runners.ProgramRunner;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.util.InvalidDataException;
|
||||
import com.intellij.openapi.util.UserDataHolderBase;
|
||||
import com.intellij.openapi.util.WriteExternalException;
|
||||
import org.jdom.Element;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author dyoma
|
||||
*/
|
||||
public abstract class RunConfigurationBase extends UserDataHolderBase implements RunConfiguration, TargetAwareRunProfile {
|
||||
private final ConfigurationFactory myFactory;
|
||||
private final Project myProject;
|
||||
private String myName = "";
|
||||
|
||||
private ArrayList<LogFileOptions> myLogFiles = new ArrayList<LogFileOptions>();
|
||||
private ArrayList<PredefinedLogFile> myPredefinedLogFiles = new ArrayList<PredefinedLogFile>();
|
||||
|
||||
@NonNls private static final String LOG_FILE = "log_file";
|
||||
@NonNls private static final String PREDEFINED_LOG_FILE_ELEMENT = "predefined_log_file";
|
||||
@NonNls private static final String FILE_OUTPUT = "output_file";
|
||||
@NonNls private static final String SAVE = "is_save";
|
||||
@NonNls private static final String OUTPUT_FILE = "path";
|
||||
@NonNls private static final String SHOW_CONSOLE_ON_STD_OUT = "show_console_on_std_out";
|
||||
@NonNls private static final String SHOW_CONSOLE_ON_STD_ERR = "show_console_on_std_err";
|
||||
|
||||
private final Icon myIcon;
|
||||
private boolean mySaveOutput = false;
|
||||
private boolean myShowConsoleOnStdOut = false;
|
||||
private boolean myShowConsoleOnStdErr = false;
|
||||
private String myFileOutputPath = null;
|
||||
|
||||
protected RunConfigurationBase(final Project project, final ConfigurationFactory factory, final String name) {
|
||||
myProject = project;
|
||||
myFactory = factory;
|
||||
myName = name;
|
||||
myIcon = factory.getIcon();
|
||||
}
|
||||
|
||||
public int getUniqueID() {
|
||||
return System.identityHashCode(this);
|
||||
}
|
||||
|
||||
public final ConfigurationFactory getFactory() {
|
||||
return myFactory;
|
||||
}
|
||||
|
||||
public final void setName(final String name) {
|
||||
myName = name;
|
||||
}
|
||||
|
||||
public final Project getProject() {
|
||||
return myProject;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigurationType getType() {
|
||||
return myFactory.getType();
|
||||
}
|
||||
|
||||
public Icon getIcon() {
|
||||
return myIcon;
|
||||
}
|
||||
|
||||
public final String getName() {
|
||||
return myName;
|
||||
}
|
||||
|
||||
public final int hashCode() {
|
||||
return super.hashCode();
|
||||
}
|
||||
|
||||
public void checkRunnerSettings(@NotNull ProgramRunner runner, @Nullable RunnerSettings runnerSettings,
|
||||
@Nullable ConfigurationPerRunnerSettings configurationPerRunnerSettings) throws RuntimeConfigurationException {
|
||||
}
|
||||
|
||||
public void checkSettingsBeforeRun() throws RuntimeConfigurationException {
|
||||
}
|
||||
|
||||
public boolean canRunOn(@NotNull ExecutionTarget target) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public final boolean equals(final Object obj) {
|
||||
return super.equals(obj);
|
||||
}
|
||||
|
||||
public RunConfiguration clone() {
|
||||
final RunConfigurationBase runConfiguration = (RunConfigurationBase)super.clone();
|
||||
runConfiguration.myLogFiles = new ArrayList<LogFileOptions>(myLogFiles);
|
||||
runConfiguration.myPredefinedLogFiles = new ArrayList<PredefinedLogFile>(myPredefinedLogFiles);
|
||||
runConfiguration.myFileOutputPath = myFileOutputPath;
|
||||
runConfiguration.mySaveOutput = mySaveOutput;
|
||||
runConfiguration.myShowConsoleOnStdOut = myShowConsoleOnStdOut;
|
||||
runConfiguration.myShowConsoleOnStdErr = myShowConsoleOnStdErr;
|
||||
copyCopyableDataTo(runConfiguration);
|
||||
return runConfiguration;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public LogFileOptions getOptionsForPredefinedLogFile(PredefinedLogFile predefinedLogFile) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void removeAllPredefinedLogFiles() {
|
||||
myPredefinedLogFiles.clear();
|
||||
}
|
||||
|
||||
public void addPredefinedLogFile(PredefinedLogFile predefinedLogFile) {
|
||||
myPredefinedLogFiles.add(predefinedLogFile);
|
||||
}
|
||||
|
||||
public ArrayList<PredefinedLogFile> getPredefinedLogFiles() {
|
||||
return myPredefinedLogFiles;
|
||||
}
|
||||
|
||||
public ArrayList<LogFileOptions> getAllLogFiles() {
|
||||
final ArrayList<LogFileOptions> list = new ArrayList<LogFileOptions>(myLogFiles);
|
||||
for (PredefinedLogFile predefinedLogFile : myPredefinedLogFiles) {
|
||||
final LogFileOptions options = getOptionsForPredefinedLogFile(predefinedLogFile);
|
||||
if (options != null) {
|
||||
list.add(options);
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public ArrayList<LogFileOptions> getLogFiles() {
|
||||
return myLogFiles;
|
||||
}
|
||||
|
||||
public void addLogFile(String file, String alias, boolean checked){
|
||||
myLogFiles.add(new LogFileOptions(alias, file, checked, true, false));
|
||||
}
|
||||
|
||||
public void addLogFile(String file, String alias, boolean checked, boolean skipContent, final boolean showAll){
|
||||
myLogFiles.add(new LogFileOptions(alias, file, checked, skipContent, showAll));
|
||||
}
|
||||
|
||||
public void removeAllLogFiles() {
|
||||
myLogFiles.clear();
|
||||
}
|
||||
|
||||
//invoke before run/debug tabs are shown.
|
||||
//Should be overriden to add additional tabs for run/debug toolwindow
|
||||
public void createAdditionalTabComponents(AdditionalTabComponentManager manager, ProcessHandler startedProcess) {
|
||||
}
|
||||
|
||||
public void customizeLogConsole(LogConsole console) {
|
||||
}
|
||||
|
||||
public void readExternal(Element element) throws InvalidDataException {
|
||||
myLogFiles.clear();
|
||||
for (final Object o : element.getChildren(LOG_FILE)) {
|
||||
LogFileOptions logFileOptions = new LogFileOptions();
|
||||
logFileOptions.readExternal((Element)o);
|
||||
myLogFiles.add(logFileOptions);
|
||||
}
|
||||
myPredefinedLogFiles.clear();
|
||||
final List list = element.getChildren(PREDEFINED_LOG_FILE_ELEMENT);
|
||||
for (Object fileElement : list) {
|
||||
final PredefinedLogFile logFile = new PredefinedLogFile();
|
||||
logFile.readExternal((Element)fileElement);
|
||||
myPredefinedLogFiles.add(logFile);
|
||||
}
|
||||
final Element fileOutputElement = element.getChild(FILE_OUTPUT);
|
||||
if (fileOutputElement != null) {
|
||||
myFileOutputPath = fileOutputElement.getAttributeValue(OUTPUT_FILE);
|
||||
final String isSave = fileOutputElement.getAttributeValue(SAVE);
|
||||
mySaveOutput = isSave != null && Boolean.parseBoolean(isSave);
|
||||
}
|
||||
myShowConsoleOnStdOut = Boolean.parseBoolean(element.getAttributeValue(SHOW_CONSOLE_ON_STD_OUT));
|
||||
myShowConsoleOnStdErr = Boolean.parseBoolean(element.getAttributeValue(SHOW_CONSOLE_ON_STD_ERR));
|
||||
}
|
||||
|
||||
public void writeExternal(Element element) throws WriteExternalException {
|
||||
for (final LogFileOptions options : myLogFiles) {
|
||||
Element logFile = new Element(LOG_FILE);
|
||||
options.writeExternal(logFile);
|
||||
element.addContent(logFile);
|
||||
}
|
||||
for (PredefinedLogFile predefinedLogFile : myPredefinedLogFiles) {
|
||||
Element fileElement = new Element(PREDEFINED_LOG_FILE_ELEMENT);
|
||||
predefinedLogFile.writeExternal(fileElement);
|
||||
element.addContent(fileElement);
|
||||
}
|
||||
final Element fileOutputPathElement = new Element(FILE_OUTPUT);
|
||||
if (myFileOutputPath != null) {
|
||||
fileOutputPathElement.setAttribute(OUTPUT_FILE, myFileOutputPath);
|
||||
}
|
||||
fileOutputPathElement.setAttribute(SAVE, String.valueOf(mySaveOutput));
|
||||
if (myFileOutputPath != null || mySaveOutput) {
|
||||
element.addContent(fileOutputPathElement);
|
||||
}
|
||||
if (myShowConsoleOnStdOut) {//default value shouldn't be written
|
||||
element.setAttribute(SHOW_CONSOLE_ON_STD_OUT, String.valueOf(myShowConsoleOnStdOut));
|
||||
}
|
||||
if (myShowConsoleOnStdErr) {//default value shouldn't be written
|
||||
element.setAttribute(SHOW_CONSOLE_ON_STD_ERR, String.valueOf(myShowConsoleOnStdErr));
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isSaveOutputToFile() {
|
||||
return mySaveOutput;
|
||||
}
|
||||
|
||||
public void setSaveOutputToFile(boolean redirectOutput) {
|
||||
mySaveOutput = redirectOutput;
|
||||
}
|
||||
|
||||
public boolean isShowConsoleOnStdOut() {
|
||||
return myShowConsoleOnStdOut;
|
||||
}
|
||||
|
||||
public void setShowConsoleOnStdOut(boolean showConsoleOnStdOut) {
|
||||
myShowConsoleOnStdOut = showConsoleOnStdOut;
|
||||
}
|
||||
|
||||
public boolean isShowConsoleOnStdErr() {
|
||||
return myShowConsoleOnStdErr;
|
||||
}
|
||||
|
||||
public void setShowConsoleOnStdErr(boolean showConsoleOnStdErr) {
|
||||
myShowConsoleOnStdErr = showConsoleOnStdErr;
|
||||
}
|
||||
|
||||
public String getOutputFilePath() {
|
||||
return myFileOutputPath;
|
||||
}
|
||||
|
||||
public void setFileOutputPath(String fileOutputPath) {
|
||||
myFileOutputPath = fileOutputPath;
|
||||
}
|
||||
|
||||
public boolean collectOutputFromProcessHandler() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean excludeCompileBeforeLaunchOption() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getType().getDisplayName() + ": " + getName();
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 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.execution.configurations;
|
||||
|
||||
import com.intellij.diagnostic.logging.LogConsole;
|
||||
import com.intellij.execution.ExecutionTarget;
|
||||
import com.intellij.execution.process.ProcessHandler;
|
||||
import com.intellij.execution.runners.ProgramRunner;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.util.InvalidDataException;
|
||||
import com.intellij.openapi.util.UserDataHolderBase;
|
||||
import com.intellij.openapi.util.WriteExternalException;
|
||||
import org.jdom.Element;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author dyoma
|
||||
*/
|
||||
public abstract class RunConfigurationBase extends UserDataHolderBase implements RunConfiguration, TargetAwareRunProfile {
|
||||
private final ConfigurationFactory myFactory;
|
||||
private final Project myProject;
|
||||
private String myName = "";
|
||||
|
||||
private ArrayList<LogFileOptions> myLogFiles = new ArrayList<LogFileOptions>();
|
||||
private ArrayList<PredefinedLogFile> myPredefinedLogFiles = new ArrayList<PredefinedLogFile>();
|
||||
|
||||
@NonNls private static final String LOG_FILE = "log_file";
|
||||
@NonNls private static final String PREDEFINED_LOG_FILE_ELEMENT = "predefined_log_file";
|
||||
@NonNls private static final String FILE_OUTPUT = "output_file";
|
||||
@NonNls private static final String SAVE = "is_save";
|
||||
@NonNls private static final String OUTPUT_FILE = "path";
|
||||
@NonNls private static final String SHOW_CONSOLE_ON_STD_OUT = "show_console_on_std_out";
|
||||
@NonNls private static final String SHOW_CONSOLE_ON_STD_ERR = "show_console_on_std_err";
|
||||
|
||||
private final Icon myIcon;
|
||||
private boolean mySaveOutput = false;
|
||||
private boolean myShowConsoleOnStdOut = false;
|
||||
private boolean myShowConsoleOnStdErr = false;
|
||||
private String myFileOutputPath = null;
|
||||
|
||||
protected RunConfigurationBase(final Project project, final ConfigurationFactory factory, final String name) {
|
||||
myProject = project;
|
||||
myFactory = factory;
|
||||
myName = name;
|
||||
myIcon = factory.getIcon();
|
||||
}
|
||||
|
||||
public int getUniqueID() {
|
||||
return System.identityHashCode(this);
|
||||
}
|
||||
|
||||
public final ConfigurationFactory getFactory() {
|
||||
return myFactory;
|
||||
}
|
||||
|
||||
public final void setName(final String name) {
|
||||
myName = name;
|
||||
}
|
||||
|
||||
public final Project getProject() {
|
||||
return myProject;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigurationType getType() {
|
||||
return myFactory.getType();
|
||||
}
|
||||
|
||||
public Icon getIcon() {
|
||||
return myIcon;
|
||||
}
|
||||
|
||||
public final String getName() {
|
||||
return myName;
|
||||
}
|
||||
|
||||
public final int hashCode() {
|
||||
return super.hashCode();
|
||||
}
|
||||
|
||||
public void checkRunnerSettings(@NotNull ProgramRunner runner, @Nullable RunnerSettings runnerSettings,
|
||||
@Nullable ConfigurationPerRunnerSettings configurationPerRunnerSettings) throws RuntimeConfigurationException {
|
||||
}
|
||||
|
||||
public void checkSettingsBeforeRun() throws RuntimeConfigurationException {
|
||||
}
|
||||
|
||||
public boolean canRunOn(@NotNull ExecutionTarget target) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public final boolean equals(final Object obj) {
|
||||
return super.equals(obj);
|
||||
}
|
||||
|
||||
public RunConfiguration clone() {
|
||||
final RunConfigurationBase runConfiguration = (RunConfigurationBase)super.clone();
|
||||
runConfiguration.myLogFiles = new ArrayList<LogFileOptions>(myLogFiles);
|
||||
runConfiguration.myPredefinedLogFiles = new ArrayList<PredefinedLogFile>(myPredefinedLogFiles);
|
||||
runConfiguration.myFileOutputPath = myFileOutputPath;
|
||||
runConfiguration.mySaveOutput = mySaveOutput;
|
||||
runConfiguration.myShowConsoleOnStdOut = myShowConsoleOnStdOut;
|
||||
runConfiguration.myShowConsoleOnStdErr = myShowConsoleOnStdErr;
|
||||
copyCopyableDataTo(runConfiguration);
|
||||
return runConfiguration;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public LogFileOptions getOptionsForPredefinedLogFile(PredefinedLogFile predefinedLogFile) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void removeAllPredefinedLogFiles() {
|
||||
myPredefinedLogFiles.clear();
|
||||
}
|
||||
|
||||
public void addPredefinedLogFile(PredefinedLogFile predefinedLogFile) {
|
||||
myPredefinedLogFiles.add(predefinedLogFile);
|
||||
}
|
||||
|
||||
public ArrayList<PredefinedLogFile> getPredefinedLogFiles() {
|
||||
return myPredefinedLogFiles;
|
||||
}
|
||||
|
||||
public ArrayList<LogFileOptions> getAllLogFiles() {
|
||||
final ArrayList<LogFileOptions> list = new ArrayList<LogFileOptions>(myLogFiles);
|
||||
for (PredefinedLogFile predefinedLogFile : myPredefinedLogFiles) {
|
||||
final LogFileOptions options = getOptionsForPredefinedLogFile(predefinedLogFile);
|
||||
if (options != null) {
|
||||
list.add(options);
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public ArrayList<LogFileOptions> getLogFiles() {
|
||||
return myLogFiles;
|
||||
}
|
||||
|
||||
public void addLogFile(String file, String alias, boolean checked){
|
||||
myLogFiles.add(new LogFileOptions(alias, file, checked, true, false));
|
||||
}
|
||||
|
||||
public void addLogFile(String file, String alias, boolean checked, boolean skipContent, final boolean showAll){
|
||||
myLogFiles.add(new LogFileOptions(alias, file, checked, skipContent, showAll));
|
||||
}
|
||||
|
||||
public void removeAllLogFiles() {
|
||||
myLogFiles.clear();
|
||||
}
|
||||
|
||||
//invoke before run/debug tabs are shown.
|
||||
//Should be overriden to add additional tabs for run/debug toolwindow
|
||||
public void createAdditionalTabComponents(AdditionalTabComponentManager manager, ProcessHandler startedProcess) {
|
||||
}
|
||||
|
||||
public void customizeLogConsole(LogConsole console) {
|
||||
}
|
||||
|
||||
public void readExternal(Element element) throws InvalidDataException {
|
||||
myLogFiles.clear();
|
||||
for (final Object o : element.getChildren(LOG_FILE)) {
|
||||
LogFileOptions logFileOptions = new LogFileOptions();
|
||||
logFileOptions.readExternal((Element)o);
|
||||
myLogFiles.add(logFileOptions);
|
||||
}
|
||||
myPredefinedLogFiles.clear();
|
||||
final List list = element.getChildren(PREDEFINED_LOG_FILE_ELEMENT);
|
||||
for (Object fileElement : list) {
|
||||
final PredefinedLogFile logFile = new PredefinedLogFile();
|
||||
logFile.readExternal((Element)fileElement);
|
||||
myPredefinedLogFiles.add(logFile);
|
||||
}
|
||||
final Element fileOutputElement = element.getChild(FILE_OUTPUT);
|
||||
if (fileOutputElement != null) {
|
||||
myFileOutputPath = fileOutputElement.getAttributeValue(OUTPUT_FILE);
|
||||
final String isSave = fileOutputElement.getAttributeValue(SAVE);
|
||||
mySaveOutput = isSave != null && Boolean.parseBoolean(isSave);
|
||||
}
|
||||
myShowConsoleOnStdOut = Boolean.parseBoolean(element.getAttributeValue(SHOW_CONSOLE_ON_STD_OUT));
|
||||
myShowConsoleOnStdErr = Boolean.parseBoolean(element.getAttributeValue(SHOW_CONSOLE_ON_STD_ERR));
|
||||
}
|
||||
|
||||
public void writeExternal(Element element) throws WriteExternalException {
|
||||
for (final LogFileOptions options : myLogFiles) {
|
||||
Element logFile = new Element(LOG_FILE);
|
||||
options.writeExternal(logFile);
|
||||
element.addContent(logFile);
|
||||
}
|
||||
for (PredefinedLogFile predefinedLogFile : myPredefinedLogFiles) {
|
||||
Element fileElement = new Element(PREDEFINED_LOG_FILE_ELEMENT);
|
||||
predefinedLogFile.writeExternal(fileElement);
|
||||
element.addContent(fileElement);
|
||||
}
|
||||
final Element fileOutputPathElement = new Element(FILE_OUTPUT);
|
||||
if (myFileOutputPath != null) {
|
||||
fileOutputPathElement.setAttribute(OUTPUT_FILE, myFileOutputPath);
|
||||
}
|
||||
fileOutputPathElement.setAttribute(SAVE, String.valueOf(mySaveOutput));
|
||||
if (myFileOutputPath != null || mySaveOutput) {
|
||||
element.addContent(fileOutputPathElement);
|
||||
}
|
||||
if (myShowConsoleOnStdOut) {//default value shouldn't be written
|
||||
element.setAttribute(SHOW_CONSOLE_ON_STD_OUT, String.valueOf(myShowConsoleOnStdOut));
|
||||
}
|
||||
if (myShowConsoleOnStdErr) {//default value shouldn't be written
|
||||
element.setAttribute(SHOW_CONSOLE_ON_STD_ERR, String.valueOf(myShowConsoleOnStdErr));
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isSaveOutputToFile() {
|
||||
return mySaveOutput;
|
||||
}
|
||||
|
||||
public void setSaveOutputToFile(boolean redirectOutput) {
|
||||
mySaveOutput = redirectOutput;
|
||||
}
|
||||
|
||||
public boolean isShowConsoleOnStdOut() {
|
||||
return myShowConsoleOnStdOut;
|
||||
}
|
||||
|
||||
public void setShowConsoleOnStdOut(boolean showConsoleOnStdOut) {
|
||||
myShowConsoleOnStdOut = showConsoleOnStdOut;
|
||||
}
|
||||
|
||||
public boolean isShowConsoleOnStdErr() {
|
||||
return myShowConsoleOnStdErr;
|
||||
}
|
||||
|
||||
public void setShowConsoleOnStdErr(boolean showConsoleOnStdErr) {
|
||||
myShowConsoleOnStdErr = showConsoleOnStdErr;
|
||||
}
|
||||
|
||||
public String getOutputFilePath() {
|
||||
return myFileOutputPath;
|
||||
}
|
||||
|
||||
public void setFileOutputPath(String fileOutputPath) {
|
||||
myFileOutputPath = fileOutputPath;
|
||||
}
|
||||
|
||||
public boolean collectOutputFromProcessHandler() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean excludeCompileBeforeLaunchOption() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getType().getDisplayName() + ": " + getName();
|
||||
}
|
||||
}
|
||||
|
||||
+23
-23
@@ -1,23 +1,23 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.execution.configurations;
|
||||
|
||||
import com.intellij.execution.ExecutionTarget;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public interface TargetAwareRunProfile extends RunProfile {
|
||||
boolean canRunOn(@NotNull ExecutionTarget target);
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.execution.configurations;
|
||||
|
||||
import com.intellij.execution.ExecutionTarget;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public interface TargetAwareRunProfile extends RunProfile {
|
||||
boolean canRunOn(@NotNull ExecutionTarget target);
|
||||
}
|
||||
|
||||
@@ -1,95 +1,95 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.formatting;
|
||||
|
||||
import com.intellij.openapi.util.TextRange;
|
||||
import gnu.trove.TObjectIntHashMap;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* Holds settings that should be used if
|
||||
* {@link Spacing#createDependentLFSpacing(int, int, TextRange, boolean, int, DependentSpacingRule) dependent spacing}
|
||||
* target region changes its 'contains line feeds' status.
|
||||
*
|
||||
* @author Denis Zhdanov
|
||||
* @since 6/28/12 1:08 PM
|
||||
*/
|
||||
public class DependentSpacingRule {
|
||||
|
||||
public enum Anchor {
|
||||
MIN_LINE_FEEDS, MAX_LINE_FEEDS
|
||||
}
|
||||
|
||||
public enum Trigger {
|
||||
HAS_LINE_FEEDS, DOES_NOT_HAVE_LINE_FEEDS
|
||||
}
|
||||
|
||||
public static final DependentSpacingRule DEFAULT =
|
||||
new DependentSpacingRule(Trigger.HAS_LINE_FEEDS).registerData(Anchor.MIN_LINE_FEEDS, 1);
|
||||
|
||||
private final TObjectIntHashMap<Anchor> myData = new TObjectIntHashMap<Anchor>();
|
||||
|
||||
@NotNull private final Trigger myTrigger;
|
||||
|
||||
public DependentSpacingRule(@NotNull Trigger trigger) {
|
||||
myTrigger = trigger;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Trigger getTrigger() {
|
||||
return myTrigger;
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows to register given data for the given anchor within the current rule.
|
||||
*
|
||||
* @param anchor target anchor
|
||||
* @param data data to register for the given anchor
|
||||
* @param <T> data's type
|
||||
* @see #getData(Anchor)
|
||||
*/
|
||||
public DependentSpacingRule registerData(@NotNull Anchor anchor, int data) {
|
||||
myData.put(anchor, data);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param anchor target data anchor
|
||||
* @return <code>true</code> if there is a data registered for the given anchor within the current rule;
|
||||
* <code>false</code> otherwise
|
||||
*/
|
||||
public boolean hasData(@NotNull Anchor anchor) {
|
||||
return myData.containsKey(anchor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows to retrieve data associated with the given anchor.
|
||||
*
|
||||
* @param anchor target anchor
|
||||
* @param <T> data's type
|
||||
* @return data associated for the given anchor
|
||||
* @throws IllegalArgumentException if no data is registered for the given anchor
|
||||
* (use {@link #hasData(Anchor)} for the preliminary examination)
|
||||
*/
|
||||
public int getData(@NotNull Anchor anchor) throws IllegalArgumentException {
|
||||
if (!myData.containsKey(anchor)) {
|
||||
throw new IllegalArgumentException(String.format(
|
||||
"No data is registered for the dependent spacing rule %s. Registered: %s", anchor, myData
|
||||
));
|
||||
}
|
||||
return myData.get(anchor);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.formatting;
|
||||
|
||||
import com.intellij.openapi.util.TextRange;
|
||||
import gnu.trove.TObjectIntHashMap;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* Holds settings that should be used if
|
||||
* {@link Spacing#createDependentLFSpacing(int, int, TextRange, boolean, int, DependentSpacingRule) dependent spacing}
|
||||
* target region changes its 'contains line feeds' status.
|
||||
*
|
||||
* @author Denis Zhdanov
|
||||
* @since 6/28/12 1:08 PM
|
||||
*/
|
||||
public class DependentSpacingRule {
|
||||
|
||||
public enum Anchor {
|
||||
MIN_LINE_FEEDS, MAX_LINE_FEEDS
|
||||
}
|
||||
|
||||
public enum Trigger {
|
||||
HAS_LINE_FEEDS, DOES_NOT_HAVE_LINE_FEEDS
|
||||
}
|
||||
|
||||
public static final DependentSpacingRule DEFAULT =
|
||||
new DependentSpacingRule(Trigger.HAS_LINE_FEEDS).registerData(Anchor.MIN_LINE_FEEDS, 1);
|
||||
|
||||
private final TObjectIntHashMap<Anchor> myData = new TObjectIntHashMap<Anchor>();
|
||||
|
||||
@NotNull private final Trigger myTrigger;
|
||||
|
||||
public DependentSpacingRule(@NotNull Trigger trigger) {
|
||||
myTrigger = trigger;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Trigger getTrigger() {
|
||||
return myTrigger;
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows to register given data for the given anchor within the current rule.
|
||||
*
|
||||
* @param anchor target anchor
|
||||
* @param data data to register for the given anchor
|
||||
* @param <T> data's type
|
||||
* @see #getData(Anchor)
|
||||
*/
|
||||
public DependentSpacingRule registerData(@NotNull Anchor anchor, int data) {
|
||||
myData.put(anchor, data);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param anchor target data anchor
|
||||
* @return <code>true</code> if there is a data registered for the given anchor within the current rule;
|
||||
* <code>false</code> otherwise
|
||||
*/
|
||||
public boolean hasData(@NotNull Anchor anchor) {
|
||||
return myData.containsKey(anchor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows to retrieve data associated with the given anchor.
|
||||
*
|
||||
* @param anchor target anchor
|
||||
* @param <T> data's type
|
||||
* @return data associated for the given anchor
|
||||
* @throws IllegalArgumentException if no data is registered for the given anchor
|
||||
* (use {@link #hasData(Anchor)} for the preliminary examination)
|
||||
*/
|
||||
public int getData(@NotNull Anchor anchor) throws IllegalArgumentException {
|
||||
if (!myData.containsKey(anchor)) {
|
||||
throw new IllegalArgumentException(String.format(
|
||||
"No data is registered for the dependent spacing rule %s. Registered: %s", anchor, myData
|
||||
));
|
||||
}
|
||||
return myData.get(anchor);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,185 +1,185 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.formatting;
|
||||
|
||||
import com.intellij.openapi.util.TextRange;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* The spacing setting for a formatting model block. Indicates the number of spaces and/or
|
||||
* line breaks that should be inserted between the specified children of the specified block.
|
||||
*
|
||||
* @see Block#getSpacing(Block, Block)
|
||||
*/
|
||||
|
||||
public abstract class Spacing {
|
||||
private static SpacingFactory myFactory;
|
||||
|
||||
static void setFactory(SpacingFactory factory) {
|
||||
myFactory = factory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a regular spacing setting instance.
|
||||
*
|
||||
* @param minSpaces The minimum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related. Spaces are inserted
|
||||
* if there are less than this amount of spaces in the document.
|
||||
* @param maxSpaces The maximum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related, or <code>Integer.MAX_VALUE</code>
|
||||
* if the number of spaces is not limited. Spaces are deleted if there are
|
||||
* more than this amount of spaces in the document.
|
||||
* @param minLineFeeds The minimum number of line breaks that should be present between the blocks
|
||||
* to which the spacing setting instance is related.
|
||||
* @param keepLineBreaks Whether the existing line breaks between the blocks should be preserved.
|
||||
* @param keepBlankLines Whether the existing blank lines between the blocks should be preserved.
|
||||
* @return the spacing setting instance.
|
||||
*/
|
||||
public static Spacing createSpacing(int minSpaces,
|
||||
int maxSpaces,
|
||||
int minLineFeeds,
|
||||
boolean keepLineBreaks,
|
||||
int keepBlankLines) {
|
||||
return myFactory.createSpacing(minSpaces, maxSpaces, minLineFeeds, keepLineBreaks, keepBlankLines);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a regular spacing setting instance.
|
||||
*
|
||||
* @param minSpaces The minimum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related. Spaces are inserted
|
||||
* if there are less than this amount of spaces in the document.
|
||||
* @param maxSpaces The maximum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related, or <code>Integer.MAX_VALUE</code>
|
||||
* if the number of spaces is not limited. Spaces are deleted if there are
|
||||
* more than this amount of spaces in the document.
|
||||
* @param minLineFeeds The minimum number of line breaks that should be present between the blocks
|
||||
* to which the spacing setting instance is related.
|
||||
* @param keepLineBreaks Whether the existing line breaks between the blocks should be preserved.
|
||||
* @param keepBlankLines Whether the existing blank lines between the blocks should be preserved.
|
||||
* @return the spacing setting instance.
|
||||
*/
|
||||
public static Spacing createSpacing(int minSpaces,
|
||||
int maxSpaces,
|
||||
int minLineFeeds,
|
||||
boolean keepLineBreaks,
|
||||
int keepBlankLines,
|
||||
int prefLineFeeds) {
|
||||
return myFactory.createSpacing(minSpaces, maxSpaces, minLineFeeds, keepLineBreaks, keepBlankLines, prefLineFeeds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a spacing setting instance indicating that no line breaks or spaces can be
|
||||
* inserted or removed by the formatter between the specified two blocks.
|
||||
* @return the spacing setting instance.
|
||||
*/
|
||||
public static Spacing getReadOnlySpacing() {
|
||||
return myFactory.getReadOnlySpacing();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a spacing setting instance which inserts a line break if the specified text range also
|
||||
* contains a line break. Used for formatting rules like the "next line if wrapped" brace placement.
|
||||
*
|
||||
* @param minSpaces The minimum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related. Spaces are inserted
|
||||
* if there are less than this amount of spaces in the document.
|
||||
* @param maxSpaces The maximum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related, or <code>Integer.MAX_VALUE</code>
|
||||
* if the number of spaces is not limited. Spaces are deleted if there are
|
||||
* more than this amount of spaces in the document.
|
||||
* @param dependency The text range checked for the presence of line breaks.
|
||||
* @param keepLineBreaks Whether the existing line breaks between the blocks should be preserved.
|
||||
* @param keepBlankLines Whether the existing blank lines between the blocks should be preserved.
|
||||
* @return the spacing setting instance.
|
||||
*/
|
||||
public static Spacing createDependentLFSpacing(int minSpaces,
|
||||
int maxSpaces,
|
||||
TextRange dependency,
|
||||
boolean keepLineBreaks,
|
||||
int keepBlankLines)
|
||||
{
|
||||
return createDependentLFSpacing(minSpaces, maxSpaces, dependency, keepLineBreaks, keepBlankLines, DependentSpacingRule.DEFAULT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a spacing setting instance which uses settings from the given dependent spacing rule if the specified text range changes
|
||||
* its 'has line feed' status during formatting (new line feed is added and the range hasn't contained them before
|
||||
* or it contained line feed(s) and it was removed during formatting).
|
||||
* <p/>
|
||||
* Used for formatting rules like the "next line if wrapped" brace placement.
|
||||
*
|
||||
* @param minSpaces The minimum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related. Spaces are inserted
|
||||
* if there are less than this amount of spaces in the document.
|
||||
* @param maxSpaces The maximum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related, or <code>Integer.MAX_VALUE</code>
|
||||
* if the number of spaces is not limited. Spaces are deleted if there are
|
||||
* more than this amount of spaces in the document.
|
||||
* @param dependencyRange The text range checked for the presence of line breaks.
|
||||
* @param keepLineBreaks Whether the existing line breaks between the blocks should be preserved.
|
||||
* @param keepBlankLines Whether the existing blank lines between the blocks should be preserved.
|
||||
* @param rule settings to use if dependent region changes its 'contains line feed' status during formatting
|
||||
* @return the spacing setting instance for the given parameters
|
||||
*/
|
||||
public static Spacing createDependentLFSpacing(int minSpaces,
|
||||
int maxSpaces,
|
||||
@NotNull TextRange dependencyRange,
|
||||
boolean keepLineBreaks,
|
||||
int keepBlankLines,
|
||||
@NotNull DependentSpacingRule rule)
|
||||
{
|
||||
return myFactory.createDependentLFSpacing(minSpaces, maxSpaces, dependencyRange, keepLineBreaks, keepBlankLines, rule);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a spacing setting instance which preserves the presence of spaces between the blocks but,
|
||||
* if spaces are present, may insert or delete the spaces. Used, for example, for HTML formatting
|
||||
* where the presence of a whitespace is significant but the specific number of whitespaces at a
|
||||
* given location is not.
|
||||
*
|
||||
* @param keepLineBreaks Whether the existing line breaks between the blocks should be preserved.
|
||||
* @param keepBlankLines Whether the existing blank lines between the blocks should be preserved.
|
||||
* @return the spacing setting instance.
|
||||
*/
|
||||
public static Spacing createSafeSpacing(boolean keepLineBreaks,
|
||||
int keepBlankLines) {
|
||||
return myFactory.createSafeSpacing(keepLineBreaks, keepBlankLines);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a spacing setting instance that keeps the second child on the first column if it was
|
||||
* there before the formatting, but may indent the second child if it was not in the first column.
|
||||
* Used for implementing the "Keep when Reformatting | Comment in first column" setting.
|
||||
*
|
||||
* @param minSpaces The minimum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related. Spaces are inserted
|
||||
* if there are less than this amount of spaces in the document.
|
||||
* @param maxSpaces The maximum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related, or <code>Integer.MAX_VALUE</code>
|
||||
* if the number of spaces is not limited. Spaces are deleted if there are
|
||||
* more than this amount of spaces in the document.
|
||||
* @param keepLineBreaks Whether the existing line breaks between the blocks should be preserved.
|
||||
* @param keepBlankLines Whether the existing blank lines between the blocks should be preserved.
|
||||
* @return the spacing setting instance.
|
||||
*/
|
||||
public static Spacing createKeepingFirstColumnSpacing(final int minSpaces,
|
||||
final int maxSpaces,
|
||||
final boolean keepLineBreaks,
|
||||
final int keepBlankLines) {
|
||||
return myFactory.createKeepingFirstColumnSpacing(minSpaces, maxSpaces, keepLineBreaks, keepBlankLines);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.formatting;
|
||||
|
||||
import com.intellij.openapi.util.TextRange;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* The spacing setting for a formatting model block. Indicates the number of spaces and/or
|
||||
* line breaks that should be inserted between the specified children of the specified block.
|
||||
*
|
||||
* @see Block#getSpacing(Block, Block)
|
||||
*/
|
||||
|
||||
public abstract class Spacing {
|
||||
private static SpacingFactory myFactory;
|
||||
|
||||
static void setFactory(SpacingFactory factory) {
|
||||
myFactory = factory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a regular spacing setting instance.
|
||||
*
|
||||
* @param minSpaces The minimum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related. Spaces are inserted
|
||||
* if there are less than this amount of spaces in the document.
|
||||
* @param maxSpaces The maximum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related, or <code>Integer.MAX_VALUE</code>
|
||||
* if the number of spaces is not limited. Spaces are deleted if there are
|
||||
* more than this amount of spaces in the document.
|
||||
* @param minLineFeeds The minimum number of line breaks that should be present between the blocks
|
||||
* to which the spacing setting instance is related.
|
||||
* @param keepLineBreaks Whether the existing line breaks between the blocks should be preserved.
|
||||
* @param keepBlankLines Whether the existing blank lines between the blocks should be preserved.
|
||||
* @return the spacing setting instance.
|
||||
*/
|
||||
public static Spacing createSpacing(int minSpaces,
|
||||
int maxSpaces,
|
||||
int minLineFeeds,
|
||||
boolean keepLineBreaks,
|
||||
int keepBlankLines) {
|
||||
return myFactory.createSpacing(minSpaces, maxSpaces, minLineFeeds, keepLineBreaks, keepBlankLines);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a regular spacing setting instance.
|
||||
*
|
||||
* @param minSpaces The minimum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related. Spaces are inserted
|
||||
* if there are less than this amount of spaces in the document.
|
||||
* @param maxSpaces The maximum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related, or <code>Integer.MAX_VALUE</code>
|
||||
* if the number of spaces is not limited. Spaces are deleted if there are
|
||||
* more than this amount of spaces in the document.
|
||||
* @param minLineFeeds The minimum number of line breaks that should be present between the blocks
|
||||
* to which the spacing setting instance is related.
|
||||
* @param keepLineBreaks Whether the existing line breaks between the blocks should be preserved.
|
||||
* @param keepBlankLines Whether the existing blank lines between the blocks should be preserved.
|
||||
* @return the spacing setting instance.
|
||||
*/
|
||||
public static Spacing createSpacing(int minSpaces,
|
||||
int maxSpaces,
|
||||
int minLineFeeds,
|
||||
boolean keepLineBreaks,
|
||||
int keepBlankLines,
|
||||
int prefLineFeeds) {
|
||||
return myFactory.createSpacing(minSpaces, maxSpaces, minLineFeeds, keepLineBreaks, keepBlankLines, prefLineFeeds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a spacing setting instance indicating that no line breaks or spaces can be
|
||||
* inserted or removed by the formatter between the specified two blocks.
|
||||
* @return the spacing setting instance.
|
||||
*/
|
||||
public static Spacing getReadOnlySpacing() {
|
||||
return myFactory.getReadOnlySpacing();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a spacing setting instance which inserts a line break if the specified text range also
|
||||
* contains a line break. Used for formatting rules like the "next line if wrapped" brace placement.
|
||||
*
|
||||
* @param minSpaces The minimum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related. Spaces are inserted
|
||||
* if there are less than this amount of spaces in the document.
|
||||
* @param maxSpaces The maximum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related, or <code>Integer.MAX_VALUE</code>
|
||||
* if the number of spaces is not limited. Spaces are deleted if there are
|
||||
* more than this amount of spaces in the document.
|
||||
* @param dependency The text range checked for the presence of line breaks.
|
||||
* @param keepLineBreaks Whether the existing line breaks between the blocks should be preserved.
|
||||
* @param keepBlankLines Whether the existing blank lines between the blocks should be preserved.
|
||||
* @return the spacing setting instance.
|
||||
*/
|
||||
public static Spacing createDependentLFSpacing(int minSpaces,
|
||||
int maxSpaces,
|
||||
TextRange dependency,
|
||||
boolean keepLineBreaks,
|
||||
int keepBlankLines)
|
||||
{
|
||||
return createDependentLFSpacing(minSpaces, maxSpaces, dependency, keepLineBreaks, keepBlankLines, DependentSpacingRule.DEFAULT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a spacing setting instance which uses settings from the given dependent spacing rule if the specified text range changes
|
||||
* its 'has line feed' status during formatting (new line feed is added and the range hasn't contained them before
|
||||
* or it contained line feed(s) and it was removed during formatting).
|
||||
* <p/>
|
||||
* Used for formatting rules like the "next line if wrapped" brace placement.
|
||||
*
|
||||
* @param minSpaces The minimum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related. Spaces are inserted
|
||||
* if there are less than this amount of spaces in the document.
|
||||
* @param maxSpaces The maximum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related, or <code>Integer.MAX_VALUE</code>
|
||||
* if the number of spaces is not limited. Spaces are deleted if there are
|
||||
* more than this amount of spaces in the document.
|
||||
* @param dependencyRange The text range checked for the presence of line breaks.
|
||||
* @param keepLineBreaks Whether the existing line breaks between the blocks should be preserved.
|
||||
* @param keepBlankLines Whether the existing blank lines between the blocks should be preserved.
|
||||
* @param rule settings to use if dependent region changes its 'contains line feed' status during formatting
|
||||
* @return the spacing setting instance for the given parameters
|
||||
*/
|
||||
public static Spacing createDependentLFSpacing(int minSpaces,
|
||||
int maxSpaces,
|
||||
@NotNull TextRange dependencyRange,
|
||||
boolean keepLineBreaks,
|
||||
int keepBlankLines,
|
||||
@NotNull DependentSpacingRule rule)
|
||||
{
|
||||
return myFactory.createDependentLFSpacing(minSpaces, maxSpaces, dependencyRange, keepLineBreaks, keepBlankLines, rule);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a spacing setting instance which preserves the presence of spaces between the blocks but,
|
||||
* if spaces are present, may insert or delete the spaces. Used, for example, for HTML formatting
|
||||
* where the presence of a whitespace is significant but the specific number of whitespaces at a
|
||||
* given location is not.
|
||||
*
|
||||
* @param keepLineBreaks Whether the existing line breaks between the blocks should be preserved.
|
||||
* @param keepBlankLines Whether the existing blank lines between the blocks should be preserved.
|
||||
* @return the spacing setting instance.
|
||||
*/
|
||||
public static Spacing createSafeSpacing(boolean keepLineBreaks,
|
||||
int keepBlankLines) {
|
||||
return myFactory.createSafeSpacing(keepLineBreaks, keepBlankLines);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a spacing setting instance that keeps the second child on the first column if it was
|
||||
* there before the formatting, but may indent the second child if it was not in the first column.
|
||||
* Used for implementing the "Keep when Reformatting | Comment in first column" setting.
|
||||
*
|
||||
* @param minSpaces The minimum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related. Spaces are inserted
|
||||
* if there are less than this amount of spaces in the document.
|
||||
* @param maxSpaces The maximum number of spaces that should be present between the blocks
|
||||
* to which the spacing setting instance is related, or <code>Integer.MAX_VALUE</code>
|
||||
* if the number of spaces is not limited. Spaces are deleted if there are
|
||||
* more than this amount of spaces in the document.
|
||||
* @param keepLineBreaks Whether the existing line breaks between the blocks should be preserved.
|
||||
* @param keepBlankLines Whether the existing blank lines between the blocks should be preserved.
|
||||
* @return the spacing setting instance.
|
||||
*/
|
||||
public static Spacing createKeepingFirstColumnSpacing(final int minSpaces,
|
||||
final int maxSpaces,
|
||||
final boolean keepLineBreaks,
|
||||
final int keepBlankLines) {
|
||||
return myFactory.createKeepingFirstColumnSpacing(minSpaces, maxSpaces, keepLineBreaks, keepBlankLines);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,58 +1,58 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.formatting;
|
||||
|
||||
import com.intellij.openapi.util.TextRange;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* Internal interface for creating spacing instances.
|
||||
*/
|
||||
|
||||
interface SpacingFactory {
|
||||
|
||||
@NotNull
|
||||
Spacing createSpacing(int minSpaces,
|
||||
int maxSpaces,
|
||||
int minLineFeeds,
|
||||
boolean keepLineBreaks,
|
||||
int keepBlankLines);
|
||||
|
||||
@NotNull
|
||||
Spacing getReadOnlySpacing();
|
||||
|
||||
@NotNull
|
||||
Spacing createDependentLFSpacing(int minSpaces,
|
||||
int maxSpaces,
|
||||
@NotNull TextRange dependencyRange,
|
||||
boolean keepLineBreaks,
|
||||
int keepBlankLines,
|
||||
@NotNull DependentSpacingRule rule);
|
||||
|
||||
@NotNull
|
||||
Spacing createSafeSpacing(boolean keepLineBreaks,
|
||||
int keepBlankLines);
|
||||
|
||||
@NotNull
|
||||
Spacing createKeepingFirstColumnSpacing(final int minSpaces,
|
||||
final int maxSpaces,
|
||||
final boolean keepLineBreaks,
|
||||
final int keepBlankLines);
|
||||
|
||||
@NotNull
|
||||
Spacing createSpacing(final int minSpaces, final int maxSpaces, final int minLineFeeds, final boolean keepLineBreaks,
|
||||
final int keepBlankLines, final int prefLineFeeds);
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.intellij.formatting;
|
||||
|
||||
import com.intellij.openapi.util.TextRange;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* Internal interface for creating spacing instances.
|
||||
*/
|
||||
|
||||
interface SpacingFactory {
|
||||
|
||||
@NotNull
|
||||
Spacing createSpacing(int minSpaces,
|
||||
int maxSpaces,
|
||||
int minLineFeeds,
|
||||
boolean keepLineBreaks,
|
||||
int keepBlankLines);
|
||||
|
||||
@NotNull
|
||||
Spacing getReadOnlySpacing();
|
||||
|
||||
@NotNull
|
||||
Spacing createDependentLFSpacing(int minSpaces,
|
||||
int maxSpaces,
|
||||
@NotNull TextRange dependencyRange,
|
||||
boolean keepLineBreaks,
|
||||
int keepBlankLines,
|
||||
@NotNull DependentSpacingRule rule);
|
||||
|
||||
@NotNull
|
||||
Spacing createSafeSpacing(boolean keepLineBreaks,
|
||||
int keepBlankLines);
|
||||
|
||||
@NotNull
|
||||
Spacing createKeepingFirstColumnSpacing(final int minSpaces,
|
||||
final int maxSpaces,
|
||||
final boolean keepLineBreaks,
|
||||
final int keepBlankLines);
|
||||
|
||||
@NotNull
|
||||
Spacing createSpacing(final int minSpaces, final int maxSpaces, final int minLineFeeds, final boolean keepLineBreaks,
|
||||
final int keepBlankLines, final int prefLineFeeds);
|
||||
}
|
||||
|
||||
@@ -1,339 +1,339 @@
|
||||
/*
|
||||
* Copyright 2000-2009 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.patterns;
|
||||
|
||||
import com.intellij.lang.ASTNode;
|
||||
import com.intellij.lang.Language;
|
||||
import com.intellij.openapi.util.TextRange;
|
||||
import com.intellij.openapi.vfs.VirtualFile;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.meta.PsiMetaData;
|
||||
import com.intellij.psi.meta.PsiMetaOwner;
|
||||
import com.intellij.psi.tree.IElementType;
|
||||
import com.intellij.psi.tree.TokenSet;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.util.PairProcessor;
|
||||
import com.intellij.util.ProcessingContext;
|
||||
import com.intellij.util.ReflectionCache;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import static com.intellij.patterns.PlatformPatterns.psiElement;
|
||||
import static com.intellij.patterns.StandardPatterns.collection;
|
||||
import static com.intellij.patterns.StandardPatterns.not;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public abstract class PsiElementPattern<T extends PsiElement,Self extends PsiElementPattern<T,Self>> extends TreeElementPattern<PsiElement,T,Self> {
|
||||
protected PsiElementPattern(final Class<T> aClass) {
|
||||
super(aClass);
|
||||
}
|
||||
|
||||
protected PsiElementPattern(@NotNull final InitialPatternCondition<T> condition) {
|
||||
super(condition);
|
||||
}
|
||||
|
||||
protected PsiElement[] getChildren(@NotNull final PsiElement element) {
|
||||
return element.getChildren();
|
||||
}
|
||||
|
||||
protected PsiElement getParent(@NotNull final PsiElement element) {
|
||||
return element.getContext();
|
||||
}
|
||||
|
||||
public Self withElementType(IElementType type) {
|
||||
return withElementType(PlatformPatterns.elementType().equalTo(type));
|
||||
}
|
||||
|
||||
public Self withElementType(TokenSet type) {
|
||||
return withElementType(PlatformPatterns.elementType().tokenSet(type));
|
||||
}
|
||||
|
||||
public Self afterLeaf(@NotNull final String... withText) {
|
||||
return afterLeaf(psiElement().withText(PlatformPatterns.string().oneOf(withText)));
|
||||
}
|
||||
|
||||
public Self afterLeaf(@NotNull final ElementPattern<? extends PsiElement> pattern) {
|
||||
return afterLeafSkipping(psiElement().whitespaceCommentEmptyOrError(), pattern);
|
||||
}
|
||||
|
||||
public Self beforeLeaf(@NotNull final ElementPattern<? extends PsiElement> pattern) {
|
||||
return beforeLeafSkipping(psiElement().whitespaceCommentEmptyOrError(), pattern);
|
||||
}
|
||||
|
||||
public Self whitespace() {
|
||||
return withElementType(TokenType.WHITE_SPACE);
|
||||
}
|
||||
|
||||
public Self whitespaceCommentOrError() {
|
||||
return andOr(psiElement().whitespace(), psiElement(PsiComment.class), psiElement(PsiErrorElement.class));
|
||||
}
|
||||
|
||||
public Self whitespaceCommentEmptyOrError() {
|
||||
return andOr(psiElement().whitespace(), psiElement(PsiComment.class), psiElement(PsiErrorElement.class), psiElement().withText(""));
|
||||
}
|
||||
|
||||
public Self withFirstNonWhitespaceChild(@NotNull final ElementPattern<? extends PsiElement> pattern) {
|
||||
return withChildren(collection(PsiElement.class).filter(not(psiElement().whitespace()), collection(PsiElement.class).first(pattern)));
|
||||
}
|
||||
|
||||
public Self withReference(final Class<? extends PsiReference> referenceClass) {
|
||||
return with(new PatternCondition<T>("withReference") {
|
||||
@Override
|
||||
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
|
||||
for (final PsiReference reference : t.getReferences()) {
|
||||
if (ReflectionCache.isInstance(reference, referenceClass)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self inFile(@NotNull final ElementPattern<? extends PsiFile> filePattern) {
|
||||
return with(new PatternCondition<T>("inFile") {
|
||||
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
|
||||
return filePattern.accepts(t.getContainingFile(), context);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self inVirtualFile(@NotNull final ElementPattern<? extends VirtualFile> filePattern) {
|
||||
return with(new PatternCondition<T>("inVirtualFile") {
|
||||
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
|
||||
return filePattern.accepts(t.getContainingFile().getViewProvider().getVirtualFile(), context);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self equalTo(@NotNull final T o) {
|
||||
return with(new PatternCondition<T>("equalTo") {
|
||||
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
|
||||
return t.getManager().areElementsEquivalent(t, o);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
public Self withElementType(final ElementPattern<IElementType> pattern) {
|
||||
return with(new PatternCondition<T>("withElementType") {
|
||||
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
|
||||
final ASTNode node = t.getNode();
|
||||
return node != null && pattern.accepts(node.getElementType());
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
public Self withText(@NotNull @NonNls final String text) {
|
||||
return withText(StandardPatterns.string().equalTo(text));
|
||||
}
|
||||
|
||||
public Self withoutText(@NotNull final String text) {
|
||||
return withoutText(StandardPatterns.string().equalTo(text));
|
||||
}
|
||||
|
||||
public Self withName(@NotNull @NonNls final String name) {
|
||||
return withName(StandardPatterns.string().equalTo(name));
|
||||
}
|
||||
|
||||
public Self withName(@NotNull final ElementPattern<String> name) {
|
||||
return with(new PsiNamePatternCondition<T>("withName", name));
|
||||
}
|
||||
|
||||
public Self afterLeafSkipping(@NotNull final ElementPattern skip, @NotNull final ElementPattern pattern) {
|
||||
return with(new PatternCondition<T>("afterLeafSkipping") {
|
||||
public boolean accepts(@NotNull T t, final ProcessingContext context) {
|
||||
PsiElement element = t;
|
||||
while (true) {
|
||||
element = PsiTreeUtil.prevLeaf(element);
|
||||
if (element != null && element.getTextLength() == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!skip.getCondition().accepts(element, context)) {
|
||||
return pattern.getCondition().accepts(element, context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
public Self beforeLeafSkipping(@NotNull final ElementPattern skip, @NotNull final ElementPattern pattern) {
|
||||
return with(new PatternCondition<T>("beforeLeafSkipping") {
|
||||
public boolean accepts(@NotNull T t, final ProcessingContext context) {
|
||||
PsiElement element = t;
|
||||
while (true) {
|
||||
element = PsiTreeUtil.nextLeaf(element);
|
||||
if (element != null && element.getTextLength() == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!skip.getCondition().accepts(element, context)) {
|
||||
return pattern.getCondition().accepts(element, context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
public Self atStartOf(@NotNull final ElementPattern pattern) {
|
||||
return with(new PatternCondition<T>("atStartOf") {
|
||||
public boolean accepts(@NotNull T t, final ProcessingContext context) {
|
||||
PsiElement element = t;
|
||||
while (element != null) {
|
||||
if (pattern.getCondition().accepts(element, context)) {
|
||||
return element.getTextRange().getStartOffset() == t.getTextRange().getStartOffset();
|
||||
}
|
||||
element = element.getContext();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self withTextLength(@NotNull final ElementPattern lengthPattern) {
|
||||
return with(new PatternConditionPlus<T, Integer>("withTextLength", lengthPattern) {
|
||||
@Override
|
||||
public boolean processValues(T t,
|
||||
ProcessingContext context,
|
||||
PairProcessor<Integer, ProcessingContext> integerProcessingContextPairProcessor) {
|
||||
return integerProcessingContextPairProcessor.process(t.getTextLength(), context);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self notEmpty() {
|
||||
return withTextLengthLongerThan(0);
|
||||
}
|
||||
|
||||
public Self withTextLengthLongerThan(final int minLength) {
|
||||
return with(new PatternCondition<T>("withTextLengthLongerThan") {
|
||||
@Override
|
||||
public boolean accepts(@NotNull T t, ProcessingContext context) {
|
||||
return t.getTextLength() > minLength;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self withText(@NotNull final ElementPattern text) {
|
||||
return with(_withText(text));
|
||||
}
|
||||
|
||||
private PatternCondition<T> _withText(final ElementPattern pattern) {
|
||||
return new PatternConditionPlus<T, String>("_withText", pattern) {
|
||||
@Override
|
||||
public boolean processValues(T t,
|
||||
ProcessingContext context,
|
||||
PairProcessor<String, ProcessingContext> processor) {
|
||||
return processor.process(t.getText(), context);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public Self withoutText(@NotNull final ElementPattern text) {
|
||||
return without(_withText(text));
|
||||
}
|
||||
|
||||
public Self withLanguage(@NotNull final Language language) {
|
||||
return with(new PatternCondition<T>("withLanguage") {
|
||||
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
|
||||
return t.getLanguage().equals(language);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self withMetaData(final ElementPattern<? extends PsiMetaData> metaDataPattern) {
|
||||
return with(new PatternCondition<T>("withMetaData") {
|
||||
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
|
||||
return t instanceof PsiMetaOwner && metaDataPattern.accepts(((PsiMetaOwner)t).getMetaData(), context);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self referencing(final ElementPattern<? extends PsiElement> targetPattern) {
|
||||
return with(new PatternCondition<T>("referencing") {
|
||||
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
|
||||
final PsiReference[] references = t.getReferences();
|
||||
for (final PsiReference reference : references) {
|
||||
if (targetPattern.accepts(reference.resolve(), context)) return true;
|
||||
if (reference instanceof PsiPolyVariantReference) {
|
||||
for (final ResolveResult result : ((PsiPolyVariantReference)reference).multiResolve(true)) {
|
||||
if (targetPattern.accepts(result.getElement(), context)) return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self compiled() {
|
||||
return with(new PatternCondition<T>("compiled") {
|
||||
@Override
|
||||
public boolean accepts(@NotNull T t, ProcessingContext context) {
|
||||
return t instanceof PsiCompiledElement;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self withTreeParent(final ElementPattern<? extends PsiElement> ancestor) {
|
||||
return with(new PatternCondition<T>("withTreeParent") {
|
||||
@Override
|
||||
public boolean accepts(@NotNull T t, ProcessingContext context) {
|
||||
return ancestor.accepts(t.getParent(), context);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self insideStarting(final ElementPattern<? extends PsiElement> ancestor) {
|
||||
return with(new PatternCondition<PsiElement>("insideStarting") {
|
||||
@Override
|
||||
public boolean accepts(@NotNull PsiElement start, ProcessingContext context) {
|
||||
PsiElement element = getParent(start);
|
||||
TextRange range = start.getTextRange();
|
||||
if (range == null) return false;
|
||||
|
||||
int startOffset = range.getStartOffset();
|
||||
while (element != null && element.getTextRange() != null && element.getTextRange().getStartOffset() == startOffset) {
|
||||
if (ancestor.accepts(element, context)) {
|
||||
return true;
|
||||
}
|
||||
element = getParent(element);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static class Capture<T extends PsiElement> extends PsiElementPattern<T,Capture<T>> {
|
||||
|
||||
protected Capture(final Class<T> aClass) {
|
||||
super(aClass);
|
||||
}
|
||||
|
||||
protected Capture(@NotNull final InitialPatternCondition<T> condition) {
|
||||
super(condition);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 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.patterns;
|
||||
|
||||
import com.intellij.lang.ASTNode;
|
||||
import com.intellij.lang.Language;
|
||||
import com.intellij.openapi.util.TextRange;
|
||||
import com.intellij.openapi.vfs.VirtualFile;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.meta.PsiMetaData;
|
||||
import com.intellij.psi.meta.PsiMetaOwner;
|
||||
import com.intellij.psi.tree.IElementType;
|
||||
import com.intellij.psi.tree.TokenSet;
|
||||
import com.intellij.psi.util.PsiTreeUtil;
|
||||
import com.intellij.util.PairProcessor;
|
||||
import com.intellij.util.ProcessingContext;
|
||||
import com.intellij.util.ReflectionCache;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import static com.intellij.patterns.PlatformPatterns.psiElement;
|
||||
import static com.intellij.patterns.StandardPatterns.collection;
|
||||
import static com.intellij.patterns.StandardPatterns.not;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public abstract class PsiElementPattern<T extends PsiElement,Self extends PsiElementPattern<T,Self>> extends TreeElementPattern<PsiElement,T,Self> {
|
||||
protected PsiElementPattern(final Class<T> aClass) {
|
||||
super(aClass);
|
||||
}
|
||||
|
||||
protected PsiElementPattern(@NotNull final InitialPatternCondition<T> condition) {
|
||||
super(condition);
|
||||
}
|
||||
|
||||
protected PsiElement[] getChildren(@NotNull final PsiElement element) {
|
||||
return element.getChildren();
|
||||
}
|
||||
|
||||
protected PsiElement getParent(@NotNull final PsiElement element) {
|
||||
return element.getContext();
|
||||
}
|
||||
|
||||
public Self withElementType(IElementType type) {
|
||||
return withElementType(PlatformPatterns.elementType().equalTo(type));
|
||||
}
|
||||
|
||||
public Self withElementType(TokenSet type) {
|
||||
return withElementType(PlatformPatterns.elementType().tokenSet(type));
|
||||
}
|
||||
|
||||
public Self afterLeaf(@NotNull final String... withText) {
|
||||
return afterLeaf(psiElement().withText(PlatformPatterns.string().oneOf(withText)));
|
||||
}
|
||||
|
||||
public Self afterLeaf(@NotNull final ElementPattern<? extends PsiElement> pattern) {
|
||||
return afterLeafSkipping(psiElement().whitespaceCommentEmptyOrError(), pattern);
|
||||
}
|
||||
|
||||
public Self beforeLeaf(@NotNull final ElementPattern<? extends PsiElement> pattern) {
|
||||
return beforeLeafSkipping(psiElement().whitespaceCommentEmptyOrError(), pattern);
|
||||
}
|
||||
|
||||
public Self whitespace() {
|
||||
return withElementType(TokenType.WHITE_SPACE);
|
||||
}
|
||||
|
||||
public Self whitespaceCommentOrError() {
|
||||
return andOr(psiElement().whitespace(), psiElement(PsiComment.class), psiElement(PsiErrorElement.class));
|
||||
}
|
||||
|
||||
public Self whitespaceCommentEmptyOrError() {
|
||||
return andOr(psiElement().whitespace(), psiElement(PsiComment.class), psiElement(PsiErrorElement.class), psiElement().withText(""));
|
||||
}
|
||||
|
||||
public Self withFirstNonWhitespaceChild(@NotNull final ElementPattern<? extends PsiElement> pattern) {
|
||||
return withChildren(collection(PsiElement.class).filter(not(psiElement().whitespace()), collection(PsiElement.class).first(pattern)));
|
||||
}
|
||||
|
||||
public Self withReference(final Class<? extends PsiReference> referenceClass) {
|
||||
return with(new PatternCondition<T>("withReference") {
|
||||
@Override
|
||||
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
|
||||
for (final PsiReference reference : t.getReferences()) {
|
||||
if (ReflectionCache.isInstance(reference, referenceClass)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self inFile(@NotNull final ElementPattern<? extends PsiFile> filePattern) {
|
||||
return with(new PatternCondition<T>("inFile") {
|
||||
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
|
||||
return filePattern.accepts(t.getContainingFile(), context);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self inVirtualFile(@NotNull final ElementPattern<? extends VirtualFile> filePattern) {
|
||||
return with(new PatternCondition<T>("inVirtualFile") {
|
||||
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
|
||||
return filePattern.accepts(t.getContainingFile().getViewProvider().getVirtualFile(), context);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self equalTo(@NotNull final T o) {
|
||||
return with(new PatternCondition<T>("equalTo") {
|
||||
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
|
||||
return t.getManager().areElementsEquivalent(t, o);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
public Self withElementType(final ElementPattern<IElementType> pattern) {
|
||||
return with(new PatternCondition<T>("withElementType") {
|
||||
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
|
||||
final ASTNode node = t.getNode();
|
||||
return node != null && pattern.accepts(node.getElementType());
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
public Self withText(@NotNull @NonNls final String text) {
|
||||
return withText(StandardPatterns.string().equalTo(text));
|
||||
}
|
||||
|
||||
public Self withoutText(@NotNull final String text) {
|
||||
return withoutText(StandardPatterns.string().equalTo(text));
|
||||
}
|
||||
|
||||
public Self withName(@NotNull @NonNls final String name) {
|
||||
return withName(StandardPatterns.string().equalTo(name));
|
||||
}
|
||||
|
||||
public Self withName(@NotNull final ElementPattern<String> name) {
|
||||
return with(new PsiNamePatternCondition<T>("withName", name));
|
||||
}
|
||||
|
||||
public Self afterLeafSkipping(@NotNull final ElementPattern skip, @NotNull final ElementPattern pattern) {
|
||||
return with(new PatternCondition<T>("afterLeafSkipping") {
|
||||
public boolean accepts(@NotNull T t, final ProcessingContext context) {
|
||||
PsiElement element = t;
|
||||
while (true) {
|
||||
element = PsiTreeUtil.prevLeaf(element);
|
||||
if (element != null && element.getTextLength() == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!skip.getCondition().accepts(element, context)) {
|
||||
return pattern.getCondition().accepts(element, context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
public Self beforeLeafSkipping(@NotNull final ElementPattern skip, @NotNull final ElementPattern pattern) {
|
||||
return with(new PatternCondition<T>("beforeLeafSkipping") {
|
||||
public boolean accepts(@NotNull T t, final ProcessingContext context) {
|
||||
PsiElement element = t;
|
||||
while (true) {
|
||||
element = PsiTreeUtil.nextLeaf(element);
|
||||
if (element != null && element.getTextLength() == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!skip.getCondition().accepts(element, context)) {
|
||||
return pattern.getCondition().accepts(element, context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
public Self atStartOf(@NotNull final ElementPattern pattern) {
|
||||
return with(new PatternCondition<T>("atStartOf") {
|
||||
public boolean accepts(@NotNull T t, final ProcessingContext context) {
|
||||
PsiElement element = t;
|
||||
while (element != null) {
|
||||
if (pattern.getCondition().accepts(element, context)) {
|
||||
return element.getTextRange().getStartOffset() == t.getTextRange().getStartOffset();
|
||||
}
|
||||
element = element.getContext();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self withTextLength(@NotNull final ElementPattern lengthPattern) {
|
||||
return with(new PatternConditionPlus<T, Integer>("withTextLength", lengthPattern) {
|
||||
@Override
|
||||
public boolean processValues(T t,
|
||||
ProcessingContext context,
|
||||
PairProcessor<Integer, ProcessingContext> integerProcessingContextPairProcessor) {
|
||||
return integerProcessingContextPairProcessor.process(t.getTextLength(), context);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self notEmpty() {
|
||||
return withTextLengthLongerThan(0);
|
||||
}
|
||||
|
||||
public Self withTextLengthLongerThan(final int minLength) {
|
||||
return with(new PatternCondition<T>("withTextLengthLongerThan") {
|
||||
@Override
|
||||
public boolean accepts(@NotNull T t, ProcessingContext context) {
|
||||
return t.getTextLength() > minLength;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self withText(@NotNull final ElementPattern text) {
|
||||
return with(_withText(text));
|
||||
}
|
||||
|
||||
private PatternCondition<T> _withText(final ElementPattern pattern) {
|
||||
return new PatternConditionPlus<T, String>("_withText", pattern) {
|
||||
@Override
|
||||
public boolean processValues(T t,
|
||||
ProcessingContext context,
|
||||
PairProcessor<String, ProcessingContext> processor) {
|
||||
return processor.process(t.getText(), context);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public Self withoutText(@NotNull final ElementPattern text) {
|
||||
return without(_withText(text));
|
||||
}
|
||||
|
||||
public Self withLanguage(@NotNull final Language language) {
|
||||
return with(new PatternCondition<T>("withLanguage") {
|
||||
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
|
||||
return t.getLanguage().equals(language);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self withMetaData(final ElementPattern<? extends PsiMetaData> metaDataPattern) {
|
||||
return with(new PatternCondition<T>("withMetaData") {
|
||||
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
|
||||
return t instanceof PsiMetaOwner && metaDataPattern.accepts(((PsiMetaOwner)t).getMetaData(), context);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self referencing(final ElementPattern<? extends PsiElement> targetPattern) {
|
||||
return with(new PatternCondition<T>("referencing") {
|
||||
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
|
||||
final PsiReference[] references = t.getReferences();
|
||||
for (final PsiReference reference : references) {
|
||||
if (targetPattern.accepts(reference.resolve(), context)) return true;
|
||||
if (reference instanceof PsiPolyVariantReference) {
|
||||
for (final ResolveResult result : ((PsiPolyVariantReference)reference).multiResolve(true)) {
|
||||
if (targetPattern.accepts(result.getElement(), context)) return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self compiled() {
|
||||
return with(new PatternCondition<T>("compiled") {
|
||||
@Override
|
||||
public boolean accepts(@NotNull T t, ProcessingContext context) {
|
||||
return t instanceof PsiCompiledElement;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self withTreeParent(final ElementPattern<? extends PsiElement> ancestor) {
|
||||
return with(new PatternCondition<T>("withTreeParent") {
|
||||
@Override
|
||||
public boolean accepts(@NotNull T t, ProcessingContext context) {
|
||||
return ancestor.accepts(t.getParent(), context);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Self insideStarting(final ElementPattern<? extends PsiElement> ancestor) {
|
||||
return with(new PatternCondition<PsiElement>("insideStarting") {
|
||||
@Override
|
||||
public boolean accepts(@NotNull PsiElement start, ProcessingContext context) {
|
||||
PsiElement element = getParent(start);
|
||||
TextRange range = start.getTextRange();
|
||||
if (range == null) return false;
|
||||
|
||||
int startOffset = range.getStartOffset();
|
||||
while (element != null && element.getTextRange() != null && element.getTextRange().getStartOffset() == startOffset) {
|
||||
if (ancestor.accepts(element, context)) {
|
||||
return true;
|
||||
}
|
||||
element = getParent(element);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static class Capture<T extends PsiElement> extends PsiElementPattern<T,Capture<T>> {
|
||||
|
||||
protected Capture(final Class<T> aClass) {
|
||||
super(aClass);
|
||||
}
|
||||
|
||||
protected Capture(@NotNull final InitialPatternCondition<T> condition) {
|
||||
super(condition);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,235 +1,235 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.application.options.CodeCompletionPanel">
|
||||
<grid id="8765f" binding="myPanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
|
||||
<margin top="0" left="0" bottom="0" right="0"/>
|
||||
<constraints>
|
||||
<xy x="17" y="22" width="559" height="563"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<enabled value="true"/>
|
||||
</properties>
|
||||
<border type="none"/>
|
||||
<children>
|
||||
<grid id="be0ff" layout-manager="GridLayoutManager" row-count="2" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
|
||||
<margin top="0" left="0" bottom="0" right="0"/>
|
||||
<constraints>
|
||||
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="9" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties/>
|
||||
<border type="none"/>
|
||||
<children>
|
||||
<grid id="7f988" layout-manager="GridLayoutManager" row-count="11" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
|
||||
<margin top="0" left="0" bottom="0" right="0"/>
|
||||
<constraints>
|
||||
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties/>
|
||||
<clientProperties>
|
||||
<BorderFactoryClass class="java.lang.String" value="com.intellij.ui.IdeBorderFactory$PlainSmallWithIndent"/>
|
||||
<html.disable class="java.lang.Boolean" value="false"/>
|
||||
</clientProperties>
|
||||
<border type="none" title-resource-bundle="messages/ApplicationBundle" title-key="title.code.completion"/>
|
||||
<children>
|
||||
<component id="85153" class="javax.swing.JLabel">
|
||||
<constraints>
|
||||
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="combobox.case.sensitive.completion"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="9c981" class="javax.swing.JCheckBox" binding="myCbOnCodeCompletion">
|
||||
<constraints>
|
||||
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<margin top="2" left="2" bottom="2" right="2"/>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="checkbox.autocomplete.basic"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="8276c" class="javax.swing.JCheckBox" binding="myCbOnSmartTypeCompletion">
|
||||
<constraints>
|
||||
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<margin top="2" left="2" bottom="2" right="2"/>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="checkbox.autocomplete.smart.type"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="6141" class="javax.swing.JCheckBox" binding="myCbAutocompleteCommonPrefix">
|
||||
<constraints>
|
||||
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="9" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<margin top="2" left="2" bottom="2" right="2"/>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="checkbox.autocomplete.common.prefix"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="8063c" class="javax.swing.JCheckBox" binding="myCbSorting">
|
||||
<constraints>
|
||||
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="9" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<margin top="2" left="2" bottom="2" right="2"/>
|
||||
<text value="Sort lookup items lexicographically"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="beda2" class="javax.swing.JCheckBox" binding="myCbShowStaticAfterInstance">
|
||||
<constraints>
|
||||
<grid row="6" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="9" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<margin top="2" left="2" bottom="12" right="2"/>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="checkbox.show.static.members.after.instance.qualifier"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="fccaa" class="javax.swing.JComboBox" binding="myCaseSensitiveCombo">
|
||||
<constraints>
|
||||
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="2" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties/>
|
||||
</component>
|
||||
<component id="51007" class="javax.swing.JLabel">
|
||||
<constraints>
|
||||
<grid row="1" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="label.autocomplete.when.only.one.choice"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="59c92" class="javax.swing.JCheckBox" binding="myCbAutocompletion">
|
||||
<constraints>
|
||||
<grid row="7" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<margin top="2" left="2" bottom="2" right="2"/>
|
||||
<text value="Autopopup code completion in (ms):"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="28a18" class="javax.swing.JTextField" binding="myAutocompletionDelayField">
|
||||
<constraints>
|
||||
<grid row="7" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="0" indent="0" use-parent-layout="false">
|
||||
<minimum-size width="50" height="-1"/>
|
||||
<preferred-size width="144" height="28"/>
|
||||
<maximum-size width="50" height="-1"/>
|
||||
</grid>
|
||||
</constraints>
|
||||
<properties>
|
||||
<columns value="4"/>
|
||||
<text value="0"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="ae843" class="javax.swing.JLabel">
|
||||
<constraints>
|
||||
<grid row="8" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="9" fill="0" indent="2" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<iconTextGap value="4"/>
|
||||
<inheritsPopupMenu value="true"/>
|
||||
<text value="Preselect the first suggestion:"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="6cbc" class="javax.swing.JComboBox" binding="myFocusLookup">
|
||||
<constraints>
|
||||
<grid row="8" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="2" anchor="9" fill="1" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties/>
|
||||
</component>
|
||||
<component id="a1f3b" class="javax.swing.JTextField" binding="myAutopopupJavaDocField">
|
||||
<constraints>
|
||||
<grid row="10" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="9" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<columns value="4"/>
|
||||
<text value="1000"/>
|
||||
</properties>
|
||||
</component>
|
||||
<grid id="f8961" layout-manager="GridLayoutManager" row-count="2" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="0">
|
||||
<margin top="0" left="0" bottom="0" right="0"/>
|
||||
<constraints>
|
||||
<grid row="10" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties/>
|
||||
<border type="none"/>
|
||||
<children>
|
||||
<component id="749a1" class="javax.swing.JCheckBox" binding="myCbAutopopupJavaDoc">
|
||||
<constraints>
|
||||
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<margin top="2" left="2" bottom="0" right="2"/>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="editbox.autopopup.javadoc.in.ms"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="b0975" class="com.intellij.ui.components.JBLabel">
|
||||
<constraints>
|
||||
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="9" fill="0" indent="2" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<componentStyle value="SMALL"/>
|
||||
<enabled value="true"/>
|
||||
<fontColor value="BRIGHTER"/>
|
||||
<text value="For explicitly invoked completion"/>
|
||||
</properties>
|
||||
</component>
|
||||
</children>
|
||||
</grid>
|
||||
<grid id="6f2d3" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
|
||||
<margin top="0" left="0" bottom="0" right="0"/>
|
||||
<constraints>
|
||||
<grid row="9" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="3" indent="0" use-parent-layout="false">
|
||||
<minimum-size width="-1" height="4"/>
|
||||
</grid>
|
||||
</constraints>
|
||||
<properties/>
|
||||
<border type="none"/>
|
||||
<children/>
|
||||
</grid>
|
||||
</children>
|
||||
</grid>
|
||||
<grid id="8dae3" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
|
||||
<margin top="0" left="0" bottom="0" right="0"/>
|
||||
<constraints>
|
||||
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties/>
|
||||
<clientProperties>
|
||||
<BorderFactoryClass class="java.lang.String" value="com.intellij.ui.IdeBorderFactory$PlainSmallWithIndent"/>
|
||||
</clientProperties>
|
||||
<border type="none" title-resource-bundle="messages/ApplicationBundle" title-key="title.parameter.info"/>
|
||||
<children>
|
||||
<component id="c7fb5" class="javax.swing.JCheckBox" binding="myCbParameterInfoPopup">
|
||||
<constraints>
|
||||
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="editbox.autopopup.in.ms"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="ceaee" class="javax.swing.JCheckBox" binding="myCbShowFullParameterSignatures">
|
||||
<constraints>
|
||||
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="checkbox.show.full.signatures"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="8ad96" class="javax.swing.JTextField" binding="myParameterInfoDelayField">
|
||||
<constraints>
|
||||
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="0" indent="0" use-parent-layout="false">
|
||||
<minimum-size width="50" height="-1"/>
|
||||
<maximum-size width="50" height="-1"/>
|
||||
</grid>
|
||||
</constraints>
|
||||
<properties>
|
||||
<columns value="4"/>
|
||||
<text value="1000"/>
|
||||
</properties>
|
||||
</component>
|
||||
</children>
|
||||
</grid>
|
||||
</children>
|
||||
</grid>
|
||||
</children>
|
||||
</grid>
|
||||
</form>
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.application.options.CodeCompletionPanel">
|
||||
<grid id="8765f" binding="myPanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
|
||||
<margin top="0" left="0" bottom="0" right="0"/>
|
||||
<constraints>
|
||||
<xy x="17" y="22" width="559" height="563"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<enabled value="true"/>
|
||||
</properties>
|
||||
<border type="none"/>
|
||||
<children>
|
||||
<grid id="be0ff" layout-manager="GridLayoutManager" row-count="2" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
|
||||
<margin top="0" left="0" bottom="0" right="0"/>
|
||||
<constraints>
|
||||
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="9" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties/>
|
||||
<border type="none"/>
|
||||
<children>
|
||||
<grid id="7f988" layout-manager="GridLayoutManager" row-count="11" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
|
||||
<margin top="0" left="0" bottom="0" right="0"/>
|
||||
<constraints>
|
||||
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties/>
|
||||
<clientProperties>
|
||||
<BorderFactoryClass class="java.lang.String" value="com.intellij.ui.IdeBorderFactory$PlainSmallWithIndent"/>
|
||||
<html.disable class="java.lang.Boolean" value="false"/>
|
||||
</clientProperties>
|
||||
<border type="none" title-resource-bundle="messages/ApplicationBundle" title-key="title.code.completion"/>
|
||||
<children>
|
||||
<component id="85153" class="javax.swing.JLabel">
|
||||
<constraints>
|
||||
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="combobox.case.sensitive.completion"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="9c981" class="javax.swing.JCheckBox" binding="myCbOnCodeCompletion">
|
||||
<constraints>
|
||||
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<margin top="2" left="2" bottom="2" right="2"/>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="checkbox.autocomplete.basic"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="8276c" class="javax.swing.JCheckBox" binding="myCbOnSmartTypeCompletion">
|
||||
<constraints>
|
||||
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<margin top="2" left="2" bottom="2" right="2"/>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="checkbox.autocomplete.smart.type"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="6141" class="javax.swing.JCheckBox" binding="myCbAutocompleteCommonPrefix">
|
||||
<constraints>
|
||||
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="9" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<margin top="2" left="2" bottom="2" right="2"/>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="checkbox.autocomplete.common.prefix"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="8063c" class="javax.swing.JCheckBox" binding="myCbSorting">
|
||||
<constraints>
|
||||
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="9" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<margin top="2" left="2" bottom="2" right="2"/>
|
||||
<text value="Sort lookup items lexicographically"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="beda2" class="javax.swing.JCheckBox" binding="myCbShowStaticAfterInstance">
|
||||
<constraints>
|
||||
<grid row="6" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="9" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<margin top="2" left="2" bottom="12" right="2"/>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="checkbox.show.static.members.after.instance.qualifier"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="fccaa" class="javax.swing.JComboBox" binding="myCaseSensitiveCombo">
|
||||
<constraints>
|
||||
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="2" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties/>
|
||||
</component>
|
||||
<component id="51007" class="javax.swing.JLabel">
|
||||
<constraints>
|
||||
<grid row="1" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="label.autocomplete.when.only.one.choice"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="59c92" class="javax.swing.JCheckBox" binding="myCbAutocompletion">
|
||||
<constraints>
|
||||
<grid row="7" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<margin top="2" left="2" bottom="2" right="2"/>
|
||||
<text value="Autopopup code completion in (ms):"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="28a18" class="javax.swing.JTextField" binding="myAutocompletionDelayField">
|
||||
<constraints>
|
||||
<grid row="7" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="0" indent="0" use-parent-layout="false">
|
||||
<minimum-size width="50" height="-1"/>
|
||||
<preferred-size width="144" height="28"/>
|
||||
<maximum-size width="50" height="-1"/>
|
||||
</grid>
|
||||
</constraints>
|
||||
<properties>
|
||||
<columns value="4"/>
|
||||
<text value="0"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="ae843" class="javax.swing.JLabel">
|
||||
<constraints>
|
||||
<grid row="8" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="9" fill="0" indent="2" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<iconTextGap value="4"/>
|
||||
<inheritsPopupMenu value="true"/>
|
||||
<text value="Preselect the first suggestion:"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="6cbc" class="javax.swing.JComboBox" binding="myFocusLookup">
|
||||
<constraints>
|
||||
<grid row="8" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="2" anchor="9" fill="1" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties/>
|
||||
</component>
|
||||
<component id="a1f3b" class="javax.swing.JTextField" binding="myAutopopupJavaDocField">
|
||||
<constraints>
|
||||
<grid row="10" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="9" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<columns value="4"/>
|
||||
<text value="1000"/>
|
||||
</properties>
|
||||
</component>
|
||||
<grid id="f8961" layout-manager="GridLayoutManager" row-count="2" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="0">
|
||||
<margin top="0" left="0" bottom="0" right="0"/>
|
||||
<constraints>
|
||||
<grid row="10" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties/>
|
||||
<border type="none"/>
|
||||
<children>
|
||||
<component id="749a1" class="javax.swing.JCheckBox" binding="myCbAutopopupJavaDoc">
|
||||
<constraints>
|
||||
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<margin top="2" left="2" bottom="0" right="2"/>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="editbox.autopopup.javadoc.in.ms"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="b0975" class="com.intellij.ui.components.JBLabel">
|
||||
<constraints>
|
||||
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="9" fill="0" indent="2" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<componentStyle value="SMALL"/>
|
||||
<enabled value="true"/>
|
||||
<fontColor value="BRIGHTER"/>
|
||||
<text value="For explicitly invoked completion"/>
|
||||
</properties>
|
||||
</component>
|
||||
</children>
|
||||
</grid>
|
||||
<grid id="6f2d3" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
|
||||
<margin top="0" left="0" bottom="0" right="0"/>
|
||||
<constraints>
|
||||
<grid row="9" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="3" indent="0" use-parent-layout="false">
|
||||
<minimum-size width="-1" height="4"/>
|
||||
</grid>
|
||||
</constraints>
|
||||
<properties/>
|
||||
<border type="none"/>
|
||||
<children/>
|
||||
</grid>
|
||||
</children>
|
||||
</grid>
|
||||
<grid id="8dae3" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
|
||||
<margin top="0" left="0" bottom="0" right="0"/>
|
||||
<constraints>
|
||||
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties/>
|
||||
<clientProperties>
|
||||
<BorderFactoryClass class="java.lang.String" value="com.intellij.ui.IdeBorderFactory$PlainSmallWithIndent"/>
|
||||
</clientProperties>
|
||||
<border type="none" title-resource-bundle="messages/ApplicationBundle" title-key="title.parameter.info"/>
|
||||
<children>
|
||||
<component id="c7fb5" class="javax.swing.JCheckBox" binding="myCbParameterInfoPopup">
|
||||
<constraints>
|
||||
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="editbox.autopopup.in.ms"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="ceaee" class="javax.swing.JCheckBox" binding="myCbShowFullParameterSignatures">
|
||||
<constraints>
|
||||
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
|
||||
</constraints>
|
||||
<properties>
|
||||
<text resource-bundle="messages/ApplicationBundle" key="checkbox.show.full.signatures"/>
|
||||
</properties>
|
||||
</component>
|
||||
<component id="8ad96" class="javax.swing.JTextField" binding="myParameterInfoDelayField">
|
||||
<constraints>
|
||||
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="0" indent="0" use-parent-layout="false">
|
||||
<minimum-size width="50" height="-1"/>
|
||||
<maximum-size width="50" height="-1"/>
|
||||
</grid>
|
||||
</constraints>
|
||||
<properties>
|
||||
<columns value="4"/>
|
||||
<text value="1000"/>
|
||||
</properties>
|
||||
</component>
|
||||
</children>
|
||||
</grid>
|
||||
</children>
|
||||
</grid>
|
||||
</children>
|
||||
</grid>
|
||||
</form>
|
||||
|
||||
+236
-236
@@ -1,237 +1,237 @@
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.intellij.application.options;
|
||||
|
||||
import com.intellij.codeInsight.CodeInsightSettings;
|
||||
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
|
||||
import com.intellij.ide.DataManager;
|
||||
import com.intellij.ide.ui.UISettings;
|
||||
import com.intellij.openapi.actionSystem.PlatformDataKeys;
|
||||
import com.intellij.openapi.application.ApplicationBundle;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import org.intellij.lang.annotations.MagicConstant;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.awt.event.ActionEvent;
|
||||
import java.awt.event.ActionListener;
|
||||
|
||||
public class CodeCompletionPanel {
|
||||
JPanel myPanel;
|
||||
private JCheckBox myCbAutocompletion;
|
||||
private JTextField myAutocompletionDelayField;
|
||||
private JCheckBox myCbAutopopupJavaDoc;
|
||||
private JTextField myAutopopupJavaDocField;
|
||||
private JCheckBox myCbAutocompleteCommonPrefix;
|
||||
private JCheckBox myCbShowStaticAfterInstance;
|
||||
|
||||
private JCheckBox myCbOnCodeCompletion;
|
||||
private JCheckBox myCbOnSmartTypeCompletion;
|
||||
|
||||
private JCheckBox myCbParameterInfoPopup;
|
||||
private JTextField myParameterInfoDelayField;
|
||||
private JCheckBox myCbShowFullParameterSignatures;
|
||||
|
||||
private JComboBox myCaseSensitiveCombo;
|
||||
private JComboBox myFocusLookup;
|
||||
private JCheckBox myCbSorting;
|
||||
private static final String CASE_SENSITIVE_ALL = ApplicationBundle.message("combobox.autocomplete.case.sensitive.all");
|
||||
private static final String CASE_SENSITIVE_NONE = ApplicationBundle.message("combobox.autocomplete.case.sensitive.none");
|
||||
private static final String CASE_SENSITIVE_FIRST_LETTER = ApplicationBundle.message("combobox.autocomplete.case.sensitive.first.letter");
|
||||
private static final String[] CASE_VARIANTS = {CASE_SENSITIVE_ALL, CASE_SENSITIVE_NONE, CASE_SENSITIVE_FIRST_LETTER};
|
||||
private static final String[] FOCUS_VARIANTS = {"Never", "'Smart'", "Always"};
|
||||
|
||||
public CodeCompletionPanel(){
|
||||
myCaseSensitiveCombo.setModel(new DefaultComboBoxModel(CASE_VARIANTS));
|
||||
myFocusLookup.setModel(new DefaultComboBoxModel(FOCUS_VARIANTS));
|
||||
|
||||
|
||||
myCbAutocompletion.addActionListener(
|
||||
new ActionListener() {
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent event) {
|
||||
myAutocompletionDelayField.setEnabled(myCbAutocompletion.isSelected());
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
myCbAutopopupJavaDoc.addActionListener(
|
||||
new ActionListener() {
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent event) {
|
||||
myAutopopupJavaDocField.setEnabled(myCbAutopopupJavaDoc.isSelected());
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
myCbParameterInfoPopup.addActionListener(
|
||||
new ActionListener() {
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent event) {
|
||||
myParameterInfoDelayField.setEnabled(myCbParameterInfoPopup.isSelected());
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
hideOption(myCbShowStaticAfterInstance, OptionId.COMPLETION_SHOW_STATIC_AFTER_IMPORT);
|
||||
hideOption(myCbOnSmartTypeCompletion, OptionId.COMPLETION_SMART_TYPE);
|
||||
myCbAutocompleteCommonPrefix.setVisible(false);
|
||||
|
||||
reset();
|
||||
}
|
||||
|
||||
private static void hideOption(JComponent component, OptionId id) {
|
||||
component.setVisible(OptionsApplicabilityFilter.isApplicable(id));
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
CodeInsightSettings codeInsightSettings = CodeInsightSettings.getInstance();
|
||||
|
||||
final String value;
|
||||
switch(codeInsightSettings.COMPLETION_CASE_SENSITIVE){
|
||||
case CodeInsightSettings.ALL:
|
||||
value = CASE_SENSITIVE_ALL;
|
||||
break;
|
||||
|
||||
case CodeInsightSettings.NONE:
|
||||
value = CASE_SENSITIVE_NONE;
|
||||
break;
|
||||
|
||||
default:
|
||||
value = CASE_SENSITIVE_FIRST_LETTER;
|
||||
break;
|
||||
}
|
||||
myCaseSensitiveCombo.setSelectedItem(value);
|
||||
|
||||
myFocusLookup.setSelectedIndex(Math.min(Math.max(codeInsightSettings.AUTOPOPUP_FOCUS_POLICY - 1, 0), FOCUS_VARIANTS.length - 1));
|
||||
|
||||
myCbOnCodeCompletion.setSelected(codeInsightSettings.AUTOCOMPLETE_ON_CODE_COMPLETION);
|
||||
myCbOnSmartTypeCompletion.setSelected(codeInsightSettings.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION);
|
||||
myCbAutocompleteCommonPrefix.setSelected(codeInsightSettings.AUTOCOMPLETE_COMMON_PREFIX);
|
||||
myCbShowStaticAfterInstance.setSelected(codeInsightSettings.SHOW_STATIC_AFTER_INSTANCE);
|
||||
|
||||
myCbAutocompletion.setSelected(codeInsightSettings.AUTO_POPUP_COMPLETION_LOOKUP);
|
||||
myAutocompletionDelayField.setEnabled(codeInsightSettings.AUTO_POPUP_COMPLETION_LOOKUP);
|
||||
myAutocompletionDelayField.setText(String.valueOf(codeInsightSettings.AUTO_LOOKUP_DELAY));
|
||||
|
||||
myCbAutopopupJavaDoc.setSelected(codeInsightSettings.AUTO_POPUP_JAVADOC_INFO);
|
||||
myAutopopupJavaDocField.setEnabled(codeInsightSettings.AUTO_POPUP_JAVADOC_INFO);
|
||||
myAutopopupJavaDocField.setText(String.valueOf(codeInsightSettings.JAVADOC_INFO_DELAY));
|
||||
|
||||
myCbParameterInfoPopup.setSelected(codeInsightSettings.AUTO_POPUP_PARAMETER_INFO);
|
||||
myParameterInfoDelayField.setEnabled(codeInsightSettings.AUTO_POPUP_PARAMETER_INFO);
|
||||
myParameterInfoDelayField.setText(String.valueOf(codeInsightSettings.PARAMETER_INFO_DELAY));
|
||||
myCbShowFullParameterSignatures.setSelected(codeInsightSettings.SHOW_FULL_SIGNATURES_IN_PARAMETER_INFO);
|
||||
|
||||
myCbAutocompletion.setSelected(codeInsightSettings.AUTO_POPUP_COMPLETION_LOOKUP);
|
||||
myCbSorting.setSelected(UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY);
|
||||
}
|
||||
|
||||
public void apply() {
|
||||
|
||||
CodeInsightSettings codeInsightSettings = CodeInsightSettings.getInstance();
|
||||
|
||||
codeInsightSettings.COMPLETION_CASE_SENSITIVE = getCaseSensitiveValue();
|
||||
//noinspection MagicConstant
|
||||
codeInsightSettings.AUTOPOPUP_FOCUS_POLICY = getFocusLookupValue();
|
||||
|
||||
codeInsightSettings.AUTOCOMPLETE_ON_CODE_COMPLETION = myCbOnCodeCompletion.isSelected();
|
||||
codeInsightSettings.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION = myCbOnSmartTypeCompletion.isSelected();
|
||||
codeInsightSettings.AUTOCOMPLETE_COMMON_PREFIX = myCbAutocompleteCommonPrefix.isSelected();
|
||||
codeInsightSettings.SHOW_STATIC_AFTER_INSTANCE = myCbShowStaticAfterInstance.isSelected();
|
||||
codeInsightSettings.SHOW_FULL_SIGNATURES_IN_PARAMETER_INFO = myCbShowFullParameterSignatures.isSelected();
|
||||
|
||||
codeInsightSettings.AUTO_POPUP_PARAMETER_INFO = myCbParameterInfoPopup.isSelected();
|
||||
codeInsightSettings.AUTO_POPUP_COMPLETION_LOOKUP = myCbAutocompletion.isSelected();
|
||||
codeInsightSettings.AUTO_POPUP_JAVADOC_INFO = myCbAutopopupJavaDoc.isSelected();
|
||||
|
||||
codeInsightSettings.AUTO_LOOKUP_DELAY = getIntegerValue(myAutocompletionDelayField.getText(), 0);
|
||||
codeInsightSettings.PARAMETER_INFO_DELAY = getIntegerValue(myParameterInfoDelayField.getText(), 0);
|
||||
codeInsightSettings.JAVADOC_INFO_DELAY = getIntegerValue(myAutopopupJavaDocField.getText(), 0);
|
||||
|
||||
UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = myCbSorting.isSelected();
|
||||
|
||||
final Project project = PlatformDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(myPanel));
|
||||
if (project != null){
|
||||
DaemonCodeAnalyzer.getInstance(project).settingsChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isModified() {
|
||||
CodeInsightSettings codeInsightSettings = CodeInsightSettings.getInstance();
|
||||
boolean isModified = false;
|
||||
|
||||
//noinspection ConstantConditions
|
||||
isModified |= getCaseSensitiveValue() != codeInsightSettings.COMPLETION_CASE_SENSITIVE;
|
||||
//noinspection MagicConstant
|
||||
isModified |= getFocusLookupValue() != codeInsightSettings.AUTOPOPUP_FOCUS_POLICY;
|
||||
|
||||
isModified |= isModified(myCbOnCodeCompletion, codeInsightSettings.AUTOCOMPLETE_ON_CODE_COMPLETION);
|
||||
isModified |= isModified(myCbOnSmartTypeCompletion, codeInsightSettings.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION);
|
||||
isModified |= isModified(myCbAutocompleteCommonPrefix, codeInsightSettings.AUTOCOMPLETE_COMMON_PREFIX);
|
||||
isModified |= isModified(myCbShowStaticAfterInstance, codeInsightSettings.SHOW_STATIC_AFTER_INSTANCE);
|
||||
isModified |= isModified(myCbShowFullParameterSignatures, codeInsightSettings.SHOW_FULL_SIGNATURES_IN_PARAMETER_INFO);
|
||||
isModified |= isModified(myCbParameterInfoPopup, codeInsightSettings.AUTO_POPUP_PARAMETER_INFO);
|
||||
isModified |= isModified(myCbAutocompletion, codeInsightSettings.AUTO_POPUP_COMPLETION_LOOKUP);
|
||||
|
||||
isModified |= isModified(myCbAutopopupJavaDoc, codeInsightSettings.AUTO_POPUP_JAVADOC_INFO);
|
||||
isModified |= isModified(myAutocompletionDelayField, codeInsightSettings.AUTO_LOOKUP_DELAY, 0);
|
||||
isModified |= isModified(myParameterInfoDelayField, codeInsightSettings.PARAMETER_INFO_DELAY, 0);
|
||||
isModified |= isModified(myAutopopupJavaDocField, codeInsightSettings.JAVADOC_INFO_DELAY, 0);
|
||||
isModified |= isModified(myCbSorting, UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY);
|
||||
|
||||
return isModified;
|
||||
}
|
||||
|
||||
private static boolean isModified(JCheckBox checkBox, boolean value) {
|
||||
return checkBox.isSelected() != value;
|
||||
}
|
||||
|
||||
private static boolean isModified(JTextField textField, int value, int defaultValue) {
|
||||
return getIntegerValue(textField.getText(), defaultValue) != value;
|
||||
}
|
||||
|
||||
private static int getIntegerValue(String s, int defaultValue) {
|
||||
int value = defaultValue;
|
||||
try {
|
||||
value = Integer.parseInt(s);
|
||||
if(value < 0) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
catch (NumberFormatException ignored) {
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
@MagicConstant(intValues = {CodeInsightSettings.ALL, CodeInsightSettings.NONE, CodeInsightSettings.FIRST_LETTER})
|
||||
private int getCaseSensitiveValue() {
|
||||
Object value = myCaseSensitiveCombo.getSelectedItem();
|
||||
if (CASE_SENSITIVE_ALL.equals(value)){
|
||||
return CodeInsightSettings.ALL;
|
||||
}
|
||||
else if (CASE_SENSITIVE_NONE.equals(value)){
|
||||
return CodeInsightSettings.NONE;
|
||||
}
|
||||
else {
|
||||
return CodeInsightSettings.FIRST_LETTER;
|
||||
}
|
||||
}
|
||||
|
||||
private int getFocusLookupValue() {
|
||||
return myFocusLookup.getSelectedIndex() + 1;
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.intellij.application.options;
|
||||
|
||||
import com.intellij.codeInsight.CodeInsightSettings;
|
||||
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
|
||||
import com.intellij.ide.DataManager;
|
||||
import com.intellij.ide.ui.UISettings;
|
||||
import com.intellij.openapi.actionSystem.PlatformDataKeys;
|
||||
import com.intellij.openapi.application.ApplicationBundle;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import org.intellij.lang.annotations.MagicConstant;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.awt.event.ActionEvent;
|
||||
import java.awt.event.ActionListener;
|
||||
|
||||
public class CodeCompletionPanel {
|
||||
JPanel myPanel;
|
||||
private JCheckBox myCbAutocompletion;
|
||||
private JTextField myAutocompletionDelayField;
|
||||
private JCheckBox myCbAutopopupJavaDoc;
|
||||
private JTextField myAutopopupJavaDocField;
|
||||
private JCheckBox myCbAutocompleteCommonPrefix;
|
||||
private JCheckBox myCbShowStaticAfterInstance;
|
||||
|
||||
private JCheckBox myCbOnCodeCompletion;
|
||||
private JCheckBox myCbOnSmartTypeCompletion;
|
||||
|
||||
private JCheckBox myCbParameterInfoPopup;
|
||||
private JTextField myParameterInfoDelayField;
|
||||
private JCheckBox myCbShowFullParameterSignatures;
|
||||
|
||||
private JComboBox myCaseSensitiveCombo;
|
||||
private JComboBox myFocusLookup;
|
||||
private JCheckBox myCbSorting;
|
||||
private static final String CASE_SENSITIVE_ALL = ApplicationBundle.message("combobox.autocomplete.case.sensitive.all");
|
||||
private static final String CASE_SENSITIVE_NONE = ApplicationBundle.message("combobox.autocomplete.case.sensitive.none");
|
||||
private static final String CASE_SENSITIVE_FIRST_LETTER = ApplicationBundle.message("combobox.autocomplete.case.sensitive.first.letter");
|
||||
private static final String[] CASE_VARIANTS = {CASE_SENSITIVE_ALL, CASE_SENSITIVE_NONE, CASE_SENSITIVE_FIRST_LETTER};
|
||||
private static final String[] FOCUS_VARIANTS = {"Never", "'Smart'", "Always"};
|
||||
|
||||
public CodeCompletionPanel(){
|
||||
myCaseSensitiveCombo.setModel(new DefaultComboBoxModel(CASE_VARIANTS));
|
||||
myFocusLookup.setModel(new DefaultComboBoxModel(FOCUS_VARIANTS));
|
||||
|
||||
|
||||
myCbAutocompletion.addActionListener(
|
||||
new ActionListener() {
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent event) {
|
||||
myAutocompletionDelayField.setEnabled(myCbAutocompletion.isSelected());
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
myCbAutopopupJavaDoc.addActionListener(
|
||||
new ActionListener() {
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent event) {
|
||||
myAutopopupJavaDocField.setEnabled(myCbAutopopupJavaDoc.isSelected());
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
myCbParameterInfoPopup.addActionListener(
|
||||
new ActionListener() {
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent event) {
|
||||
myParameterInfoDelayField.setEnabled(myCbParameterInfoPopup.isSelected());
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
hideOption(myCbShowStaticAfterInstance, OptionId.COMPLETION_SHOW_STATIC_AFTER_IMPORT);
|
||||
hideOption(myCbOnSmartTypeCompletion, OptionId.COMPLETION_SMART_TYPE);
|
||||
myCbAutocompleteCommonPrefix.setVisible(false);
|
||||
|
||||
reset();
|
||||
}
|
||||
|
||||
private static void hideOption(JComponent component, OptionId id) {
|
||||
component.setVisible(OptionsApplicabilityFilter.isApplicable(id));
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
CodeInsightSettings codeInsightSettings = CodeInsightSettings.getInstance();
|
||||
|
||||
final String value;
|
||||
switch(codeInsightSettings.COMPLETION_CASE_SENSITIVE){
|
||||
case CodeInsightSettings.ALL:
|
||||
value = CASE_SENSITIVE_ALL;
|
||||
break;
|
||||
|
||||
case CodeInsightSettings.NONE:
|
||||
value = CASE_SENSITIVE_NONE;
|
||||
break;
|
||||
|
||||
default:
|
||||
value = CASE_SENSITIVE_FIRST_LETTER;
|
||||
break;
|
||||
}
|
||||
myCaseSensitiveCombo.setSelectedItem(value);
|
||||
|
||||
myFocusLookup.setSelectedIndex(Math.min(Math.max(codeInsightSettings.AUTOPOPUP_FOCUS_POLICY - 1, 0), FOCUS_VARIANTS.length - 1));
|
||||
|
||||
myCbOnCodeCompletion.setSelected(codeInsightSettings.AUTOCOMPLETE_ON_CODE_COMPLETION);
|
||||
myCbOnSmartTypeCompletion.setSelected(codeInsightSettings.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION);
|
||||
myCbAutocompleteCommonPrefix.setSelected(codeInsightSettings.AUTOCOMPLETE_COMMON_PREFIX);
|
||||
myCbShowStaticAfterInstance.setSelected(codeInsightSettings.SHOW_STATIC_AFTER_INSTANCE);
|
||||
|
||||
myCbAutocompletion.setSelected(codeInsightSettings.AUTO_POPUP_COMPLETION_LOOKUP);
|
||||
myAutocompletionDelayField.setEnabled(codeInsightSettings.AUTO_POPUP_COMPLETION_LOOKUP);
|
||||
myAutocompletionDelayField.setText(String.valueOf(codeInsightSettings.AUTO_LOOKUP_DELAY));
|
||||
|
||||
myCbAutopopupJavaDoc.setSelected(codeInsightSettings.AUTO_POPUP_JAVADOC_INFO);
|
||||
myAutopopupJavaDocField.setEnabled(codeInsightSettings.AUTO_POPUP_JAVADOC_INFO);
|
||||
myAutopopupJavaDocField.setText(String.valueOf(codeInsightSettings.JAVADOC_INFO_DELAY));
|
||||
|
||||
myCbParameterInfoPopup.setSelected(codeInsightSettings.AUTO_POPUP_PARAMETER_INFO);
|
||||
myParameterInfoDelayField.setEnabled(codeInsightSettings.AUTO_POPUP_PARAMETER_INFO);
|
||||
myParameterInfoDelayField.setText(String.valueOf(codeInsightSettings.PARAMETER_INFO_DELAY));
|
||||
myCbShowFullParameterSignatures.setSelected(codeInsightSettings.SHOW_FULL_SIGNATURES_IN_PARAMETER_INFO);
|
||||
|
||||
myCbAutocompletion.setSelected(codeInsightSettings.AUTO_POPUP_COMPLETION_LOOKUP);
|
||||
myCbSorting.setSelected(UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY);
|
||||
}
|
||||
|
||||
public void apply() {
|
||||
|
||||
CodeInsightSettings codeInsightSettings = CodeInsightSettings.getInstance();
|
||||
|
||||
codeInsightSettings.COMPLETION_CASE_SENSITIVE = getCaseSensitiveValue();
|
||||
//noinspection MagicConstant
|
||||
codeInsightSettings.AUTOPOPUP_FOCUS_POLICY = getFocusLookupValue();
|
||||
|
||||
codeInsightSettings.AUTOCOMPLETE_ON_CODE_COMPLETION = myCbOnCodeCompletion.isSelected();
|
||||
codeInsightSettings.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION = myCbOnSmartTypeCompletion.isSelected();
|
||||
codeInsightSettings.AUTOCOMPLETE_COMMON_PREFIX = myCbAutocompleteCommonPrefix.isSelected();
|
||||
codeInsightSettings.SHOW_STATIC_AFTER_INSTANCE = myCbShowStaticAfterInstance.isSelected();
|
||||
codeInsightSettings.SHOW_FULL_SIGNATURES_IN_PARAMETER_INFO = myCbShowFullParameterSignatures.isSelected();
|
||||
|
||||
codeInsightSettings.AUTO_POPUP_PARAMETER_INFO = myCbParameterInfoPopup.isSelected();
|
||||
codeInsightSettings.AUTO_POPUP_COMPLETION_LOOKUP = myCbAutocompletion.isSelected();
|
||||
codeInsightSettings.AUTO_POPUP_JAVADOC_INFO = myCbAutopopupJavaDoc.isSelected();
|
||||
|
||||
codeInsightSettings.AUTO_LOOKUP_DELAY = getIntegerValue(myAutocompletionDelayField.getText(), 0);
|
||||
codeInsightSettings.PARAMETER_INFO_DELAY = getIntegerValue(myParameterInfoDelayField.getText(), 0);
|
||||
codeInsightSettings.JAVADOC_INFO_DELAY = getIntegerValue(myAutopopupJavaDocField.getText(), 0);
|
||||
|
||||
UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = myCbSorting.isSelected();
|
||||
|
||||
final Project project = PlatformDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(myPanel));
|
||||
if (project != null){
|
||||
DaemonCodeAnalyzer.getInstance(project).settingsChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isModified() {
|
||||
CodeInsightSettings codeInsightSettings = CodeInsightSettings.getInstance();
|
||||
boolean isModified = false;
|
||||
|
||||
//noinspection ConstantConditions
|
||||
isModified |= getCaseSensitiveValue() != codeInsightSettings.COMPLETION_CASE_SENSITIVE;
|
||||
//noinspection MagicConstant
|
||||
isModified |= getFocusLookupValue() != codeInsightSettings.AUTOPOPUP_FOCUS_POLICY;
|
||||
|
||||
isModified |= isModified(myCbOnCodeCompletion, codeInsightSettings.AUTOCOMPLETE_ON_CODE_COMPLETION);
|
||||
isModified |= isModified(myCbOnSmartTypeCompletion, codeInsightSettings.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION);
|
||||
isModified |= isModified(myCbAutocompleteCommonPrefix, codeInsightSettings.AUTOCOMPLETE_COMMON_PREFIX);
|
||||
isModified |= isModified(myCbShowStaticAfterInstance, codeInsightSettings.SHOW_STATIC_AFTER_INSTANCE);
|
||||
isModified |= isModified(myCbShowFullParameterSignatures, codeInsightSettings.SHOW_FULL_SIGNATURES_IN_PARAMETER_INFO);
|
||||
isModified |= isModified(myCbParameterInfoPopup, codeInsightSettings.AUTO_POPUP_PARAMETER_INFO);
|
||||
isModified |= isModified(myCbAutocompletion, codeInsightSettings.AUTO_POPUP_COMPLETION_LOOKUP);
|
||||
|
||||
isModified |= isModified(myCbAutopopupJavaDoc, codeInsightSettings.AUTO_POPUP_JAVADOC_INFO);
|
||||
isModified |= isModified(myAutocompletionDelayField, codeInsightSettings.AUTO_LOOKUP_DELAY, 0);
|
||||
isModified |= isModified(myParameterInfoDelayField, codeInsightSettings.PARAMETER_INFO_DELAY, 0);
|
||||
isModified |= isModified(myAutopopupJavaDocField, codeInsightSettings.JAVADOC_INFO_DELAY, 0);
|
||||
isModified |= isModified(myCbSorting, UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY);
|
||||
|
||||
return isModified;
|
||||
}
|
||||
|
||||
private static boolean isModified(JCheckBox checkBox, boolean value) {
|
||||
return checkBox.isSelected() != value;
|
||||
}
|
||||
|
||||
private static boolean isModified(JTextField textField, int value, int defaultValue) {
|
||||
return getIntegerValue(textField.getText(), defaultValue) != value;
|
||||
}
|
||||
|
||||
private static int getIntegerValue(String s, int defaultValue) {
|
||||
int value = defaultValue;
|
||||
try {
|
||||
value = Integer.parseInt(s);
|
||||
if(value < 0) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
catch (NumberFormatException ignored) {
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
@MagicConstant(intValues = {CodeInsightSettings.ALL, CodeInsightSettings.NONE, CodeInsightSettings.FIRST_LETTER})
|
||||
private int getCaseSensitiveValue() {
|
||||
Object value = myCaseSensitiveCombo.getSelectedItem();
|
||||
if (CASE_SENSITIVE_ALL.equals(value)){
|
||||
return CodeInsightSettings.ALL;
|
||||
}
|
||||
else if (CASE_SENSITIVE_NONE.equals(value)){
|
||||
return CodeInsightSettings.NONE;
|
||||
}
|
||||
else {
|
||||
return CodeInsightSettings.FIRST_LETTER;
|
||||
}
|
||||
}
|
||||
|
||||
private int getFocusLookupValue() {
|
||||
return myFocusLookup.getSelectedIndex() + 1;
|
||||
}
|
||||
}
|
||||
@@ -1,31 +1,31 @@
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.intellij.application.options;
|
||||
|
||||
/**
|
||||
* @author yole
|
||||
*/
|
||||
public class OptionId {
|
||||
private OptionId() {
|
||||
}
|
||||
|
||||
public static final OptionId RENAME_IN_PLACE = new OptionId();
|
||||
public static final OptionId COMPLETION_SHOW_STATIC_AFTER_IMPORT = new OptionId();
|
||||
public static final OptionId COMPLETION_SMART_TYPE = new OptionId();
|
||||
@Deprecated public static final OptionId COMPLETION_CLASS_NAME = new OptionId();
|
||||
public static final OptionId ICONS_IN_GUTTER = new OptionId();
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.intellij.application.options;
|
||||
|
||||
/**
|
||||
* @author yole
|
||||
*/
|
||||
public class OptionId {
|
||||
private OptionId() {
|
||||
}
|
||||
|
||||
public static final OptionId RENAME_IN_PLACE = new OptionId();
|
||||
public static final OptionId COMPLETION_SHOW_STATIC_AFTER_IMPORT = new OptionId();
|
||||
public static final OptionId COMPLETION_SMART_TYPE = new OptionId();
|
||||
@Deprecated public static final OptionId COMPLETION_CLASS_NAME = new OptionId();
|
||||
public static final OptionId ICONS_IN_GUTTER = new OptionId();
|
||||
}
|
||||
|
||||
@@ -1,171 +1,171 @@
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.intellij.codeInsight;
|
||||
|
||||
import com.intellij.openapi.application.PathManager;
|
||||
import com.intellij.openapi.components.*;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.util.ArrayUtil;
|
||||
import com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters;
|
||||
import com.intellij.util.xmlb.XmlSerializationException;
|
||||
import com.intellij.util.xmlb.XmlSerializer;
|
||||
import com.intellij.util.xmlb.annotations.AbstractCollection;
|
||||
import com.intellij.util.xmlb.annotations.Property;
|
||||
import org.intellij.lang.annotations.MagicConstant;
|
||||
import org.jdom.Element;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
|
||||
@State(
|
||||
name = "CodeInsightSettings",
|
||||
storages = {
|
||||
@Storage(
|
||||
file = StoragePathMacros.APP_CONFIG + "/editor.codeinsight.xml"
|
||||
)}
|
||||
)
|
||||
public class CodeInsightSettings implements PersistentStateComponent<Element>, Cloneable, ExportableComponent {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.CodeInsightSettings");
|
||||
|
||||
@NonNls public static final String EXTERNAL_FILE_NAME = "editor.codeinsight";
|
||||
|
||||
public static CodeInsightSettings getInstance() {
|
||||
return ServiceManager.getService(CodeInsightSettings.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public File[] getExportFiles() {
|
||||
return new File[]{PathManager.getOptionsFile(EXTERNAL_FILE_NAME)};
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getPresentableName() {
|
||||
return CodeInsightBundle.message("codeinsight.settings");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public CodeInsightSettings clone() {
|
||||
try {
|
||||
return (CodeInsightSettings)super.clone();
|
||||
}
|
||||
catch (CloneNotSupportedException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean AUTO_POPUP_PARAMETER_INFO = true;
|
||||
public int PARAMETER_INFO_DELAY = 1000;
|
||||
public boolean AUTO_POPUP_JAVADOC_INFO = false;
|
||||
public int JAVADOC_INFO_DELAY = 1000;
|
||||
public boolean AUTO_POPUP_COMPLETION_LOOKUP = true;
|
||||
public int AUTO_LOOKUP_DELAY = 0;
|
||||
|
||||
@MagicConstant(intValues = {ALL, NONE, FIRST_LETTER})
|
||||
public int COMPLETION_CASE_SENSITIVE = FIRST_LETTER;
|
||||
public static final int ALL = 1;
|
||||
public static final int NONE = 2;
|
||||
public static final int FIRST_LETTER = 3;
|
||||
|
||||
@MagicConstant(intValues = {NEVER, SMART, ALWAYS})
|
||||
public int AUTOPOPUP_FOCUS_POLICY = SMART;
|
||||
public static final int NEVER = 1;
|
||||
public static final int SMART = 2;
|
||||
public static final int ALWAYS = 3;
|
||||
|
||||
public boolean AUTOCOMPLETE_ON_CODE_COMPLETION = true;
|
||||
public boolean AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION = true;
|
||||
@Deprecated public boolean AUTOCOMPLETE_ON_CLASS_NAME_COMPLETION = false;
|
||||
public boolean AUTOCOMPLETE_COMMON_PREFIX = true;
|
||||
public boolean SHOW_STATIC_AFTER_INSTANCE = false;
|
||||
|
||||
public boolean SHOW_FULL_SIGNATURES_IN_PARAMETER_INFO = false;
|
||||
|
||||
public boolean SMART_INDENT_ON_ENTER = true;
|
||||
public boolean INSERT_BRACE_ON_ENTER = true;
|
||||
public boolean INSERT_SCRIPTLET_END_ON_ENTER = true;
|
||||
public boolean JAVADOC_STUB_ON_ENTER = true;
|
||||
public boolean SMART_END_ACTION = true;
|
||||
public boolean JAVADOC_GENERATE_CLOSING_TAG = true;
|
||||
|
||||
public boolean SURROUND_SELECTION_ON_QUOTE_TYPED = false;
|
||||
|
||||
public boolean AUTOINSERT_PAIR_BRACKET = true;
|
||||
public boolean AUTOINSERT_PAIR_QUOTE = true;
|
||||
|
||||
public int REFORMAT_ON_PASTE = INDENT_EACH_LINE;
|
||||
public static final int NO_REFORMAT = 1;
|
||||
public static final int INDENT_BLOCK = 2;
|
||||
public static final int INDENT_EACH_LINE = 3;
|
||||
public static final int REFORMAT_BLOCK = 4;
|
||||
|
||||
public boolean INDENT_TO_CARET_ON_PASTE = false;
|
||||
|
||||
public int ADD_IMPORTS_ON_PASTE = ASK; // YES, NO or ASK
|
||||
public static final int YES = 1;
|
||||
public static final int NO = 2;
|
||||
public static final int ASK = 3;
|
||||
|
||||
public boolean HIGHLIGHT_BRACES = true;
|
||||
public boolean HIGHLIGHT_SCOPE = false;
|
||||
|
||||
public boolean USE_INSTANCEOF_ON_EQUALS_PARAMETER = false;
|
||||
|
||||
public boolean HIGHLIGHT_IDENTIFIER_UNDER_CARET = true;
|
||||
|
||||
public boolean OPTIMIZE_IMPORTS_ON_THE_FLY = false;
|
||||
public boolean ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = false;
|
||||
public boolean JSP_ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = false;
|
||||
|
||||
@Property(surroundWithTag = false)
|
||||
@AbstractCollection(
|
||||
surroundWithTag = false,
|
||||
elementTag = "EXCLUDED_PACKAGE",
|
||||
elementValueAttribute = "NAME")
|
||||
public String[] EXCLUDED_PACKAGES = ArrayUtil.EMPTY_STRING_ARRAY;
|
||||
|
||||
@Override
|
||||
public void loadState(final Element state) {
|
||||
try {
|
||||
XmlSerializer.deserializeInto(this, state);
|
||||
}
|
||||
catch (XmlSerializationException e) {
|
||||
LOG.info(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Element getState() {
|
||||
Element element = new Element("state");
|
||||
writeExternal(element);
|
||||
return element;
|
||||
}
|
||||
|
||||
public void writeExternal(final Element element) {
|
||||
try {
|
||||
XmlSerializer.serializeInto(this, element, new SkipDefaultValuesSerializationFilters());
|
||||
}
|
||||
catch (XmlSerializationException e) {
|
||||
LOG.info(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2012 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.intellij.codeInsight;
|
||||
|
||||
import com.intellij.openapi.application.PathManager;
|
||||
import com.intellij.openapi.components.*;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.util.ArrayUtil;
|
||||
import com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters;
|
||||
import com.intellij.util.xmlb.XmlSerializationException;
|
||||
import com.intellij.util.xmlb.XmlSerializer;
|
||||
import com.intellij.util.xmlb.annotations.AbstractCollection;
|
||||
import com.intellij.util.xmlb.annotations.Property;
|
||||
import org.intellij.lang.annotations.MagicConstant;
|
||||
import org.jdom.Element;
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
|
||||
@State(
|
||||
name = "CodeInsightSettings",
|
||||
storages = {
|
||||
@Storage(
|
||||
file = StoragePathMacros.APP_CONFIG + "/editor.codeinsight.xml"
|
||||
)}
|
||||
)
|
||||
public class CodeInsightSettings implements PersistentStateComponent<Element>, Cloneable, ExportableComponent {
|
||||
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.CodeInsightSettings");
|
||||
|
||||
@NonNls public static final String EXTERNAL_FILE_NAME = "editor.codeinsight";
|
||||
|
||||
public static CodeInsightSettings getInstance() {
|
||||
return ServiceManager.getService(CodeInsightSettings.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public File[] getExportFiles() {
|
||||
return new File[]{PathManager.getOptionsFile(EXTERNAL_FILE_NAME)};
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getPresentableName() {
|
||||
return CodeInsightBundle.message("codeinsight.settings");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public CodeInsightSettings clone() {
|
||||
try {
|
||||
return (CodeInsightSettings)super.clone();
|
||||
}
|
||||
catch (CloneNotSupportedException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean AUTO_POPUP_PARAMETER_INFO = true;
|
||||
public int PARAMETER_INFO_DELAY = 1000;
|
||||
public boolean AUTO_POPUP_JAVADOC_INFO = false;
|
||||
public int JAVADOC_INFO_DELAY = 1000;
|
||||
public boolean AUTO_POPUP_COMPLETION_LOOKUP = true;
|
||||
public int AUTO_LOOKUP_DELAY = 0;
|
||||
|
||||
@MagicConstant(intValues = {ALL, NONE, FIRST_LETTER})
|
||||
public int COMPLETION_CASE_SENSITIVE = FIRST_LETTER;
|
||||
public static final int ALL = 1;
|
||||
public static final int NONE = 2;
|
||||
public static final int FIRST_LETTER = 3;
|
||||
|
||||
@MagicConstant(intValues = {NEVER, SMART, ALWAYS})
|
||||
public int AUTOPOPUP_FOCUS_POLICY = SMART;
|
||||
public static final int NEVER = 1;
|
||||
public static final int SMART = 2;
|
||||
public static final int ALWAYS = 3;
|
||||
|
||||
public boolean AUTOCOMPLETE_ON_CODE_COMPLETION = true;
|
||||
public boolean AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION = true;
|
||||
@Deprecated public boolean AUTOCOMPLETE_ON_CLASS_NAME_COMPLETION = false;
|
||||
public boolean AUTOCOMPLETE_COMMON_PREFIX = true;
|
||||
public boolean SHOW_STATIC_AFTER_INSTANCE = false;
|
||||
|
||||
public boolean SHOW_FULL_SIGNATURES_IN_PARAMETER_INFO = false;
|
||||
|
||||
public boolean SMART_INDENT_ON_ENTER = true;
|
||||
public boolean INSERT_BRACE_ON_ENTER = true;
|
||||
public boolean INSERT_SCRIPTLET_END_ON_ENTER = true;
|
||||
public boolean JAVADOC_STUB_ON_ENTER = true;
|
||||
public boolean SMART_END_ACTION = true;
|
||||
public boolean JAVADOC_GENERATE_CLOSING_TAG = true;
|
||||
|
||||
public boolean SURROUND_SELECTION_ON_QUOTE_TYPED = false;
|
||||
|
||||
public boolean AUTOINSERT_PAIR_BRACKET = true;
|
||||
public boolean AUTOINSERT_PAIR_QUOTE = true;
|
||||
|
||||
public int REFORMAT_ON_PASTE = INDENT_EACH_LINE;
|
||||
public static final int NO_REFORMAT = 1;
|
||||
public static final int INDENT_BLOCK = 2;
|
||||
public static final int INDENT_EACH_LINE = 3;
|
||||
public static final int REFORMAT_BLOCK = 4;
|
||||
|
||||
public boolean INDENT_TO_CARET_ON_PASTE = false;
|
||||
|
||||
public int ADD_IMPORTS_ON_PASTE = ASK; // YES, NO or ASK
|
||||
public static final int YES = 1;
|
||||
public static final int NO = 2;
|
||||
public static final int ASK = 3;
|
||||
|
||||
public boolean HIGHLIGHT_BRACES = true;
|
||||
public boolean HIGHLIGHT_SCOPE = false;
|
||||
|
||||
public boolean USE_INSTANCEOF_ON_EQUALS_PARAMETER = false;
|
||||
|
||||
public boolean HIGHLIGHT_IDENTIFIER_UNDER_CARET = true;
|
||||
|
||||
public boolean OPTIMIZE_IMPORTS_ON_THE_FLY = false;
|
||||
public boolean ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = false;
|
||||
public boolean JSP_ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = false;
|
||||
|
||||
@Property(surroundWithTag = false)
|
||||
@AbstractCollection(
|
||||
surroundWithTag = false,
|
||||
elementTag = "EXCLUDED_PACKAGE",
|
||||
elementValueAttribute = "NAME")
|
||||
public String[] EXCLUDED_PACKAGES = ArrayUtil.EMPTY_STRING_ARRAY;
|
||||
|
||||
@Override
|
||||
public void loadState(final Element state) {
|
||||
try {
|
||||
XmlSerializer.deserializeInto(this, state);
|
||||
}
|
||||
catch (XmlSerializationException e) {
|
||||
LOG.info(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Element getState() {
|
||||
Element element = new Element("state");
|
||||
writeExternal(element);
|
||||
return element;
|
||||
}
|
||||
|
||||
public void writeExternal(final Element element) {
|
||||
try {
|
||||
XmlSerializer.serializeInto(this, element, new SkipDefaultValuesSerializationFilters());
|
||||
}
|
||||
catch (XmlSerializationException e) {
|
||||
LOG.info(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+38
-38
@@ -1,38 +1,38 @@
|
||||
/*
|
||||
* Copyright 2000-2009 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.completion;
|
||||
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public interface
|
||||
CodeCompletionFeatures {
|
||||
@NonNls String EXCLAMATION_FINISH = "editing.completion.finishByExclamation";
|
||||
@NonNls String SECOND_BASIC_COMPLETION = "editing.completion.second.basic";
|
||||
@NonNls String EDITING_COMPLETION_SMARTTYPE_GENERAL = "editing.completion.smarttype.general";
|
||||
@NonNls String EDITING_COMPLETION_BASIC = "editing.completion.basic";
|
||||
@NonNls String EDITING_COMPLETION_CLASSNAME = "editing.completion.classname";
|
||||
@NonNls String EDITING_COMPLETION_CAMEL_HUMPS = "editing.completion.camelHumps";
|
||||
@NonNls String EDITING_COMPLETION_REPLACE = "editing.completion.replace";
|
||||
@NonNls String EDITING_COMPLETION_FINISH_BY_DOT_ETC = "editing.completion.finishByDotEtc";
|
||||
@NonNls String EDITING_COMPLETION_FINISH_BY_SMART_ENTER = "editing.completion.finishBySmartEnter";
|
||||
|
||||
@NonNls String EDITING_COMPLETION_CONTROL_ENTER = "editing.completion.finishByControlEnter";
|
||||
@NonNls String EDITING_COMPLETION_CONTROL_ARROWS = "editing.completion.cancelByControlArrows";
|
||||
@NonNls String EDITING_COMPLETION_CHANGE_SORTING = "editing.completion.changeSorting";
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 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.completion;
|
||||
|
||||
import org.jetbrains.annotations.NonNls;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public interface
|
||||
CodeCompletionFeatures {
|
||||
@NonNls String EXCLAMATION_FINISH = "editing.completion.finishByExclamation";
|
||||
@NonNls String SECOND_BASIC_COMPLETION = "editing.completion.second.basic";
|
||||
@NonNls String EDITING_COMPLETION_SMARTTYPE_GENERAL = "editing.completion.smarttype.general";
|
||||
@NonNls String EDITING_COMPLETION_BASIC = "editing.completion.basic";
|
||||
@NonNls String EDITING_COMPLETION_CLASSNAME = "editing.completion.classname";
|
||||
@NonNls String EDITING_COMPLETION_CAMEL_HUMPS = "editing.completion.camelHumps";
|
||||
@NonNls String EDITING_COMPLETION_REPLACE = "editing.completion.replace";
|
||||
@NonNls String EDITING_COMPLETION_FINISH_BY_DOT_ETC = "editing.completion.finishByDotEtc";
|
||||
@NonNls String EDITING_COMPLETION_FINISH_BY_SMART_ENTER = "editing.completion.finishBySmartEnter";
|
||||
|
||||
@NonNls String EDITING_COMPLETION_CONTROL_ENTER = "editing.completion.finishByControlEnter";
|
||||
@NonNls String EDITING_COMPLETION_CONTROL_ARROWS = "editing.completion.cancelByControlArrows";
|
||||
@NonNls String EDITING_COMPLETION_CHANGE_SORTING = "editing.completion.changeSorting";
|
||||
}
|
||||
|
||||
+30
-30
@@ -1,30 +1,30 @@
|
||||
/*
|
||||
* Copyright 2000-2009 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.completion;
|
||||
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public class PrefixMatchingWeigher extends CompletionWeigher {
|
||||
|
||||
@Override
|
||||
public Comparable weigh(@NotNull LookupElement element, @NotNull CompletionLocation location) {
|
||||
throw new UnsupportedOperationException("Not implemented");
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 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.completion;
|
||||
|
||||
import com.intellij.codeInsight.lookup.LookupElement;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public class PrefixMatchingWeigher extends CompletionWeigher {
|
||||
|
||||
@Override
|
||||
public Comparable weigh(@NotNull LookupElement element, @NotNull CompletionLocation location) {
|
||||
throw new UnsupportedOperationException("Not implemented");
|
||||
}
|
||||
}
|
||||
|
||||
+69
-69
@@ -1,69 +1,69 @@
|
||||
/*
|
||||
* Copyright 2000-2009 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.completion.actions;
|
||||
|
||||
import com.intellij.codeInsight.completion.CodeCompletionHandlerBase;
|
||||
import com.intellij.codeInsight.completion.CompletionType;
|
||||
import com.intellij.codeInsight.hint.HintManagerImpl;
|
||||
import com.intellij.openapi.actionSystem.AnAction;
|
||||
import com.intellij.openapi.actionSystem.AnActionEvent;
|
||||
import com.intellij.openapi.actionSystem.DataContext;
|
||||
import com.intellij.openapi.actionSystem.PlatformDataKeys;
|
||||
import com.intellij.openapi.application.ApplicationManager;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.project.DumbAware;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.psi.PsiFile;
|
||||
import com.intellij.psi.util.PsiUtilBase;
|
||||
|
||||
import java.awt.event.InputEvent;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public abstract class BaseCodeCompletionAction extends AnAction implements HintManagerImpl.ActionToIgnore, DumbAware {
|
||||
|
||||
protected BaseCodeCompletionAction() {
|
||||
setEnabledInModalContext(true);
|
||||
setInjectedContext(true);
|
||||
}
|
||||
|
||||
protected static void invokeCompletion(AnActionEvent e, CompletionType type, int time) {
|
||||
Project project = e.getData(PlatformDataKeys.PROJECT);
|
||||
Editor editor = e.getData(PlatformDataKeys.EDITOR);
|
||||
assert project != null;
|
||||
assert editor != null;
|
||||
InputEvent inputEvent = e.getInputEvent();
|
||||
new CodeCompletionHandlerBase(type).invokeCompletion(project, editor, time, inputEvent != null && inputEvent.getModifiers() != 0, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(AnActionEvent e) {
|
||||
DataContext dataContext = e.getDataContext();
|
||||
e.getPresentation().setEnabled(false);
|
||||
Project project = PlatformDataKeys.PROJECT.getData(dataContext);
|
||||
if (project == null) return;
|
||||
|
||||
Editor editor = PlatformDataKeys.EDITOR.getData(dataContext);
|
||||
if (editor == null) return;
|
||||
|
||||
final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
|
||||
if (psiFile == null) return;
|
||||
|
||||
if (!ApplicationManager.getApplication().isUnitTestMode() && !editor.getContentComponent().isShowing()) return;
|
||||
e.getPresentation().setEnabled(true);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Copyright 2000-2009 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.completion.actions;
|
||||
|
||||
import com.intellij.codeInsight.completion.CodeCompletionHandlerBase;
|
||||
import com.intellij.codeInsight.completion.CompletionType;
|
||||
import com.intellij.codeInsight.hint.HintManagerImpl;
|
||||
import com.intellij.openapi.actionSystem.AnAction;
|
||||
import com.intellij.openapi.actionSystem.AnActionEvent;
|
||||
import com.intellij.openapi.actionSystem.DataContext;
|
||||
import com.intellij.openapi.actionSystem.PlatformDataKeys;
|
||||
import com.intellij.openapi.application.ApplicationManager;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.project.DumbAware;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.psi.PsiFile;
|
||||
import com.intellij.psi.util.PsiUtilBase;
|
||||
|
||||
import java.awt.event.InputEvent;
|
||||
|
||||
/**
|
||||
* @author peter
|
||||
*/
|
||||
public abstract class BaseCodeCompletionAction extends AnAction implements HintManagerImpl.ActionToIgnore, DumbAware {
|
||||
|
||||
protected BaseCodeCompletionAction() {
|
||||
setEnabledInModalContext(true);
|
||||
setInjectedContext(true);
|
||||
}
|
||||
|
||||
protected static void invokeCompletion(AnActionEvent e, CompletionType type, int time) {
|
||||
Project project = e.getData(PlatformDataKeys.PROJECT);
|
||||
Editor editor = e.getData(PlatformDataKeys.EDITOR);
|
||||
assert project != null;
|
||||
assert editor != null;
|
||||
InputEvent inputEvent = e.getInputEvent();
|
||||
new CodeCompletionHandlerBase(type).invokeCompletion(project, editor, time, inputEvent != null && inputEvent.getModifiers() != 0, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(AnActionEvent e) {
|
||||
DataContext dataContext = e.getDataContext();
|
||||
e.getPresentation().setEnabled(false);
|
||||
Project project = PlatformDataKeys.PROJECT.getData(dataContext);
|
||||
if (project == null) return;
|
||||
|
||||
Editor editor = PlatformDataKeys.EDITOR.getData(dataContext);
|
||||
if (editor == null) return;
|
||||
|
||||
final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
|
||||
if (psiFile == null) return;
|
||||
|
||||
if (!ApplicationManager.getApplication().isUnitTestMode() && !editor.getContentComponent().isShowing()) return;
|
||||
e.getPresentation().setEnabled(true);
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user