Merge remote-tracking branch 'origin/master'

This commit is contained in:
Dmitry Batkovich
2016-03-21 20:57:29 +03:00
157 changed files with 2527 additions and 2119 deletions
+28 -28
View File
@@ -149,8 +149,8 @@ binding.setVariable("generateLicensesTable", {String filePath, Set<String> usedM
notifyArtifactBuilt(filePath)
})
libraryLicense(name: "aether-api-0.9.0.M2.jar", version: "0.9.0.M2", libraryNames: ["aether-api-0.9.0.M2.jar"], license: "Eclipse Public License v1.0", url: "http://nexus.sonatype.org/", licenseUrl: "http://www.eclipse.org/org/documents/epl-v10.html")
libraryLicense(name: "aether-api", version: "1.13.1", libraryNames: ["aether-api-1.13.1.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html")
libraryLicense(name: "aether-api-0.9.0.M2.jar", version: "0.9.0.M2", libraryNames: ["aether-api-0.9.0.M2.jar"], license: "Eclipse Public License v1.0", url: "http://www.eclipse.org/aether/", licenseUrl: "http://www.eclipse.org/org/documents/epl-v10.html")
libraryLicense(name: "aether-api", version: "1.13.1", libraryNames: ["aether-api-1.13.1.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Alloy L&F", libraryName: "alloy.jar", version: "1.4.4", license: "link (company license)", url: "http://lookandfeel.incors.com/", licenseUrl: "http://lookandfeel.incors.com/display_licence.php?back=purchase.php&selMenu=Purchase")
libraryLicense(name: "Android Builder Model", libraryName: "builder-model", license: "Apache 2.0", url: "http://source.android.com/")
libraryLicense(name: "Android Builder", libraryName: "android-builder", license: "Apache 2.0", url: "http://source.android.com/")
@@ -161,9 +161,9 @@ libraryLicense(name: "Ant", version: "1.9", license: "Apache 2.0", url: "http://
libraryLicense(name: "ANTLR 4 Runtime", libraryName: "antlr-runtime-4.1.jar", version: "4.1", license: "BSD", url: "http://www.antlr.org", licenseUrl: "http://www.antlr.org/license.html")
libraryLicense(name: "Antlr", libraryName: "antlr.jar", version: "3.4", license: "BSD", url: "http://www.antlr.org", licenseUrl: "http://www.antlr.org/license.html")
libraryLicense(name: "Apache Commons BeanUtils", libraryName: "commons-beanutils.jar", version: "1.6", license: "Apache 2.0", url: "http://commons.apache.org/beanutils/")
libraryLicense(name: "Apache Commons Codec", libraryName: "commons-codec", version: "1.8", license: "Apache 2.0", url: "http://commons.apache.org/codec/", licenseUrl: "http://commons.apache.org/license.html")
libraryLicense(name: "Apache Commons Codec", libraryName: "commons-codec", version: "1.8", license: "Apache 2.0", url: "http://commons.apache.org/codec/", licenseUrl: "http://www.apache.org/licenses/")
libraryLicense(name: "Apache Commons Compress", libraryName: "commons-compress-android", version: "1.0", license: "Apache 2.0", url: "http://commons.apache.org/proper/commons-compress/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Apache Commons Discovery", libraryName: "commons-discovery-0.4.jar", version: "0.4", license: "Apache 2.0", url: "http://jakarta.apache.org/commons/discovery/", licenseUrl: "http://commons.apache.org/license.html")
libraryLicense(name: "Apache Commons Discovery", libraryName: "commons-discovery-0.4.jar", version: "0.4", license: "Apache 2.0", url: "http://jakarta.apache.org/commons/discovery/", licenseUrl: "http://www.apache.org/licenses/")
libraryLicense(name: "Apache Commons HTTPClient", libraryName: "http-client-3.1", version: "3.1&nbsp; (with patch by JetBrains)", license: "Apache 2.0", url: "http://hc.apache.org/httpclient-3.x")
libraryLicense(name: "Apache Commons IO", libraryName: "commons-io-1.4.jar", version: "1.4", license: "Apache 2.0", url: "http://commons.apache.org/io/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0.txt")
libraryLicense(name: "Apache Commons Logging", libraryName: "commons-logging", version: "1.1.1", license: "Apache 2.0", url: "http://commons.apache.org/logging/")
@@ -178,15 +178,15 @@ libraryLicense(name: "ASM Bytecode Manipulation Framework", libraryName: "asm4",
libraryLicense(name: "ASM Bytecode Manipulation Framework", libraryName: "asm5", version: "5.0.3 (with patches by JetBrains)", license: "BSD", url: "http://asm.objectweb.org/", licenseUrl: "http://asm.objectweb.org/license.html")
libraryLicense(name: "assertJ", version: "3", license: "Apache 2.0", url: "https://github.com/joel-costigliola/assertj-core")
libraryLicense(name: "Automaton", libraryName: "automaton.jar", version: "1.11", license: "BSD", url: "http://www.brics.dk/automaton/", licenseUrl: "http://www.opensource.org/licenses/bsd-license.php")
libraryLicense(name: "Axis", libraryName: "axis-1.4", version: "1.4", license: "Apache 2.0", url: "http://ws.apache.org/axis/", licenseUrl: "http://svn.jetbrains.org/idea/Trunk/bundled/WebServices/resources/lib/axis-1.4.0/axis.LICENSE")
libraryLicense(name: "Axis", libraryName: "axis-1.4", version: "1.4", license: "Apache 2.0", url: "http://ws.apache.org/axis/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0.html")
libraryLicense(name: "bouncy-castle", version: "1.48", license: "MIT License", url: "http://bouncycastle.org", licenseUrl: "http://bouncycastle.org/licence.html")
libraryLicense(name: "CGLib", libraryName: "CGLIB", version: "2.2.2", license: "Apache", url: "http://cglib.sourceforge.net/", licenseUrl: "http://www.apache.org/foundation/licence-FAQ.html")
libraryLicense(name: "classworlds", libraryName: "classworlds-1.1.jar", version: "1.1", license: "codehaus", url: "http://classworlds.codehaus.org/", licenseUrl: "http://classworlds.codehaus.org/license.html")
libraryLicense(name: "classworlds", libraryName: "classworlds-1.1.jar", version: "1.1", license: "codehaus", url: "https://github.com/codehaus/classworlds", licenseUrl: "https://github.com/codehaus/classworlds/blob/master/classworlds/LICENSE.txt")
libraryLicense(name: "coverage.py", attachedTo: "python-helpers", version: "3.7.1", license: "Apache 2.0", url: "http://coverage.readthedocs.org/")
libraryLicense(name: "Cucumber-Core", libraryName: "cucumber-core", version: "1.2.4", license: "MIT License", url: "https://github.com/cucumber/cucumber-jvm/", licenseUrl: "http://www.opensource.org/licenses/mit-license.html")
libraryLicense(name: "Cucumber-Groovy", libraryName: "cucumber-groovy", version: "1.2.4", license: "MIT License", url: "https://github.com/cucumber/cucumber-jvm/", licenseUrl: "http://www.opensource.org/licenses/mit-license.html")
libraryLicense(name: "Cucumber-Java", libraryName: "cucumber-java", version: "1.2.4", license: "MIT License", url: "https://github.com/cucumber/cucumber-jvm/", licenseUrl: "http://www.opensource.org/licenses/mit-license.html")
libraryLicense(name: "Diffutils", libraryName: "Diffutils", version: "1.2.1", license: "The Apache Software License, Version 2.0", url: "http://www.apache.org/licenses/LICENSE-2.0", licenseUrl: "http://xstream.codehaus.org/license.html")
libraryLicense(name: "Diffutils", libraryName: "Diffutils", version: "1.2.1", license: "The Apache Software License, Version 2.0", url: "https://code.google.com/archive/p/java-diff-utils/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "docutils", attachedTo: "python-helpers", version: "0.8", license: "BSD", url: "http://docutils.sourceforge.net/")
libraryLicense(name: "DTDParser", version: "1.13", license: "LGPL", url: "http://sourceforge.net/projects/dtdparser/", licenseUrl: "http://www.opensource.org/licenses/lgpl-2.1")
libraryLicense(name: "Eclipse JDT Core", libraryName: "Eclipse", version: "4.2.1", license: "CPL 1.0", url: "http://www.eclipse.org/jdt/core/index.php")
@@ -196,7 +196,7 @@ libraryLicense(name: "Fest", libraryName: "fest", version: "", license: "Apache
libraryLicense(name: "FreeMarker", attachedTo: "coverage", version: "2.3.15", license: "BSD", url: "http://freemarker.sourceforge.net/")
libraryLicense(name: "FreeMarker", libraryName: "freemarker-2.3.20", version: "2.3.20", license: "BSD", url: "http://freemarker.sourceforge.net/")
libraryLicense(name: "fxg-utils", libraryName: "fxg-utils", version: "4.9.1", license: "Apache 2.0", url: "http://flex.apache.org", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Gant", version: "1.9.8", libraryName: "gant-1.9.11_groovy-2.3.0.jar", license: "Apache 2.0", url: "http://gant.codehaus.org/", licenseUrl: "http://gant.codehaus.org/Licence")
libraryLicense(name: "Gant", version: "1.9.8", libraryName: "gant-1.9.11_groovy-2.3.0.jar", license: "Apache 2.0", url: "https://github.com/codehaus/gant", licenseUrl: "https://github.com/codehaus/gant/blob/master/LICENCE.txt")
libraryLicense(name: "Gherkin", libraryName: "Gherkin", version: "2.12.2", license: "MIT", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0.txt", url: "https://github.com/cucumber/gherkin")
libraryLicense(name: "Google Feedback", libraryName: "GoogleFeedback.jar", version: "", license: "TBD")
libraryLicense(name: "gradle-tooling-api-2.9.jar", version: "2.9", license: "Apache 2.0", url: "http://gradle.org/", licenseUrl: "http://gradle.org/license")
@@ -210,7 +210,7 @@ libraryLicense(name: "Guava", version: "17.0", license: "Apache 2.0", url: "http
libraryLicense(name: "hamcrest", version: "1.3", license: "BSD", url: "http://hamcrest.org/", licenseUrl: "http://opensource.org/licenses/BSD-3-Clause")
libraryLicense(name: "HttpComponents HttpClient", libraryName: "http-client", version: "4.3.2", license: "Apache 2.0", url: "http://hc.apache.org/httpcomponents-client-ga/index.html")
libraryLicense(name: "imgscalr", libraryName: "imgscalr", version: "4.2", license: "Apache 2.0", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0.txt", url: "https://github.com/thebuzzmedia/imgscalr")
libraryLicense(name: "batik", libraryName: "batik", version: "1.7.1", license: "Apache 2.0", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0.txt", url: "https://svn.apache.org/repos/asf/xmlgraphics/batik")
libraryLicense(name: "batik", libraryName: "batik", version: "1.7.1", license: "Apache 2.0", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0.txt", url: "https://xmlgraphics.apache.org/batik/")
libraryLicense(name: "xmlgraphics-commons", libraryName: "xmlgraphics-commons", version: "1.5", license: "Apache 2.0", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0.txt", url: "https://xmlgraphics.apache.org/commons/")
libraryLicense(name: "xml-apis-ext", libraryName: "xml-apis-ext", version: "1.3", license: "Apache 2.0", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0.txt", url: "http://xerces.apache.org/xml-commons/components/external")
libraryLicense(name: "ImageIO", libraryName: "com.twelvemonkeys.imageio:imageio-tiff:3.2.1", version: "3.2.1", license: "BSD", url: "https://github.com/haraldk/TwelveMonkeys", licenseUrl: "https://github.com/haraldk/TwelveMonkeys#license")
@@ -218,7 +218,7 @@ libraryLicense(name: "ini4j", libraryName: "ini4j-0.5.2-patched", version: "0.5.
libraryLicense(name: "ISO RELAX", libraryName: "isorelax.jar", license: "MIT License", url: "http://sourceforge.net/projects/iso-relax/", licenseUrl: "http://www.opensource.org/licenses/mit-license.html")
libraryLicense(name: "Jakarta ORO", libraryName: "OroMatcher", version: "2.0.8", license: "Apache", url: "http://jakarta.apache.org/oro/", licenseUrl: "http://svn.apache.org/repos/asf/jakarta/oro/trunk/LICENSE")
libraryLicense(name: "Java-WebSocket", libraryName: "java_websocket.jar", version: "1.4.0 Trunk", license: "MIT", url: "https://github.com/TooTallNate/Java-WebSocket", licenseUrl:"https://github.com/TooTallNate/Java-WebSocket/blob/master/LICENSE")
libraryLicense(name: "JavaCVS", attachedTo: "javacvs-src", version: "no version number available (with patches by JetBrains)", license: "Sun Public License", url: "https://versioncontrol.netbeans.org/javacvs/library/", licenseUrl: "http://www.netbeans.org/about/legal/spl.html")
libraryLicense(name: "JavaCVS", attachedTo: "javacvs-src", version: "no version number available (with patches by JetBrains)", license: "Sun Public License", url: "https://versioncontrol.netbeans.org/javacvs/library/", licenseUrl: "https://netbeans.org/about/legal/license.html")
libraryLicense(name: "JavaHelp", version: "2.0_02", license: "included as license/javahelp_license.html in IntelliJ IDEA distribution", url: "http://java.sun.com/products/javahelp/")
libraryLicense(name: "javawriter", libraryName: "javawriter", license: "Apache 2.0", url: "https://github.com/square/javawriter")
libraryLicense(name: "JAXB", libraryName: "JAXB", version: "2.2.4-1", license: "CDDL 1.1", url: "http://jaxb.java.net/", licenseUrl: "http://glassfish.java.net/public/CDDL+GPL_1_1.html")
@@ -230,9 +230,9 @@ libraryLicense(name: "JediTerm", libraryName: "jediterm-pty", version: "0.2", li
libraryLicense(name: "JEuclid", libraryName: "jeuclid-core-3.1.9.jar", version: "3.1.9", license: "Apache 2.0", url: "http://jeuclid.sourceforge.net", licenseUrl:"http://sourceforge.net/p/jeuclid/code/ci/default/tree/LICENSE.txt")
libraryLicense(name: "JGit", libraryName: "jackson", version: "2.5.1", license: "Apache 2.0", licenseUrl: "http://www.eclipse.org/org/documents/edl-v10.php", url: "https://github.com/FasterXML/jackson")
libraryLicense(name: "JGit", libraryName: "jgit", version: "4.0", license: "Eclipse Distribution License 1.0", licenseUrl: "http://www.eclipse.org/org/documents/edl-v10.php", url: "https://eclipse.org/jgit/")
libraryLicense(name: "JGoodies Common", libraryName: "jgoodies-common", version: "1.2.1", license: "BSD ", url: "http://www.jgoodies.com/freeware/libraries/looks/", licenseUrl: "http://www.jgoodies.com/downloads/libraries.html")
libraryLicense(name: "JGoodies Forms", libraryName: "jgoodies-forms", version: "1.1-preview 2006-05-04 11:55:37", license: "BSD ", url: "http://www.jgoodies.com/freeware/libraries/forms/", licenseUrl: "http://www.jgoodies.com/downloads/libraries.html")
libraryLicense(name: "JGoodies Looks", libraryName: "jgoodies-looks", version: "2.4.2", license: "BSD ", url: "http://www.jgoodies.com/freeware/libraries/looks/", licenseUrl: "http://www.jgoodies.com/downloads/libraries.html")
libraryLicense(name: "JGoodies Common", libraryName: "jgoodies-common", version: "1.2.1", license: "BSD ", url: "http://www.jgoodies.com/freeware/libraries/looks/", licenseUrl: "https://opensource.org/licenses/bsd-license.html")
libraryLicense(name: "JGoodies Forms", libraryName: "jgoodies-forms", version: "1.1-preview 2006-05-04 11:55:37", license: "BSD ", url: "http://www.jgoodies.com/freeware/libraries/forms/", licenseUrl: "https://opensource.org/licenses/bsd-license.html")
libraryLicense(name: "JGoodies Looks", libraryName: "jgoodies-looks", version: "2.4.2", license: "BSD ", url: "http://www.jgoodies.com/freeware/libraries/looks/", licenseUrl: "https://opensource.org/licenses/bsd-license.html")
libraryLicense(name: "JNA", libraryName: "jna", version: "4.1.0", license: "LGPL 2.1", url: "https://github.com/java-native-access/jna", licenseUrl: "http://www.opensource.org/licenses/lgpl-2.1.php")
libraryLicense(name: "jsch-agent-proxy for svnkit trilead", libraryName: "jsch.agentproxy.svnkit-trilead-ssh2.jar", version: "0.0.7", license: "BSD", url: "https://github.com/ymnk/jsch-agent-proxy", licenseUrl: "https://github.com/ymnk/jsch-agent-proxy/blob/master/LICENSE.txt")
libraryLicense(name: "jsch-agent-proxy", libraryName: "jsch-agent-proxy", version: "0.0.7", license: "BSD", url: "https://github.com/ymnk/jsch-agent-proxy", licenseUrl: "https://github.com/ymnk/jsch-agent-proxy/blob/master/LICENSE.txt")
@@ -248,16 +248,16 @@ libraryLicense(name: "jzlib", libraryName: "jzlib", version: "1.1.1", license: "
libraryLicense(name: "Kryo", libraryName: "Kryo", version: "2.22", license: "New BSD License", url: "https://github.com/EsotericSoftware/kryo", licenseUrl: "https://github.com/EsotericSoftware/kryo/blob/master/license.txt")
libraryLicense(name: "kXML2", libraryName: "kxml2", version: "2.3.0", license: "BSD", url: "http://sourceforge.net/projects/kxml/")
libraryLicense(name: "Lobo evolution", libraryName: "Loboevolution.jar", version: "0.98.6 (with patches by JetBrains)", license: "MIT", url: "http://sourceforge.net/projects/loboevolution/", licenseUrl: "http://opensource.org/licenses/mit-license.php")
libraryLicense(name: "Log4j", libraryName: "Log4J", version: "1.2.17", license: "Apache 2.0", url: "http://logging.apache.org/log4j/1.2/index.html", licenseUrl: "http://logging.apache.org/license.html")
libraryLicense(name: "Log4j", libraryName: "Log4J", version: "1.2.17", license: "Apache 2.0", url: "http://logging.apache.org/log4j/1.2/index.html", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Lombok AST", libraryName: "lombok-ast", version: "0.2.1", license: "MIT", url: "http://projectlombok.org/", licenseUrl: "http://opensource.org/licenses/mit-license.php")
libraryLicense(name: "markdown4j", libraryName: "markdown4j-2.2", version: "2.2", license: "New BSD", url: "https://code.google.com/p/markdown4j/", licenseUrl: "http://opensource.org/licenses/BSD-3-Clause")
libraryLicense(name: "markdownj", attachedTo: "tasks-core", version: "", license: "BSD", url: "http://markdownj.org/", licenseUrl: "http://www.opensource.org/licenses/bsd-license.php")
libraryLicense(name: "markdownj", libraryName: "markdownj", version: "0.4.2", license: "New BSD", url: "https://code.google.com/p/markdownj/", licenseUrl: "http://opensource.org/licenses/BSD-3-Clause")
libraryLicense(name: "maven-2.2.1-uber", version: "2.2.1", libraryNames: ["maven-2.2.1-uber.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html")
libraryLicense(name: "maven-artifact", version: "3.0.5", libraryNames: ["maven-artifact-3.0.5.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html")
libraryLicense(name: "maven-core", version: "3.0.5", libraryNames: ["maven-core-3.0.5.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html")
libraryLicense(name: "Maven", version: "2.2.1", license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html")
libraryLicense(name: "Maven3", libraryNames: ["Maven3", "maven-dependency-tree-1.2.jar", "archetype-catalog-2.2.jar", "archetype-common-2.2.jar"], version: "3.0.5", license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html")
libraryLicense(name: "markdownj", attachedTo: "tasks-core", version: "", license: "BSD", url: "https://github.com/myabc/markdownj", licenseUrl: "http://www.opensource.org/licenses/bsd-license.php")
libraryLicense(name: "markdownj", libraryName: "markdownj", version: "0.4.2", license: "New BSD", url: "https://github.com/myabc/markdownj", licenseUrl: "http://opensource.org/licenses/BSD-3-Clause")
libraryLicense(name: "maven-2.2.1-uber", version: "2.2.1", libraryNames: ["maven-2.2.1-uber.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "maven-artifact", version: "3.0.5", libraryNames: ["maven-artifact-3.0.5.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "maven-core", version: "3.0.5", libraryNames: ["maven-core-3.0.5.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Maven", version: "2.2.1", license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Maven3", libraryNames: ["Maven3", "maven-dependency-tree-1.2.jar", "archetype-catalog-2.2.jar", "archetype-common-2.2.jar"], version: "3.0.5", license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "mercurial_prompthooks", attachedTo: "hg4idea", version: "", license: "GPLv2 (used as hg extension called from hg executable)", url: "https://github.com/willemv/mercurial_prompthooks", licenseUrl: "https://github.com/willemv/mercurial_prompthooks/blob/master/LICENSE.txt")
libraryLicense(name: "Microba", libraryName: "microba", version: "0.4.2", license: "BSD", url: "http://microba.sourceforge.net/", licenseUrl: "http://microba.sourceforge.net/license.txt")
libraryLicense(name: "MigLayout", libraryName: "miglayout-swing", version: "3.7.1", license: "BSD", url: "http://www.miglayout.com/", licenseUrl: "http://www.miglayout.com/mavensite/license.html")
@@ -268,14 +268,14 @@ libraryLicense(name: "Netty", libraryName: "Netty", version: "4.1.0.Beta3", lice
libraryLicense(name: "Objenesis", libraryName: "objenesis-1.2.jar", version: "1.2", license: "Apache 2.0", url: "http://objenesis.org/", licenseUrl: "http://apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "opentest4j", libraryName: "opentest4j", version: "1.0.0", license: "Apache 2.0", url: "https://github.com/ota4j-team/opentest4j", licenseUrl: "http://apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "pep8.py", attachedTo: "python-helpers", version: "1.6.2", license: "MIT", url: "http://pep8.readthedocs.org/")
libraryLicense(name: "PicoContainer", libraryName: "picocontainer", version: "1.2", license: "BSD", url: "http://www.picocontainer.org/", licenseUrl: "http://docs.codehaus.org/display/PICO/License")
libraryLicense(name: "PicoContainer", libraryName: "picocontainer", version: "1.2", license: "BSD", url: "https://github.com/codehaus/picocontainer", licenseUrl: "https://opensource.org/licenses/bsd-license.php")
libraryLicense(name: "plexus-archiver", libraryName: "plexus-archiver-2.4.4.jar", version: "2.4.4", license: "Apache 2.0", url: "https://github.com/codehaus-plexus/plexus-archiver", licenseUrl: "http://apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "plexus-classworlds", libraryName: "plexus-classworlds-2.4.jar", version: "2.4", license: "Apache 2.0", url: "https://github.com/codehaus-plexus/plexus-classworlds", licenseUrl: "http://apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "plexus-component-annotations", version: "1.5.5", libraryNames: ["plexus-component-annotations-1.5.5.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html")
libraryLicense(name: "plexus-component-annotations", version: "1.5.5", libraryNames: ["plexus-component-annotations-1.5.5.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "plexus-util", version: "2.0.6", license: "Apache 2.0", url: "http://maven.apache.org/", libraryNames:['plexus-utils-2.0.6.jar'], licenseUrl: "http://apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Plexus Utils", libraryName: "plexus-utils-1.5.5.jar", version: "1.5.5", license: "Apache 2.0", url: "http://plexus.codehaus.org/plexus-utils")
libraryLicense(name: "pockets", attachedTo: "python-helpers", version: "0.2.4", license: "BSD", url: "http://pockets.readthedocs.org/")
libraryLicense(name: "protobuf", version: "2.5.0", license: "New BSD", url: "http://code.google.com/p/protobuf/", licenseUrl: "http://code.google.com/p/protobuf/source/browse/trunk/COPYING.txt?r=367")
libraryLicense(name: "protobuf", version: "2.5.0", license: "New BSD", url: "http://code.google.com/p/protobuf/", licenseUrl: "https://github.com/google/protobuf/blob/master/LICENSE")
libraryLicense(name: "proxy-vole", libraryName: "proxy-vole", version: "20131209", license: "New BSD License", url: "http://code.google.com/p/proxy-vole/", licenseUrl: "http://opensource.org/licenses/BSD-3-Clause")
libraryLicense(name: "pty4j", libraryName: "pty4j", version: "0.6", license: "Eclipse Public License v1.0", url: "https://github.com/traff/pty4j")
libraryLicense(name: "PureJavaComm", libraryName: "purejavacomm", version: "0.0.16", license: "BSD", url: "http://www.sparetimelabs.com/purejavacomm")
@@ -300,19 +300,19 @@ libraryLicense(name: "sqljet", version: "bundled with SVNKit", libraryName: "sql
libraryLicense(name: "svnkit-javahl", version: "bundled with SVNKit", libraryName: "svnkit-javahl.jar", license: "link (commercial license)", url: "http://www.svnkit.com/", licenseUrl: "http://svnkit.com/license.html")
libraryLicense(name: "SVNKit", libraryName: "svnkit.jar", version: "1.8.7", license: "link (commercial license)", url: "http://www.svnkit.com/", licenseUrl: "http://svnkit.com/license.html")
libraryLicense(name: "swingx", libraryName: "swingx", version: "1.6.2", license: "LGPL 2.1", url: "http://java.net/downloads/swingx/", licenseUrl: "http://www.opensource.org/licenses/lgpl-2.1.php")
libraryLicense(name: "TestNG", version: "6.9 snapshot", license: "Apache 2.0", url: "http://testng.org/doc/", licenseUrl: "http://code.google.com/p/testng/")
libraryLicense(name: "TestNG", version: "6.9 snapshot", license: "Apache 2.0", url: "http://testng.org/doc/", licenseUrl: "https://github.com/cbeust/testng/blob/master/LICENSE.txt")
libraryLicense(name: "Trilead SSH", libraryName: "trilead-ssh2", version: "build 213 and 217", license: "BSD style (see LICENSE.txt in trilead.jar)", url: "http://www.trilead.com/SSH_Library/")
libraryLicense(name: "Twitter4J", libraryName: "twitter4j-core-4.0.4.jar", version: "4.0.4", license: "Apache 2.0", url: "http://twitter4j.org/", licenseUrl: "http://twitter4j.org/en/index.html#license")
libraryLicense(name: "Trove4j", version: "1.1 (with patches by JetBrains)", license: "LGPL", url: "http://trove4j.sourceforge.net/", licenseUrl: "http://trove4j.sourceforge.net/html/license.html")
libraryLicense(name: "Velocity", version: "1.7", license: "Apache 2.0", url: "http://velocity.apache.org/", licenseUrl: "http://velocity.apache.org/index.html")
libraryLicense(name: "Velocity", version: "1.7", license: "Apache 2.0", url: "http://velocity.apache.org/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0.txt")
libraryLicense(name: "winp", version: "1.23", license: "MIT", url: "http://java.net/projects/winp", licenseUrl: "http://opensource.org/licenses/mit-license.php")
libraryLicense(name: "Xalan", libraryName:"Xalan-2.7.1", version: "2.7.1", license: "Apache 2.0", url: "http://xml.apache.org/xalan-j/", licenseUrl: "http://xml.apache.org/xalan-j/")
libraryLicense(name: "Xerces", version: "2.11", license: "Apache 2.0", url: "http://xerces.apache.org/xerces2-j/", licenseUrl: "http://xerces.apache.org/xerces2-j/")
libraryLicense(name: "XML-RPC", libraryName: "XmlRPC", version: "2.0", license: "Apache 2.0", url: "http://ws.apache.org/xmlrpc/xmlrpc2/", licenseUrl: "http://ws.apache.org/xmlrpc/xmlrpc2/license.html")
libraryLicense(name: "XML Commons (xml-apis.jar, resolver.jar)", version: "", license: "Apache 2.0, W3C Software License , public domain", url: "http://xml.apache.org/commons/", licenseUrl: "http://xml.apache.org/commons/licenses.html")
libraryLicense(name: "XMLBeans", libraryName: "XmlBeans", version: "2.3.0", license: "Apache 2.0", url: "http://xmlbeans.apache.org/", licenseUrl: "http://svn.jetbrains.org/idea/Trunk/bundled/WebServices/resources/lib/xmlbeans-2.3.0/xmlbeans.LICENSE")
libraryLicense(name: "XStream", libraryName: "XStream", version: "1.4.2", license: "BSD License", url: "https://github.com/codehaus/xstream", licenseUrl: "http://xstream.codehaus.org/license.html")
libraryLicense(name: "XStream", version: "1.4.3", license: "BSD", url: "https://github.com/codehaus/xstream", licenseUrl: "http://xstream.codehaus.org/license.html")
libraryLicense(name: "XStream", libraryName: "XStream", version: "1.4.2", license: "BSD License", url: "https://github.com/codehaus/xstream", licenseUrl: "https://github.com/codehaus/xstream/blob/master/LICENSE.txt")
libraryLicense(name: "XStream", version: "1.4.3", license: "BSD", url: "https://github.com/codehaus/xstream", licenseUrl: "https://github.com/codehaus/xstream/blob/master/LICENSE.txt")
libraryLicense(name: "YourKit Java Profiler", libraryName: "yjp-controller-api-redist.jar", version: "8.0.x", license: "link (commercial license)", url: "http://yourkit.com/", licenseUrl: "http://www.yourkit.com/purchase/license.html")
jetbrainsLibrary("Coverage")
+1 -1
View File
@@ -4,7 +4,7 @@ import com.intellij.openapi.util.io.FileUtil
import static org.jetbrains.jps.idea.IdeaProjectLoader.guessHome
/*
* Copyright 2000-2015 JetBrains s.r.o.
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,10 +21,7 @@ import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.util.ArrayUtil;
import com.sun.jdi.Method;
import com.sun.jdi.ObjectCollectedException;
import com.sun.jdi.ThreadReference;
import com.sun.jdi.Value;
import com.sun.jdi.*;
import com.sun.jdi.event.Event;
import com.sun.jdi.event.MethodEntryEvent;
import com.sun.jdi.event.MethodExitEvent;
@@ -118,6 +115,9 @@ public class MethodReturnValueWatcher {
enableEntryWatching(false);
}
}
catch (VMDisconnectedException e) {
throw e;
}
catch (Exception e) {
LOG.error(e);
}
@@ -103,24 +103,26 @@ public class StackTraceLine {
final int dollarIndex = className.indexOf('$');
if (dollarIndex != -1) className = className.substring(0, dollarIndex);
PsiClass psiClass = findClass(project, className, lineNumber);
if (psiClass == null || (psiClass.getNavigationElement() instanceof PsiCompiledElement)) return null;
psiClass = (PsiClass)psiClass.getNavigationElement();
final PsiMethod psiMethod = getMethodAtLine(psiClass, methodName, lineNumber);
if (psiMethod != null) {
return new MethodLineLocation(project, psiMethod, PsiLocation.fromPsiElement(psiClass), lineNumber);
}
else {
return null;
PsiElement navElement = psiClass == null ? null : psiClass.getNavigationElement();
if (psiClass == null || navElement instanceof PsiCompiledElement) return null;
if (navElement instanceof PsiClass) {
final PsiMethod psiMethod = getMethodAtLine((PsiClass)navElement, methodName, lineNumber);
if (psiMethod != null) {
return new MethodLineLocation(project, psiMethod, PsiLocation.fromPsiElement((PsiClass)navElement), lineNumber);
}
}
return null;
}
private static PsiClass findClass(final Project project, final String className, final int lineNumber) {
if (project == null) return null;
final PsiManager psiManager = PsiManager.getInstance(project);
PsiClass psiClass = JavaPsiFacade.getInstance(psiManager.getProject()).findClass(className, GlobalSearchScope.allScope(project));
if (psiClass == null || (psiClass.getNavigationElement() instanceof PsiCompiledElement)) return null;
psiClass = (PsiClass)psiClass.getNavigationElement();
final PsiFile psiFile = psiClass.getContainingFile();
PsiElement navElement = psiClass == null ? null : psiClass.getNavigationElement();
if (psiClass == null || navElement instanceof PsiCompiledElement) return null;
final PsiFile psiFile = navElement.getContainingFile();
return PsiTreeUtil.getParentOfType(psiFile.findElementAt(offsetOfLine(psiFile, lineNumber)), PsiClass.class, false);
}
@@ -35,7 +35,6 @@ import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiClassImplUtil;
import com.intellij.psi.impl.PsiSuperMethodImplUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiShortNamesCache;
import com.intellij.psi.search.searches.ReferencesSearch;
@@ -442,36 +441,7 @@ public class GenericsHighlightUtil {
static HighlightInfo checkUnrelatedDefaultMethods(@NotNull PsiClass aClass,
@NotNull PsiIdentifier classIdentifier) {
final Map<MethodSignature, Set<PsiMethod>> overrideEquivalent =
new THashMap<MethodSignature, Set<PsiMethod>>(MethodSignatureUtil.METHOD_PARAMETERS_ERASURE_EQUALITY);
PsiClass[] supers = aClass.getSupers();
for (int i = 0; i < supers.length; i++) {
PsiClass superClass = supers[i];
boolean subType = false;
for (int j = 0; j < supers.length; j++) {
if (j == i) continue;
subType |= supers[j].isInheritor(supers[i], true);
}
if (subType) continue;
final PsiSubstitutor superClassSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, aClass, PsiSubstitutor.EMPTY);
for (HierarchicalMethodSignature hms : superClass.getVisibleSignatures()) {
final PsiMethod method = hms.getMethod();
if (MethodSignatureUtil.findMethodBySignature(aClass, method.getSignature(superClassSubstitutor), false) != null) continue;
final PsiClass containingClass = method.getContainingClass();
if (containingClass == null) continue;
final PsiSubstitutor containingClassSubstitutor = TypeConversionUtil.getClassSubstitutor(containingClass, aClass, PsiSubstitutor.EMPTY);
if (containingClassSubstitutor == null) continue;
final PsiSubstitutor finalSubstitutor =
PsiSuperMethodImplUtil.obtainFinalSubstitutor(containingClass, containingClassSubstitutor, hms.getSubstitutor(), false);
final MethodSignatureBackedByPsiMethod signature = MethodSignatureBackedByPsiMethod.create(method, finalSubstitutor, false);
Set<PsiMethod> methods = overrideEquivalent.get(signature);
if (methods == null) {
methods = new LinkedHashSet<PsiMethod>();
overrideEquivalent.put(signature, methods);
}
methods.add(method);
}
}
final Map<? extends MethodSignature, Set<PsiMethod>> overrideEquivalent = PsiSuperMethodUtil.collectOverrideEquivalents(aClass);
final boolean isInterface = aClass.isInterface();
for (Set<PsiMethod> overrideEquivalentMethods : overrideEquivalent.values()) {
@@ -550,7 +520,8 @@ public class GenericsHighlightUtil {
final PsiClass containingClass = method.getContainingClass();
if (containingClass == null) continue;
final PsiSubstitutor containingClassSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(containingClass, psiClass, PsiSubstitutor.EMPTY);
final PsiSubstitutor finalSubstitutor = PsiSuperMethodImplUtil.obtainFinalSubstitutor(containingClass, containingClassSubstitutor, hms.getSubstitutor(), false);
final PsiSubstitutor finalSubstitutor = PsiSuperMethodUtil
.obtainFinalSubstitutor(containingClass, containingClassSubstitutor, hms.getSubstitutor(), false);
final MethodSignatureBackedByPsiMethod signature = MethodSignatureBackedByPsiMethod.create(method, finalSubstitutor, false);
final PsiMethod foundMethod = overrideEquivalent.get(signature);
PsiClass foundMethodContainingClass;
@@ -32,10 +32,7 @@ import com.intellij.psi.controlFlow.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.RedundantCastUtil;
import com.intellij.psi.util.*;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.IntArrayList;
import org.jetbrains.annotations.Nls;
@@ -103,9 +100,9 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
final PsiStatement body = statement.getBody();
if (iteratedValue != null && body != null) {
final PsiType iteratedValueType = iteratedValue.getType();
if (InheritanceUtil.isInheritor(iteratedValueType, CommonClassNames.JAVA_UTIL_COLLECTION)) {
final PsiClass iteratorClass = PsiUtil.resolveClassInType(iteratedValueType);
LOG.assertTrue(iteratorClass != null);
final PsiClass iteratorClass = PsiUtil.resolveClassInType(iteratedValueType);
final PsiClass collectionClass = JavaPsiFacade.getInstance(body.getProject()).findClass(CommonClassNames.JAVA_UTIL_COLLECTION, statement.getResolveScope());
if (collectionClass != null && InheritanceUtil.isInheritorOrSelf(iteratorClass, collectionClass, true)) {
try {
final ControlFlow controlFlow = ControlFlowFactory.getInstance(holder.getProject())
.getControlFlow(body, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance());
@@ -124,8 +121,7 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
}
if (ExceptionUtil.getThrownCheckedExceptions(new PsiElement[] {body}).isEmpty()) {
if (!(iteratedValueType instanceof PsiClassType && ((PsiClassType)iteratedValueType).isRaw()) &&
isCollectCall(body, statement.getIterationParameter())) {
if (!isRawSubstitution(iteratedValueType, collectionClass) && isCollectCall(body, statement.getIterationParameter())) {
boolean addAll = isAddAllCall(statement, body);
holder.registerProblem(iteratedValue, "Can be replaced with " + (addAll ? "addAll call" : "collect call"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
@@ -151,6 +147,11 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
}
}
}
private boolean isRawSubstitution(PsiType iteratedValueType, PsiClass collectionClass) {
return iteratedValueType instanceof PsiClassType && PsiUtil
.isRawSubstitutor(collectionClass, TypeConversionUtil.getSuperClassSubstitutor(collectionClass, (PsiClassType)iteratedValueType));
}
};
}
@@ -115,7 +115,7 @@ public class SuspiciousMethodCallUtil {
argType = ((PsiPrimitiveType)argType).getBoxedType(methodCall);
}
if (!(argType instanceof PsiClassType)) return null;
if (argType == null) return null;
final JavaResolveResult resolveResult = methodExpression.advancedResolve(false);
PsiMethod calleeMethod = (PsiMethod)resolveResult.getElement();
@@ -216,11 +216,23 @@ public class LambdaUtil {
public static List<HierarchicalMethodSignature> findFunctionCandidates(PsiClass psiClass) {
if (psiClass != null && psiClass.isInterface() && !psiClass.isAnnotationType()) {
final List<HierarchicalMethodSignature> methods = new ArrayList<HierarchicalMethodSignature>();
final Map<MethodSignature, Set<PsiMethod>> overrideEquivalents = PsiSuperMethodUtil.collectOverrideEquivalents(psiClass);
final Collection<HierarchicalMethodSignature> visibleSignatures = psiClass.getVisibleSignatures();
for (HierarchicalMethodSignature signature : visibleSignatures) {
final PsiMethod psiMethod = signature.getMethod();
if (!psiMethod.hasModifierProperty(PsiModifier.ABSTRACT)) continue;
if (psiMethod.hasModifierProperty(PsiModifier.STATIC)) continue;
final Set<PsiMethod> equivalentMethods = overrideEquivalents.get(signature);
if (equivalentMethods != null && equivalentMethods.size() > 1) {
boolean hasNonAbstractOverrideEquivalent = false;
for (PsiMethod method : equivalentMethods) {
if (!method.hasModifierProperty(PsiModifier.ABSTRACT) && !MethodSignatureUtil.isSuperMethod(method, psiMethod)) {
hasNonAbstractOverrideEquivalent = true;
break;
}
}
if (hasNonAbstractOverrideEquivalent) continue;
}
if (!overridesPublicObjectMethod(signature)) {
methods.add(signature);
}
@@ -17,10 +17,13 @@ package com.intellij.psi.util;
import com.intellij.psi.*;
import com.intellij.util.containers.HashSet;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class PsiSuperMethodUtil {
@@ -80,4 +83,62 @@ public class PsiSuperMethodUtil {
return false;
}
@NotNull
public static PsiSubstitutor obtainFinalSubstitutor(@NotNull PsiClass superClass,
@NotNull PsiSubstitutor superSubstitutor,
@NotNull PsiSubstitutor derivedSubstitutor,
boolean inRawContext) {
if (inRawContext) {
Set<PsiTypeParameter> typeParams = superSubstitutor.getSubstitutionMap().keySet();
PsiElementFactory factory = JavaPsiFacade.getElementFactory(superClass.getProject());
superSubstitutor = factory.createRawSubstitutor(derivedSubstitutor, typeParams.toArray(new PsiTypeParameter[typeParams.size()]));
}
Map<PsiTypeParameter, PsiType> map = null;
for (PsiTypeParameter typeParameter : PsiUtil.typeParametersIterable(superClass)) {
PsiType type = superSubstitutor.substitute(typeParameter);
final PsiType t = derivedSubstitutor.substitute(type);
if (map == null) {
map = new THashMap<PsiTypeParameter, PsiType>();
}
map.put(typeParameter, t);
}
return map == null ? PsiSubstitutor.EMPTY : JavaPsiFacade.getInstance(superClass.getProject()).getElementFactory().createSubstitutor(map);
}
@NotNull
public static Map<MethodSignature, Set<PsiMethod>> collectOverrideEquivalents(@NotNull PsiClass aClass) {
final Map<MethodSignature, Set<PsiMethod>> overrideEquivalent =
new THashMap<MethodSignature, Set<PsiMethod>>(MethodSignatureUtil.METHOD_PARAMETERS_ERASURE_EQUALITY);
PsiClass[] supers = aClass.getSupers();
for (int i = 0; i < supers.length; i++) {
PsiClass superClass = supers[i];
boolean subType = false;
for (int j = 0; j < supers.length; j++) {
if (j == i) continue;
subType |= supers[j].isInheritor(supers[i], true);
}
if (subType) continue;
final PsiSubstitutor superClassSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, aClass, PsiSubstitutor.EMPTY);
for (HierarchicalMethodSignature hms : superClass.getVisibleSignatures()) {
final PsiMethod method = hms.getMethod();
if (MethodSignatureUtil.findMethodBySignature(aClass, method.getSignature(superClassSubstitutor), false) != null) continue;
final PsiClass containingClass = method.getContainingClass();
if (containingClass == null) continue;
final PsiSubstitutor containingClassSubstitutor = TypeConversionUtil.getClassSubstitutor(containingClass, aClass, PsiSubstitutor.EMPTY);
if (containingClassSubstitutor == null) continue;
final PsiSubstitutor finalSubstitutor =
obtainFinalSubstitutor(containingClass, containingClassSubstitutor, hms.getSubstitutor(), false);
final MethodSignatureBackedByPsiMethod signature = MethodSignatureBackedByPsiMethod.create(method, finalSubstitutor, false);
Set<PsiMethod> methods = overrideEquivalent.get(signature);
if (methods == null) {
methods = new LinkedHashSet<PsiMethod>();
overrideEquivalent.put(signature, methods);
}
methods.add(method);
}
}
return overrideEquivalent;
}
}
@@ -229,7 +229,7 @@ public class PsiSuperMethodImplUtil {
if (superClass == null) continue;
if (!visited.add(superClass)) continue; // cyclic inheritance
final PsiSubstitutor superSubstitutor = superTypeResolveResult.getSubstitutor();
PsiSubstitutor finalSubstitutor = obtainFinalSubstitutor(superClass, superSubstitutor, substitutor, isInRawContext);
PsiSubstitutor finalSubstitutor = PsiSuperMethodUtil.obtainFinalSubstitutor(superClass, superSubstitutor, substitutor, isInRawContext);
final boolean isInRawContextSuper = (isInRawContext || PsiUtil.isRawSubstitutor(superClass, superSubstitutor)) && superClass.getTypeParameters().length != 0;
Map<MethodSignature, HierarchicalMethodSignature> superResult = buildMethodHierarchy(superClass, nameHint, finalSubstitutor, false, visited, isInRawContextSuper, resolveScope);
@@ -373,29 +373,6 @@ public class PsiSuperMethodImplUtil {
return hierarchicalMethodSignature;
}
@NotNull
public static PsiSubstitutor obtainFinalSubstitutor(@NotNull PsiClass superClass,
@NotNull PsiSubstitutor superSubstitutor,
@NotNull PsiSubstitutor derivedSubstitutor,
boolean inRawContext) {
if (inRawContext) {
Set<PsiTypeParameter> typeParams = superSubstitutor.getSubstitutionMap().keySet();
PsiElementFactory factory = JavaPsiFacade.getElementFactory(superClass.getProject());
superSubstitutor = factory.createRawSubstitutor(derivedSubstitutor, typeParams.toArray(new PsiTypeParameter[typeParams.size()]));
}
Map<PsiTypeParameter, PsiType> map = null;
for (PsiTypeParameter typeParameter : PsiUtil.typeParametersIterable(superClass)) {
PsiType type = superSubstitutor.substitute(typeParameter);
final PsiType t = derivedSubstitutor.substitute(type);
if (map == null) {
map = new THashMap<PsiTypeParameter, PsiType>();
}
map.put(typeParameter, t);
}
return map == null ? PsiSubstitutor.EMPTY : JavaPsiFacade.getInstance(superClass.getProject()).getElementFactory().createSubstitutor(map);
}
@NotNull
public static Collection<HierarchicalMethodSignature> getVisibleSignatures(@NotNull PsiClass aClass) {
Map<MethodSignature, HierarchicalMethodSignature> map = getSignaturesMap(aClass);
@@ -130,6 +130,9 @@ public class PsiImmediateClassType extends PsiClassType.Stub {
if (substituted != null) {
lst.add(substituted);
}
else {
return PsiType.EMPTY_ARRAY;
}
}
return lst.toArray(createArray(lst.size()));
}
@@ -0,0 +1,12 @@
import java.util.*;
@FunctionalInterface
interface InfiniteIntIterator extends InfiniteIterator<Integer>, PrimitiveIterator.OfInt {}
@FunctionalInterface
interface InfiniteIterator<T> extends Iterator<T> {
@Override
default boolean hasNext() {
return true;
}
}
@@ -0,0 +1,19 @@
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Test {
public void validRedSquiggles(Stream<List<Integer>> stream) {
final Iterator<Integer> x = concat(stream
.map(cs -> cs.iterator())
.collect(Collectors.toList()).iterator());
final Iterator<Integer> x1 = concat(stream
.map(List::iterator)
.collect(Collectors.toList()).iterator());
}
public static <T> Iterator<T> concat(final Iterator<? extends Iterator<? extends T>> inputs) {
return null;
}
}
@@ -0,0 +1,20 @@
// "Replace with collect" "false"
import java.util.ArrayList;
import java.util.List;
class Main2 {
public static void main(String[] args) {
MyList list = new MyList();
List<Integer> integerList = new ArrayList<>();
for (Object element : li<caret>st) {
if (element instanceof Integer) {
integerList.add((Integer) element);
}
}
}
public static class MyList extends ArrayList {
}
}
@@ -0,0 +1,31 @@
import java.util.ArrayList;
import java.util.List;
class Main {
void suspicious(Object[][] data) {
List<String> stringList = new ArrayList<>();
stringList.remove(<warning descr="'List<String>' may not contain objects of type 'Object[][]'">data</warning>);
stringList.remove(<warning descr="'List<String>' may not contain objects of type 'Object[]'">data[0]</warning>);
stringList.remove(<warning descr="Suspicious call to 'List.remove'">data[0][0]</warning>);
stringList.contains(<warning descr="'List<String>' may not contain objects of type 'Object[][]'">data</warning>);
stringList.contains(<warning descr="'List<String>' may not contain objects of type 'Object[]'">data[0]</warning>);
stringList.contains(<warning descr="Suspicious call to 'List.contains'">data[0][0]</warning>);
M<? extends String> m = new M<>();
stringList.contains(m.get());
M<? super String> m1 = new M<>();
stringList.contains(<warning descr="Suspicious call to 'List.contains'">m1.get()</warning>);
M<?> m2 = new M<>();
stringList.contains(<warning descr="Suspicious call to 'List.contains'">m2.get()</warning>);
}
class M<T> {
public T get() {
return null;
}
}
}
@@ -30,6 +30,7 @@ public class Interface8MethodsHighlightingTest extends LightCodeInsightFixtureTe
public void testInheritUnrelatedDefaults() { doTest(true, false); }
public void testExtensionMethods() { doTest(false, false); }
public void testInheritDefaultMethodInInterface() { doTest(false, false); }
public void testCheckForFunctionalInterfaceCandidatesWhenOverrideEquivalentMethodsAreFoundInSuperInterfaces() { doTest(false, false);}
public void testStaticMethodsInFunctionalInterface() { doTest(false, false); }
public void testCyclicSubstitutor() { doTest(false, false); }
public void testThisAccessibility() { doTest(false, false); }
@@ -284,6 +284,10 @@ public class NewLambdaHighlightingTest extends LightDaemonAnalyzerTestCase {
doTest();
}
public void testIDEA153284() throws Exception {
doTest();
}
private void doTest() {
doTest(false);
}
@@ -29,6 +29,10 @@ public class SuspiciousCollectionMethodCallsTest extends LightCodeInsightFixture
doTest();
}
public void testNonClassArgTypes() throws Exception {
doTest();
}
@NotNull
@Override
protected LightProjectDescriptor getProjectDescriptor() {
@@ -384,13 +384,15 @@ public class JavaBuilder extends ModuleLevelBuilder {
}
final boolean rc;
if (!shouldForkCompilerProcess(context, chunkSdkVersion)) {
if (!shouldForkCompilerProcess(context, chunkSdkVersion, convertToNumber(getLanguageLevel(chunk.getModules().iterator().next())))) {
rc = JavacMain.compile(
options, files, classpath, _platformCp, sourcePath, outs, diagnosticSink, classesConsumer, context.getCancelStatus(), compilingTool
);
}
else {
// fork external javac
// fork external javac, compilers from SDK 1.6+ are supported
// todo: If chunkSDK is older than 1.6, we have to ask the user to specify a path to javac6+ to be used for compilation.
// todo: Add setting in compiler configuration for this.
final String sdkHome = getChunkSdkHome(chunk);
if (sdkHome == null) {
diagnosticSink.report(new PlainMessageDiagnostic(Diagnostic.Kind.ERROR, "Cannot start javac process for " + chunk.getName() + ": unknown JDK home path.\nPlease check project configuration."));
@@ -449,7 +451,7 @@ public class JavaBuilder extends ModuleLevelBuilder {
return null;
}
private static boolean shouldForkCompilerProcess(CompileContext context, final int chunkSdkVersion) {
private static boolean shouldForkCompilerProcess(CompileContext context, final int chunkSdkVersion, int chunkLanguageLevel) {
final int compilerSdkVersion = getCompilerSdkVersion(context);
if (compilerSdkVersion < 9 || chunkSdkVersion < 0) {
// javac up to version 9 supports all previous releases
@@ -461,10 +463,13 @@ public class JavaBuilder extends ModuleLevelBuilder {
// there is no way to specify full platform classpath for cross-compilation purposes.
// We have for fork compiler process with corresponding SDK runtime to ensure that compiler resolves platform classes
// against the SDK version specified for the given chunk.
// todo: if chunkSdkVersion complies to "one plus three back" rule, and "-release" option is supported, return false
return true;
}
// according to JEP 182: Retiring javac "one plus three back" policy
return Math.abs(compilerSdkVersion - chunkSdkVersion) > 3;
// compilerSdkVersion is 9+ here, so applying JEP 182 "Retiring javac 'one plus three back'" policy
final int requestedTargetPlatformVersion = chunkLanguageLevel > 0 ? chunkLanguageLevel : Math.min(chunkLanguageLevel, chunkSdkVersion);
return Math.abs(compilerSdkVersion - requestedTargetPlatformVersion) > 3;
}
// If platformCp of the build process is the same as the target plafform, do not specify platformCp explicitly
@@ -19,6 +19,7 @@ import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Ref;
import com.intellij.util.ThrowableRunnable;
import org.jetbrains.annotations.NotNull;
/**
@@ -30,7 +31,9 @@ import org.jetbrains.annotations.NotNull;
* and process UI events in other ways: it's guaranteed that no one will be able to sneak in with an unexpected model change using
* {@link javax.swing.SwingUtilities#invokeLater(Runnable)} or analogs.<p/>
*
* Transactions are run on UI thread. They have read access by default. All write actions should be performed inside a transaction.<p/>
* Transactions are run on UI thread. They have read access by default. All write actions that don't happen as the result of direct user input
* should be performed inside a transaction. No write action should be performed from within an {@code invokeLater}-like call
* unless wrapped into a transaction.<p/>
*
* The recommended way to perform a transaction is to invoke {@link #submitTransaction(Runnable)}. It either runs the transaction immediately
* (if on UI thread and there's no other transaction running) or queues it to invoke at some later moment, when it becomes possible.<p/>
@@ -192,4 +195,13 @@ public abstract class TransactionGuard {
* @param errorMessage the message that will be logged if current transaction status differs from the expected one
*/
public abstract void assertInsideTransaction(boolean transactionRequired, @NotNull String errorMessage);
/**
* Executes the given code and marks it as a user activity, to allow write actions to be run without requiring transactions.
* Please note that only direct keyboard/mouse event processing can be wrapped in such calls. If you wish to invoke some actionPerformed,
* please consider using {@code ActionManager.tryToExecute()} instead, or ensure in some other way that the action is enabled
* and can be invoked in the current modality state.
*/
public abstract <T extends Throwable> void performUserActivity(ThrowableRunnable<T> activity) throws T;
}
@@ -18,7 +18,9 @@ package com.intellij.openapi.application;
import com.intellij.openapi.diagnostic.Attachment;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.util.ThrowableRunnable;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
@@ -37,13 +39,14 @@ public class TransactionGuardImpl extends TransactionGuard {
private final Set<TransactionKind> myMergeableKinds = ContainerUtil.newHashSet();
private String myTransactionStartTrace;
private ModalityState myTransactionModality;
private boolean myUserActivity;
@Override
@NotNull
public AccessToken startSynchronousTransaction(@NotNull TransactionKind kind) throws IllegalStateException {
ModalityState modality = ModalityState.current();
if (isInsideTransaction()) {
if (modality.equals(myTransactionModality)) {
if (modality.equals(myTransactionModality) || myUserActivity) {
return AccessToken.EMPTY_ACCESS_TOKEN;
}
@@ -200,4 +203,39 @@ public class TransactionGuardImpl extends TransactionGuard {
throw new RuntimeException(exception[0]);
}
}
@Override
public <T extends Throwable> void performUserActivity(ThrowableRunnable<T> activity) throws T {
ApplicationManager.getApplication().assertIsDispatchThread();
AccessToken token = startActivity(true);
try {
activity.run();
}
finally {
token.finish();
}
}
/**
* An absolutely guru method, only intended to be used from Swing event processing. Please consult Peter if you think you need to invoke this.
*/
@NotNull
public AccessToken startActivity(boolean userActivity) {
if (myUserActivity == userActivity) {
return AccessToken.EMPTY_ACCESS_TOKEN;
}
final boolean prev = myUserActivity;
myUserActivity = userActivity;
return new AccessToken() {
@Override
public void finish() {
myUserActivity = prev;
}
};
}
public boolean isWriteActionAllowed() {
return !Registry.is("ide.require.transaction.for.model.changes", false) || isInsideTransaction() || myUserActivity;
}
}
@@ -385,7 +385,11 @@ public class UnifiedDiffViewer extends ListenerDiffViewerBase {
myFoldingModel.updateContext(myRequest, getFoldingModelSettings());
clearDiffPresentation();
if (isContentsEqual) myPanel.addNotification(DiffNotifications.createEqualContents());
if (isContentsEqual) {
boolean equalCharsets = TextDiffViewerUtil.areEqualCharsets(getContents());
boolean equalSeparators = TextDiffViewerUtil.areEqualLineSeparators(getContents());
myPanel.addNotification(DiffNotifications.createEqualContents(equalCharsets, equalSeparators));
}
TIntFunction separatorLines = myFoldingModel.getLineNumberConvertor();
myEditor.getGutterComponentEx().setLineNumberConvertor(mergeConverters(data.getLineConvertor1(), separatorLines),
@@ -19,6 +19,7 @@ import com.intellij.diff.DiffContext;
import com.intellij.diff.actions.BufferedLineIterator;
import com.intellij.diff.actions.NavigationContextChecker;
import com.intellij.diff.comparison.DiffTooBigException;
import com.intellij.diff.contents.DocumentContent;
import com.intellij.diff.fragments.LineFragment;
import com.intellij.diff.requests.ContentDiffRequest;
import com.intellij.diff.requests.DiffRequest;
@@ -52,6 +53,7 @@ import org.jetbrains.annotations.*;
import javax.swing.*;
import java.awt.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Iterator;
@@ -237,7 +239,11 @@ public class SimpleDiffViewer extends TwosideTextDiffViewer {
clearDiffPresentation();
myIsContentsEqual = data.isContentsEqual();
if (data.isContentsEqual()) myPanel.addNotification(DiffNotifications.createEqualContents());
if (data.isContentsEqual()) {
boolean equalCharsets = TextDiffViewerUtil.areEqualCharsets(getContents());
boolean equalSeparators = TextDiffViewerUtil.areEqualLineSeparators(getContents());
myPanel.addNotification(DiffNotifications.createEqualContents(equalCharsets, equalSeparators));
}
if (data.getFragments() != null) {
for (LineFragment fragment : data.getFragments()) {
@@ -26,13 +26,6 @@ import javax.swing.*;
import java.awt.*;
public class DiffNotifications {
@Deprecated @NotNull public static final JPanel INSERTED_CONTENT = createInsertedContent();
@Deprecated @NotNull public static final JPanel REMOVED_CONTENT = createRemovedContent();
@Deprecated @NotNull public static final JPanel EQUAL_CONTENTS = createEqualContents();
@Deprecated @NotNull public static final JPanel ERROR = createError();
@Deprecated @NotNull public static final JPanel OPERATION_CANCELED = createOperationCanceled();
@Deprecated @NotNull public static final JPanel DIFF_TOO_BIG = createDiffTooBig();
@NotNull
public static JPanel createInsertedContent() {
return createNotification("Content added", TextDiffType.INSERTED.getColor(null));
@@ -45,6 +38,20 @@ public class DiffNotifications {
@NotNull
public static JPanel createEqualContents() {
return createEqualContents(true, true);
}
@NotNull
public static JPanel createEqualContents(boolean equalCharsets, boolean equalSeparators) {
if (!equalCharsets && !equalSeparators) {
return createNotification(DiffBundle.message("diff.contents.have.differences.only.in.charset.and.line.separators.message.text"));
}
if (!equalSeparators) {
return createNotification(DiffBundle.message("diff.contents.have.differences.only.in.line.separators.message.text"));
}
if (!equalCharsets) {
return createNotification(DiffBundle.message("diff.contents.have.differences.only.in.charset.message.text"));
}
return createNotification(DiffBundle.message("diff.contents.are.identical.message.text"));
}
@@ -18,6 +18,7 @@ package com.intellij.diff.tools.util.base;
import com.intellij.diff.DiffContext;
import com.intellij.diff.contents.DiffContent;
import com.intellij.diff.contents.DocumentContent;
import com.intellij.diff.contents.EmptyContent;
import com.intellij.diff.requests.ContentDiffRequest;
import com.intellij.diff.tools.util.FoldingModelSupport;
import com.intellij.diff.tools.util.base.TextDiffSettingsHolder.TextDiffSettings;
@@ -38,6 +39,7 @@ import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Key;
import com.intellij.ui.ToggleActionButton;
import com.intellij.util.EditorPopupHandler;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
@@ -127,6 +129,25 @@ public class TextDiffViewerUtil {
}
}
public static boolean areEqualLineSeparators(@NotNull List<? extends DiffContent> contents) {
return areEqualDocumentContentProperties(contents, DocumentContent::getLineSeparator);
}
public static boolean areEqualCharsets(@NotNull List<? extends DiffContent> contents) {
return areEqualDocumentContentProperties(contents, DocumentContent::getCharset);
}
private static <T> boolean areEqualDocumentContentProperties(@NotNull List<? extends DiffContent> contents,
@NotNull Function<DocumentContent, T> propertyGetter) {
List<T> properties = ContainerUtil.mapNotNull(contents, (content) -> {
if (content instanceof EmptyContent) return null;
return propertyGetter.fun((DocumentContent)content);
});
if (properties.size() < 2) return true;
return ContainerUtil.newHashSet(properties).size() == 1;
}
//
// Actions
//
@@ -36,6 +36,7 @@ import com.intellij.diff.requests.ContentDiffRequest;
import com.intellij.diff.requests.DiffRequest;
import com.intellij.diff.tools.util.base.HighlightPolicy;
import com.intellij.diff.tools.util.base.IgnorePolicy;
import com.intellij.diff.tools.util.base.TextDiffViewerUtil;
import com.intellij.icons.AllIcons;
import com.intellij.lang.Language;
import com.intellij.openapi.actionSystem.AnAction;
@@ -98,6 +99,8 @@ import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import static com.intellij.diff.tools.util.base.TextDiffViewerUtil.areEqualLineSeparators;
public class DiffUtil {
private static final Logger LOG = Logger.getInstance(DiffUtil.class);
@@ -376,23 +379,8 @@ public class DiffUtil {
List<DiffContent> contents = request.getContents();
List<String> titles = request.getContentTitles();
List<Charset> charsets = ContainerUtil.map(contents, new Function<DiffContent, Charset>() {
@Override
public Charset fun(DiffContent content) {
if (content instanceof EmptyContent) return null;
return ((DocumentContent)content).getCharset();
}
});
List<LineSeparator> separators = ContainerUtil.map(contents, new Function<DiffContent, LineSeparator>() {
@Override
public LineSeparator fun(DiffContent content) {
if (content instanceof EmptyContent) return null;
return ((DocumentContent)content).getLineSeparator();
}
});
boolean equalCharsets = isEqualElements(charsets);
boolean equalSeparators = isEqualElements(separators);
boolean equalCharsets = TextDiffViewerUtil.areEqualCharsets(contents);
boolean equalSeparators = TextDiffViewerUtil.areEqualLineSeparators(contents);
List<JComponent> result = new ArrayList<JComponent>(contents.size());
@@ -421,20 +409,6 @@ public class DiffUtil {
return createStackedComponents(components, TITLE_GAP);
}
private static boolean isEqualElements(@NotNull List elements) {
for (int i = 0; i < elements.size(); i++) {
for (int j = i + 1; j < elements.size(); j++) {
if (!isEqualElements(elements.get(i), elements.get(j))) return false;
}
}
return true;
}
private static boolean isEqualElements(@Nullable Object element1, @Nullable Object element2) {
if (element1 == null || element2 == null) return true;
return element1.equals(element2);
}
@Nullable
private static JComponent createTitle(@NotNull String title,
@NotNull DiffContent content,
+1 -1
View File
@@ -20,6 +20,6 @@
<orderEntry type="module" module-name="lang-impl" />
<orderEntry type="module" module-name="dvcs-api" />
<orderEntry type="module" module-name="testFramework" scope="TEST" />
<orderEntry type="library" name="mockito" level="project" />
<orderEntry type="library" scope="TEST" name="mockito" level="project" />
</component>
</module>
@@ -22,37 +22,38 @@ import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.ContainerUtil
import com.intellij.vcsUtil.VcsImplUtil.getShortVcsRootName
class MultiRootMessage(private val myProject: Project, private val myAllRoots: Collection<VirtualFile>) {
class MultiRootMessage(private val project: Project, private val allRoots: Collection<VirtualFile>, html: Boolean) {
private val LOG = Logger.getInstance(MultiRootMessage::class.java)
private val myMessages = ContainerUtil.newLinkedHashMap<VirtualFile, String>()
private val messages = ContainerUtil.newLinkedHashMap<VirtualFile, String>()
private val lineSeparator = if (html) "<br/>\n" else "\n"
fun append(root: VirtualFile, message: String): MultiRootMessage {
if (!myAllRoots.contains(root)) {
LOG.error("The root ${root.path} is unexpected: $myAllRoots")
if (!allRoots.contains(root)) {
LOG.error("The root ${root.path} is unexpected: $allRoots")
return this
}
if (myMessages.containsKey(root)) {
if (messages.containsKey(root)) {
LOG.error("Duplicate root ${root.path} reporting message [$message]")
}
myMessages.put(root, message)
messages.put(root, message)
return this
}
fun asString(): String {
if (myMessages.isEmpty()) return "";
if (myAllRoots.size == 1) return myMessages.values.first()
if (myMessages.size == 1) {
val (root, message) = myMessages.entries.first()
return "$message in ${getShortVcsRootName(myProject, root)}"
if (messages.isEmpty()) return "";
if (allRoots.size == 1) return messages.values.first()
if (messages.size == 1) {
val (root, message) = messages.entries.first()
return "$message in ${getShortVcsRootName(project, root)}"
}
val grouped = myMessages.keys.groupBy { myMessages[it]!!.trim() }
if (grouped.size == 1 && myAllRoots.size == myMessages.size) return myMessages.values.first()
return grouped.keys.joinToString("\n") {
val shortRootNames = grouped[it]!!.map { getShortVcsRootName(myProject, it) }
val grouped = messages.keys.groupBy { messages[it]!!.trim() }
if (grouped.size == 1 && allRoots.size == messages.size) return messages.values.first()
return grouped.keys.joinToString(lineSeparator) {
val shortRootNames = grouped[it]!!.map { getShortVcsRootName(project, it) }
"$it in ${joinWithAnd(shortRootNames, 5)}" }
}
override fun toString(): String {
return myMessages.toString()
return messages.toString()
}
}
@@ -15,24 +15,23 @@
*/
package com.intellij.dvcs.push.ui;
import com.intellij.openapi.editor.SpellCheckingEditorCustomizationProvider;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.project.Project;
import com.intellij.ui.EditorCustomization;
import com.intellij.ui.TextFieldWithAutoCompletion;
import com.intellij.ui.TextFieldWithAutoCompletionListProvider;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.textCompletion.DefaultTextCompletionValueDescriptor;
import com.intellij.util.textCompletion.TextCompletionProvider;
import com.intellij.util.textCompletion.TextFieldWithCompletion;
import com.intellij.util.textCompletion.ValuesCompletionProvider;
import com.intellij.util.textCompletion.ValuesCompletionProvider.ValuesCompletionProviderDumbAware;
import org.jetbrains.annotations.NotNull;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.util.List;
public class PushTargetTextField extends TextFieldWithAutoCompletion<String> {
public PushTargetTextField(@NotNull Project project, @NotNull final List<String> targetVariants, @NotNull String defaultTargetName) {
super(project, getCompletionProvider(targetVariants), true, defaultTargetName);
setOneLineMode(true);
public class PushTargetTextField extends TextFieldWithCompletion {
public PushTargetTextField(@NotNull Project project, @NotNull List<String> targetVariants, @NotNull String defaultTargetName) {
super(project, getCompletionProvider(targetVariants), defaultTargetName, true, true, true);
addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
@@ -46,28 +45,17 @@ public class PushTargetTextField extends TextFieldWithAutoCompletion<String> {
});
}
@Override
protected EditorEx createEditor() {
// editor created lazy, so we need to update editor customization after initialization
EditorEx editorEx = super.createEditor();
EditorCustomization customization = SpellCheckingEditorCustomizationProvider.getInstance().getDisabledCustomization();
if (customization != null) {
customization.customize(editorEx);
}
return editorEx;
}
@Override
protected void updateBorder(@NotNull final EditorEx editor) {
}
@NotNull
private static TextFieldWithAutoCompletionListProvider<String> getCompletionProvider(@NotNull final List<String> targetVariants) {
return new StringsCompletionProvider(targetVariants, null) {
private static TextCompletionProvider getCompletionProvider(@NotNull final List<String> targetVariants) {
return new ValuesCompletionProviderDumbAware<>(new DefaultTextCompletionValueDescriptor.StringValueDescriptor() {
@Override
public int compare(String item1, String item2) {
return Integer.valueOf(ContainerUtil.indexOf(targetVariants, item1)).compareTo(ContainerUtil.indexOf(targetVariants, item2));
}
};
}, targetVariants);
}
}
@@ -24,48 +24,49 @@ import org.junit.Before
import org.junit.Test
import org.mockito.Mockito
import org.mockito.Mockito.mock
import java.io.File
class MultiRootMessageTest {
private lateinit var myProject : Project
private lateinit var project: Project
@Before
fun setUp() {
myProject = mock(Project::class.java)
Mockito.`when`(myProject.baseDir).thenReturn(MockVirtualFile(true, "idea"))
project = mock(Project::class.java)
Mockito.`when`(project.baseDir).thenReturn(MockVirtualFile(true, "idea"))
}
@Test
fun `test empty message`() {
val root = myProject.baseDir
val multiRootMessage = MultiRootMessage(myProject, setOf(root))
val root = project.baseDir
val multiRootMessage = multiRootMessage(root)
assertTrue(multiRootMessage.asString().isEmpty())
}
@Test
fun `test single repository`() {
val root = myProject.baseDir
val multiRootMessage = MultiRootMessage(myProject, setOf(root))
val root = project.baseDir
val multiRootMessage = multiRootMessage(root)
multiRootMessage.append(root, "Pruned obsolete remote references: origin/fix1, origin/fix2")
assertEquals("Pruned obsolete remote references: origin/fix1, origin/fix2", multiRootMessage.asString())
}
@Test
fun `test single root message in multi-root project`() {
val idea = myProject.baseDir
val idea = project.baseDir
val community = createSubDir(idea, "community")
val multiRootMessage = MultiRootMessage(myProject, setOf(idea, community))
val multiRootMessage = multiRootMessage(idea, community)
multiRootMessage.append(idea, "Pruned obsolete remote references: origin/fix1, origin/fix2")
assertEquals("Pruned obsolete remote references: origin/fix1, origin/fix2 in idea", multiRootMessage.asString())
}
@Test
fun `test two roots with same messages`() {
val idea = myProject.baseDir
val idea = project.baseDir
val community = createSubDir(idea, "community")
val multiRootMessage = MultiRootMessage(myProject, setOf(idea, community))
val multiRootMessage = multiRootMessage(idea, community)
multiRootMessage.append(idea, "Pruned obsolete remote references: origin/fix1, origin/fix2")
multiRootMessage.append(community, "Pruned obsolete remote references: origin/fix1, origin/fix2")
assertEquals("Pruned obsolete remote references: origin/fix1, origin/fix2", multiRootMessage.asString())
@@ -73,10 +74,10 @@ class MultiRootMessageTest {
@Test
fun `test two roots with different messages`() {
val idea = myProject.baseDir
val idea = project.baseDir
val community = createSubDir(idea, "community")
val multiRootMessage = MultiRootMessage(myProject, setOf(idea, community))
val multiRootMessage = multiRootMessage(idea, community)
multiRootMessage.append(idea, "Pruned obsolete remote references: origin/fix1, origin/fix2")
multiRootMessage.append(community, "Pruned obsolete remote references: origin/fix3")
assertEquals(
@@ -87,24 +88,26 @@ class MultiRootMessageTest {
}
@Test
fun `test three roots with same message, and one root with another`() {
val idea = myProject.baseDir
fun `test html message for three roots with same message, and one root with another`() {
val idea = project.baseDir
val community = createSubDir(idea, "community")
val contrib = createSubDir(idea, "contrib")
val android = createSubDir(community, "android")
val multiRootMessage = MultiRootMessage(myProject, setOf(idea, community, contrib, android))
val multiRootMessage = MultiRootMessage(project, setOf(idea, community, contrib, android), true)
multiRootMessage.append(idea, "Pruned obsolete remote references: origin/fix1, origin/fix2")
multiRootMessage.append(community, "Pruned obsolete remote references: origin/fix3")
multiRootMessage.append(contrib, "Pruned obsolete remote references: origin/fix3")
multiRootMessage.append(android, "Pruned obsolete remote references: origin/fix3")
assertEquals(
"""
Pruned obsolete remote references: origin/fix1, origin/fix2 in idea
Pruned obsolete remote references: origin/fix3 in community, contrib and community/android
Pruned obsolete remote references: origin/fix1, origin/fix2 in idea<br/>
Pruned obsolete remote references: origin/fix3 in community, contrib and community${File.separator}android
""".trimIndent(), multiRootMessage.asString())
}
private fun multiRootMessage(vararg roots : VirtualFile) = MultiRootMessage(project, roots.asList(), false)
private fun createSubDir(parent: VirtualFile, name: String): VirtualFile {
val vf = MockVirtualFile(true, name)
vf.parent = parent
@@ -8,21 +8,21 @@ final class DaltonizationFilter extends WeightFilter {
public static final ImageFilter tritanopia = forTritanopia(null);
public static ImageFilter forProtanopia(Double weight) {
return new DaltonizationFilter(weight, 0, 2.02344, -2.52581, 0, 1, 0, 0, 0, 1);
return new DaltonizationFilter("Protanopia", weight, 0, 2.02344, -2.52581, 0, 1, 0, 0, 0, 1);
}
public static ImageFilter forDeuteranopia(Double weight) {
return new DaltonizationFilter(weight, 1, 0, 0, 0.494207, 0, 1.24827, 0, 0, 1);
return new DaltonizationFilter("Deuteranopia", weight, 1, 0, 0, 0.494207, 0, 1.24827, 0, 0, 1);
}
public static ImageFilter forTritanopia(Double weight) {
return new DaltonizationFilter(weight, 1, 0, 0, 0, 1, 0, -0.395913, 0.801109, 0);
return new DaltonizationFilter("Tritanopia", weight, 1, 0, 0, 0, 1, 0, -0.395913, 0.801109, 0);
}
private final double[] myMatrix;
private DaltonizationFilter(Double weight, double... matrix) {
super(weight);
private DaltonizationFilter(String name, Double weight, double... matrix) {
super(name + " (daltonization)", weight);
myMatrix = matrix;
}
@@ -46,12 +46,9 @@ final class DaltonizationFilter extends WeightFilter {
B = srcB - B;
// Shift colors towards visible spectrum (apply error modifications)
// and add compensation to original values
double dstR = srcR + (0.0 * R) + (0.0 * G) + (0.0 * B);
double dstG = srcG + (0.7 * R) + (1.0 * G) + (0.0 * B);
double dstB = srcB + (0.7 * R) + (0.0 * G) + (1.0 * B);
return toRGB(srcR, srcG, srcB,
dstR < 0 ? 0 : dstR > 255 ? 255 : dstR,
dstR < 0 ? 0 : dstR > 255 ? 255 : dstG,
dstR < 0 ? 0 : dstR > 255 ? 255 : dstB);
double dstR = fix(srcR + (0.0 * R) + (0.0 * G) + (0.0 * B));
double dstG = fix(srcG + (0.7 * R) + (1.0 * G) + (0.0 * B));
double dstB = fix(srcB + (0.7 * R) + (0.0 * G) + (1.0 * B));
return toRGB(srcR, srcG, srcB, dstR, dstG, dstB);
}
}
@@ -9,19 +9,19 @@ final class SimulationFilter extends WeightFilter {
public static final ImageFilter achromatopsia = forAchromatopsia(null);
public static ImageFilter forProtanopia(Double weight) {
return new SimulationFilter(weight, 0.7465, 0.2535, 1.273463, -0.073894);
return new SimulationFilter("Protanopia", weight, 0.7465, 0.2535, 1.273463, -0.073894);
}
public static ImageFilter forDeuteranopia(Double weight) {
return new SimulationFilter(weight, 1.4, -0.4, 0.968437, 0.003331);
return new SimulationFilter("Deuteranopia", weight, 1.4, -0.4, 0.968437, 0.003331);
}
public static ImageFilter forTritanopia(Double weight) {
return new SimulationFilter(weight, 0.1748, 0, 0.062921, 0.292119);
return new SimulationFilter("Tritanopia", weight, 0.1748, 0, 0.062921, 0.292119);
}
public static ImageFilter forAchromatopsia(Double weight) {
return new WeightFilter(weight) {
return new WeightFilter("Achromatopsia (simulation)", weight) {
@Override
int toRGB(int srcR, int srcG, int srcB) {
double gray = 0.212656 * srcR + 0.715158 * srcG + 0.072186 * srcB;
@@ -35,8 +35,8 @@ final class SimulationFilter extends WeightFilter {
private final double myConfuseM;
private final double myConfuseYint;
private SimulationFilter(Double weight, double x, double y, double m, double yint) {
super(weight);
private SimulationFilter(String name, Double weight, double x, double y, double m, double yint) {
super(name + " (simulation)", weight);
myConfuseX = x;
myConfuseY = y;
myConfuseM = m;
@@ -85,9 +85,9 @@ final class SimulationFilter extends WeightFilter {
double fitG = ((dstG < 0 ? 0 : 1) - dstG) / diffG;
double fitB = ((dstB < 0 ? 0 : 1) - dstB) / diffB;
double adjust = Math.max(Math.max( // highest value
(fitR < 0 || 1 < fitR) ? 0 : fitR,
(fitG < 0 || 1 < fitG) ? 0 : fitG),
(fitB < 0 || 1 < fitB) ? 0 : fitB);
(fitR < 0 || 1 < fitR) ? 0 : fitR,
(fitG < 0 || 1 < fitG) ? 0 : fitG),
(fitB < 0 || 1 < fitB) ? 0 : fitB);
// Shift proportional to the greatest shift
dstR += adjust * diffR;
dstG += adjust * diffG;
@@ -3,16 +3,26 @@ package com.intellij.ide.ui;
import java.awt.image.RGBImageFilter;
abstract class WeightFilter extends RGBImageFilter {
private final String myName;
private final Double myWeight;
WeightFilter(Double weight) {
if (weight != null && (weight < 0 || 1 < weight)) {
throw new IllegalArgumentException("weight " + weight + " out of [0..1]");
WeightFilter(String name, Double weight) {
if (weight != null) {
if (weight < 0 || 1 < weight) {
throw new IllegalArgumentException("weight " + weight + " out of [0..1]");
}
name = name + " weight: " + weight;
}
myName = name;
myWeight = weight;
canFilterIndexColorModel = true;
}
@Override
public String toString() {
return myName;
}
@Override
public final int filterRGB(int x, int y, int rgb) {
return (0xFF000000 & rgb) | toRGB(0xFF & (rgb >> 16), 0xFF & (rgb >> 8), 0xFF & rgb);
@@ -34,4 +44,8 @@ abstract class WeightFilter extends RGBImageFilter {
srcB = (int)dstB;
return (srcR << 16) | (srcG << 8) | srcB;
}
static double fix(double value) {
return Double.isNaN(value) || value < 0 ? 0 : value > 255 ? 255 : value;
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.application.options;
import com.intellij.util.ui.JBUI;
/**
* @author Konstantin Bulenkov
*/
public class EditorFontsConstants {
public static int getMinEditorFontSize() {return JBUI.scale(4);}
public static int getMaxEditorFontSize() {return JBUI.scale(40);}
public static int getDefaultEditorFontSize() {return JBUI.scale(12);}
public static float getMinEditorLineSpacing() {return JBUI.scale(.6F);}
public static float getMaxEditorLineSpacing() {return JBUI.scale(3f);}
public static float getDefaultEditorLineSpacing() {return JBUI.scale(1f);}
public static int checkAndFixEditorFontSize(int size) {
return round(getMinEditorFontSize(), getMaxEditorFontSize(), size);
}
public static float checkAndFixEditorLineSpacing(int size) {
return round(getMinEditorLineSpacing(), getMaxEditorLineSpacing(), size);
}
private static int round(int min, int max, int val) {
return val < min ? min : val > max ? max : val;
}
private static float round(float min, float max, float val) {
return val < min ? min : val > max ? max : val;
}
private EditorFontsConstants() {
}
}
@@ -19,6 +19,7 @@
*/
package com.intellij.openapi.editor.colors.impl;
import com.intellij.application.options.EditorFontsConstants;
import com.intellij.ide.ui.ColorBlindness;
import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.editor.HighlighterColors;
@@ -173,6 +174,7 @@ public abstract class AbstractColorsScheme implements EditorColorsScheme {
@Override
public void setEditorFontSize(int fontSize) {
fontSize = EditorFontsConstants.checkAndFixEditorFontSize(fontSize);
myFontPreferences.register(getEditorFontName(), fontSize);
initFonts();
}
@@ -707,6 +709,7 @@ public abstract class AbstractColorsScheme implements EditorColorsScheme {
@Override
public void setConsoleFontSize(int fontSize) {
fontSize = EditorFontsConstants.checkAndFixEditorFontSize(fontSize);
myConsoleFontPreferences.register(getConsoleFontName(), fontSize);
initFonts();
}
@@ -79,7 +79,7 @@ public abstract class SettingsConnectionService {
LOG.error(e);
}
return settings;
}, Collections.emptyMap(), LOG);
}, Collections.<String, String>emptyMap(), LOG);
}
@Nullable
@@ -16,7 +16,7 @@
package com.intellij.application.options.colors;
import com.intellij.application.options.OptionsConstants;
import com.intellij.application.options.EditorFontsConstants;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.ui.AntialiasingType;
import com.intellij.ide.ui.UISettings;
@@ -161,7 +161,7 @@ public class FontOptions extends JPanel implements OptionsPanel{
try {
int value = Integer.parseInt(myEditorFontSizeField.getText());
value += (up ? 1 : -1);
value = Math.min(OptionsConstants.MAX_EDITOR_FONT_SIZE, Math.max(OptionsConstants.MIN_EDITOR_FONT_SIZE, value));
value = Math.min(EditorFontsConstants.getMaxEditorFontSize(), Math.max(EditorFontsConstants.getMinEditorFontSize(), value));
myEditorFontSizeField.setText(String.valueOf(value));
}
catch (NumberFormatException ignored) {
@@ -188,7 +188,7 @@ public class FontOptions extends JPanel implements OptionsPanel{
try {
float value = Float.parseFloat(myLineSpacingField.getText());
value += (up ? 1 : -1) * .1F;
value = Math.min(OptionsConstants.MAX_EDITOR_LINE_SPACING, Math.max(OptionsConstants.MIN_EDITOR_LINE_SPACING, value));
value = Math.min(EditorFontsConstants.getMaxEditorLineSpacing(), Math.max(EditorFontsConstants.getMinEditorLineSpacing(), value));
myLineSpacingField.setText(String.format(Locale.ENGLISH, "%.1f", value));
}
catch (NumberFormatException ignored) {
@@ -200,19 +200,19 @@ public class FontOptions extends JPanel implements OptionsPanel{
private int getFontSizeFromField() {
try {
return Math.min(OptionsConstants.MAX_EDITOR_FONT_SIZE,
Math.max(OptionsConstants.MIN_EDITOR_FONT_SIZE, Integer.parseInt(myEditorFontSizeField.getText())));
return Math.min(EditorFontsConstants.getMaxEditorFontSize(),
Math.max(EditorFontsConstants.getMinEditorFontSize(), Integer.parseInt(myEditorFontSizeField.getText())));
}
catch (NumberFormatException e) {
return OptionsConstants.DEFAULT_EDITOR_FONT_SIZE;
return EditorFontsConstants.getDefaultEditorFontSize();
}
}
private float getLineSpacingFromField() {
try {
return Math.min(OptionsConstants.MAX_EDITOR_LINE_SPACING, Math.max(OptionsConstants.MIN_EDITOR_LINE_SPACING, Float.parseFloat(myLineSpacingField.getText())));
return Math.min(EditorFontsConstants.getMaxEditorLineSpacing(), Math.max(EditorFontsConstants.getMinEditorLineSpacing(), Float.parseFloat(myLineSpacingField.getText())));
} catch (NumberFormatException e){
return OptionsConstants.DEFAULT_EDITOR_LINE_SPACING;
return EditorFontsConstants.getDefaultEditorLineSpacing();
}
}
@@ -15,6 +15,7 @@
*/
package com.intellij.codeInsight.template.postfix.templates;
import com.intellij.ide.plugins.cl.PluginClassLoader;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageExtension;
import com.intellij.openapi.diagnostic.Logger;
@@ -22,7 +23,7 @@ import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Set;
import java.util.Map;
public class LanguagePostfixTemplate extends LanguageExtension<PostfixTemplateProvider> {
private static final Logger LOG = Logger.getInstance(LanguagePostfixTemplate.class);
@@ -44,13 +45,28 @@ public class LanguagePostfixTemplate extends LanguageExtension<PostfixTemplatePr
}
private static void validateTemplatesForLanguage(Language key, List<PostfixTemplateProvider> providers) {
Set<String> templateKeys = ContainerUtil.newHashSet();
Map<String, PostfixTemplateProvider> templateKeys = ContainerUtil.newHashMap();
for (PostfixTemplateProvider provider : providers) {
for (PostfixTemplate template : provider.getTemplates()) {
if (!templateKeys.add(template.getKey())) {
LOG.error("Duplicated key " + template.getKey() + " for language " + key.getID() + " provider " + provider.getClass());
PostfixTemplateProvider oldProvider = templateKeys.put(template.getKey(), provider);
if (oldProvider != null) {
String oldPlugin = getPluginId(oldProvider);
String newPlugin = getPluginId(provider);
LOG.error("Duplicated postfix completion key '" + template.getKey() + "' for language " + key.getID() +
". Possible you need to disable one of the plugins: " + oldPlugin + ", " + newPlugin);
}
}
}
}
@NotNull
private static String getPluginId(@NotNull PostfixTemplateProvider provider) {
ClassLoader loader = provider.getClass().getClassLoader();
if (loader instanceof PluginClassLoader) {
return ((PluginClassLoader)loader).getPluginId().getIdString();
}
return "";
}
}
@@ -25,15 +25,17 @@ import com.intellij.codeInspection.reference.RefEntity;
import com.intellij.codeInspection.reference.RefManagerImpl;
import com.intellij.codeInspection.ui.InspectionResultsView;
import com.intellij.codeInspection.ui.InspectionTree;
import com.intellij.codeInspection.ui.QuickFixToolbar;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.CustomComponentAction;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.vfs.ReadonlyStatusHandler;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
@@ -41,6 +43,8 @@ import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.ui.ClickListener;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.util.SequentialModalProgressTask;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
@@ -49,12 +53,13 @@ import javax.swing.*;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.event.MouseEvent;
import java.util.*;
/**
* @author max
*/
public class QuickFixAction extends AnAction {
public class QuickFixAction extends AnAction implements CustomComponentAction {
private static final Logger LOG = Logger.getInstance("#" + QuickFixAction.class.getName());
public static final QuickFixAction[] EMPTY = new QuickFixAction[0];
@@ -307,6 +312,32 @@ public class QuickFixAction extends AnAction {
return true;
}
@Override
public JComponent createCustomComponent(Presentation presentation) {
final JButton button = new JButton(presentation.getText());
Icon icon = presentation.getIcon();
if (icon == null) {
icon = AllIcons.Actions.CreateFromUsage;
}
button.setEnabled(presentation.isEnabled());
button.setIcon(IconLoader.getTransparentIcon(icon, 0.75f));
new ClickListener() {
@Override
public boolean onClick(@NotNull MouseEvent event, int clickCount) {
actionPerformed(AnActionEvent.createFromAnAction(QuickFixAction.this,
event,
ActionPlaces.UNKNOWN,
DataManager.getInstance().getDataContext(button)));
return true;
}
}.installOn(button);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
panel.setBorder(IdeBorderFactory.createEmptyBorder(7, 0, 8, 0));
panel.add(button);
return panel;
}
private class PerformFixesTask extends PerformFixesModalTask {
@NotNull private final GlobalInspectionContextImpl myContext;
@NotNull
@@ -19,14 +19,12 @@ import com.intellij.codeInsight.daemon.HighlightDisplayKey;
import com.intellij.codeInspection.ex.DisableInspectionToolAction;
import com.intellij.codeInspection.ex.InspectionProfileImpl;
import com.intellij.codeInspection.ex.InspectionToolWrapper;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.profile.codeInspection.ui.SingleInspectionProfilePanel;
import com.intellij.ui.*;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBLabelDecorator;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.util.ui.JBInsets;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
@@ -78,8 +76,8 @@ public class InspectionNodeInfo extends JPanel {
JScrollPane pane = ScrollPaneFactory.createScrollPane(description, true);
add(pane,
new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH,
new JBInsets(0, 12, 0, 0), 0, 0));
new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.VERTICAL,
new JBInsets(0, 10, 0, 0), getFontMetrics(UIUtil.getLabelFont()).charWidth('f') * 110 - pane.getMinimumSize().width, 0));
add(myButton,
new GridBagConstraints(0, 2, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
new JBInsets(15, 9, 9, 0), 0, 0));
@@ -40,6 +40,7 @@ import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.DumbAware;
@@ -138,6 +139,7 @@ public class InspectionResultsView extends JPanel implements Disposable, Occuren
mySplitter = new OnePixelSplitter(false, AnalysisUIOptions.getInstance(myProject).SPLITTER_PROPORTION);
mySplitter.setFirstComponent(ScrollPaneFactory.createScrollPane(myTree, SideBorder.LEFT));
mySplitter.setHonorComponentsMinimumSize(false);
mySplitter.addPropertyChangeListener(evt -> {
if (Splitter.PROP_PROPORTION.equals(evt.getPropertyName())) {
@@ -396,7 +398,7 @@ public class InspectionResultsView extends JPanel implements Disposable, Occuren
mySplitter.setSecondComponent(getNothingToShowTextLabel());
}
else {
showInRightPanel(myTree.getCommonSelectedElement());
showInRightPanel(myTree.getCommonSelectedElement(), oldEditor == null);
}
}
else {
@@ -405,12 +407,12 @@ public class InspectionResultsView extends JPanel implements Disposable, Occuren
final InspectionTreeNode node = (InspectionTreeNode)pathSelected.getLastPathComponent();
if (node instanceof ProblemDescriptionNode) {
final ProblemDescriptionNode problemNode = (ProblemDescriptionNode)node;
showInRightPanel(problemNode.getElement());
showInRightPanel(problemNode.getElement(), oldEditor == null);
}
else if (node instanceof InspectionPackageNode ||
node instanceof InspectionModuleNode ||
node instanceof RefElementNode) {
showInRightPanel(node.getContainingFileLocalEntity());
showInRightPanel(node.getContainingFileLocalEntity(), oldEditor == null);
}
else if (node instanceof InspectionNode) {
final String shortName = ((InspectionNode)node).getToolWrapper().getShortName();
@@ -418,7 +420,7 @@ public class InspectionResultsView extends JPanel implements Disposable, Occuren
mySplitter.setSecondComponent(getNothingToShowTextLabel());
}
else {
showInRightPanel(null);
showInRightPanel(null, oldEditor == null);
}
}
else if (node instanceof InspectionRootNode || node instanceof InspectionGroupNode || node instanceof InspectionSeverityGroupNode) {
@@ -452,7 +454,7 @@ public class InspectionResultsView extends JPanel implements Disposable, Occuren
return multipleSelectionLabel;
}
private void showInRightPanel(@Nullable final RefEntity refEntity) {
private void showInRightPanel(@Nullable final RefEntity refEntity, boolean hasNoEditorToReuse) {
Cursor currentCursor = getCursor();
try {
setCursor(new Cursor(Cursor.WAIT_CURSOR));
@@ -470,7 +472,7 @@ public class InspectionResultsView extends JPanel implements Disposable, Occuren
}
editorPanel.add(previewPanel, BorderLayout.CENTER);
if (problemCount > 0) {
final QuickFixToolbar fixToolbar = new QuickFixToolbar(myPreviewEditor == null || myPreviewEditor.getUserData(PREVIEW_EDITOR_IS_REUSED_KEY) == null
final QuickFixToolbar fixToolbar = new QuickFixToolbar(myPreviewEditor == null || (!hasNoEditorToReuse && myPreviewEditor.getUserData(PREVIEW_EDITOR_IS_REUSED_KEY) == null)
? null
: myPreviewEditor, this);
myLoadingProgressPreview = fixToolbar;
@@ -521,9 +523,11 @@ public class InspectionResultsView extends JPanel implements Disposable, Occuren
settings.setLeadingWhitespaceShown(true);
settings.setRightMarginShown(true);
settings.setRightMargin(60);
myPreviewEditor.getColorsScheme().setColor(EditorColors.GUTTER_BACKGROUND, myPreviewEditor.getColorsScheme().getDefaultBackground());
myPreviewEditor.getScrollPane().setBorder(IdeBorderFactory.createBorder(SideBorder.TOP));
UsagePreviewPanel.highlight(Collections.emptyList(), myPreviewEditor, myProject);
}
myPreviewEditor.getSettings().setFoldingOutlineShown(problemCount != 1);
if (problemCount == 1) {
final PsiElement finalSelectedElement = selectedElement;
@@ -50,6 +50,21 @@ public class InspectionViewNavigationPanel extends JPanel implements InspectionT
resetChildrenNavigation();
}
@Override
public void updateLoadingProgress() {
resetChildrenAndRepaint();
}
@Override
public void treeLoaded() {
resetChildrenAndRepaint();
}
@NotNull
public static String getTitleText(boolean addGroupWord, boolean addColon) {
return "Select inspection" + (addGroupWord ? " group " : " ") + "to see problems" + (addColon ? ":" : ".");
}
private void resetChildrenNavigation() {
final int currentChildrenCount = myNode.getChildCount();
if (myShownChildrenCount != currentChildrenCount) {
@@ -70,18 +85,9 @@ public class InspectionViewNavigationPanel extends JPanel implements InspectionT
}
}
@NotNull
public static String getTitleText(boolean addGroupWord, boolean addColon) {
return "Select inspection" + (addGroupWord ? " group " : " ") + "to see problems" + (addColon ? ":" : ".");
}
@Override
public void updateLoadingProgress() {
resetChildrenNavigation();
}
@Override
public void treeLoaded() {
private void resetChildrenAndRepaint() {
resetChildrenNavigation();
revalidate();
repaint();
}
}
@@ -20,28 +20,21 @@ import com.intellij.codeInspection.ex.InspectionToolWrapper;
import com.intellij.codeInspection.ex.QuickFixAction;
import com.intellij.codeInspection.ui.actions.SuppressActionWrapper;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ComboBoxAction;
import com.intellij.openapi.actionSystem.ex.CustomComponentAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.IconLoader;
import com.intellij.ui.ClickListener;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.SimpleColoredComponent;
import com.intellij.util.ui.AsyncProcessIcon;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.function.Supplier;
/**
* @author Dmitry Batkovich
@@ -49,7 +42,6 @@ import java.util.function.Supplier;
public class QuickFixToolbar extends JPanel implements InspectionTreeLoadingProgressAware {
private static final Logger LOG = Logger.getInstance(QuickFixToolbar.class);
private static final int MAX_FIX_COUNT = 3;
@Nullable private final String myTargetName;
@NotNull private final InspectionResultsView myView;
private final InspectionToolWrapper myWrapper;
private final ProblemPreviewEditorFoldings myFoldings;
@@ -66,13 +58,12 @@ public class QuickFixToolbar extends JPanel implements InspectionTreeLoadingProg
int problemCount = descriptors.length;
setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
myTargetName = getTargetName();
if (view.isUpdating() && !areDescriptorNodesSelected()) {
setBorder(IdeBorderFactory.createEmptyBorder(16, 9, 13, 0));
AsyncProcessIcon waitingIcon = new AsyncProcessIcon("Inspection preview panel updating...");
Disposer.register(this, waitingIcon);
myWaitingLabel = getLabel(null, problemCount);
myWaitingLabel = getLabel(problemCount);
add(myWaitingLabel);
add(waitingIcon);
}
@@ -102,7 +93,7 @@ public class QuickFixToolbar extends JPanel implements InspectionTreeLoadingProg
if (myWaitingLabel != null) {
myWaitingLabel.clear();
final InspectionTree tree = myView.getTree();
appendTextToLabel(myWaitingLabel, tree.getSelectedProblemCount(), null);
appendTextToLabel(myWaitingLabel, tree.getSelectedProblemCount());
}
}
@@ -114,18 +105,20 @@ public class QuickFixToolbar extends JPanel implements InspectionTreeLoadingProg
boolean hasFixes = fixes != null && fixes.length != 0;
int problemCount = descriptors.length;
boolean multipleDescriptors = problemCount > 1;
fill(multipleDescriptors, () -> getLabel(fixes, problemCount), this);
fill(hasFixes, () -> createFixPanel(fixes, multipleDescriptors), this);
fill(true, () -> createSuppressionCombo(myWrapper, tree.getSelectionPaths(), project, multipleDescriptors), this);
}
@Nullable
private String getTargetName() {
if (myView.getTree().getSelectionCount() == 1) {
final Object node = myView.getTree().getSelectionPath().getLastPathComponent();
return node instanceof RefElementNode ? ((RefElementNode)node).getElement().getName() : null;
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
if (multipleDescriptors) {
add(getLabel(problemCount));
}
return null;
final DefaultActionGroup actions = new DefaultActionGroup();
if (hasFixes) {
actions.addAll(createFixActions(fixes, multipleDescriptors));
}
actions.add(createSuppressionCombo(myWrapper, tree.getSelectionPaths(), project));
final ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, actions, true);
final JComponent component = toolbar.getComponent();
toolbar.setTargetComponent(this);
add(component);
}
private boolean areDescriptorNodesSelected() {
@@ -139,34 +132,25 @@ public class QuickFixToolbar extends JPanel implements InspectionTreeLoadingProg
}
@NotNull
private SimpleColoredComponent getLabel(QuickFixAction[] fixes, int problemsCount) {
private static SimpleColoredComponent getLabel(int problemsCount) {
SimpleColoredComponent label = new SimpleColoredComponent();
appendTextToLabel(label, problemsCount, fixes);
appendTextToLabel(label, problemsCount);
label.setBorder(IdeBorderFactory.createEmptyBorder(0, 0, 0, 2));
return label;
}
private void appendTextToLabel(SimpleColoredComponent label,
int problemsCount,
QuickFixAction[] fixes) {
boolean hasFixesNonIntersectedFixes = fixes != null && fixes.length == 0;
label.append(problemsCount + " problems" +
(myTargetName == null ? "" : (" in " + myTargetName)) +
(problemsCount > 1 && (fixes != null && fixes.length >= MAX_FIX_COUNT) ? " Fix all:" : "") +
(!hasFixesNonIntersectedFixes ? ":" : ""));
if (hasFixesNonIntersectedFixes) {
label.append(" select a single problem to see its quick fixes");
}
private static void appendTextToLabel(SimpleColoredComponent label,
int problemsCount) {
label.append(problemsCount + " problems:");
}
private static JComponent createSuppressionCombo(@NotNull final InspectionToolWrapper toolWrapper,
@NotNull final TreePath[] paths,
@NotNull final Project project,
boolean multipleDescriptors) {
private static AnAction createSuppressionCombo(@NotNull final InspectionToolWrapper toolWrapper,
@NotNull final TreePath[] paths,
@NotNull final Project project) {
final AnAction[] suppressors = new SuppressActionWrapper(project, toolWrapper, paths).getChildren(null);
final ComboBoxAction action = new ComboBoxAction() {
{
getTemplatePresentation().setText(multipleDescriptors ? "Suppress All" : "Suppress");
getTemplatePresentation().setText("Suppress");
getTemplatePresentation().setEnabledAndVisible(suppressors.length != 0);
}
@@ -179,26 +163,11 @@ public class QuickFixToolbar extends JPanel implements InspectionTreeLoadingProg
}
};
action.setSmallVariant(false);
return fixComboBoxActionComponent(action.createCustomComponent(action.getTemplatePresentation()));
}
private static JComponent fixComboBoxActionComponent(JComponent component) {
JPanel containingPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
containingPanel.add(component);
containingPanel.setBorder(IdeBorderFactory.createEmptyBorder(7, 0, 8, 0));
return containingPanel;
}
private static void fill(boolean add,
@NotNull Supplier<JComponent> componentSupplier,
@NotNull JPanel parent) {
if (add) {
parent.add(componentSupplier.get());
}
return action;
}
@NotNull
private static JComponent createFixPanel(QuickFixAction[] fixes, boolean multipleDescriptors) {
private static AnAction[] createFixActions(QuickFixAction[] fixes, boolean multipleDescriptors) {
if (fixes.length > MAX_FIX_COUNT) {
final ComboBoxAction fixComboBox = new ComboBoxAction() {
{
@@ -217,71 +186,8 @@ public class QuickFixToolbar extends JPanel implements InspectionTreeLoadingProg
return actionGroup;
}
};
return fixComboBoxActionComponent(fixComboBox.createCustomComponent(fixComboBox.getTemplatePresentation()));
}
else {
JPanel fixPanel = new JPanel();
fixPanel.setLayout(new BoxLayout(fixPanel, BoxLayout.LINE_AXIS));
fixPanel.setBorder(IdeBorderFactory.createEmptyBorder(7, 0, 8, 0));
final boolean multipleFixes = fixes.length > 1;
for (QuickFixAction fix : fixes) {
fixPanel.add(createQuickFixButton(fix, multipleDescriptors && !multipleFixes));
if (fix != fixes[fixes.length - 1]) {
fixPanel.add(Box.createHorizontalStrut(3));
}
}
return fixPanel;
}
}
private static JComponent createQuickFixButton(@NotNull QuickFixAction fix, boolean multipleFixes) {
final MyCustomComponentLocalQuickFixWrapper action = new MyCustomComponentLocalQuickFixWrapper(fix);
if (multipleFixes) {
action.getTemplatePresentation().setText("Fix all '" + fix.getText() + "'");
}
return action.createCustomComponent(action.getTemplatePresentation());
}
private static class MyCustomComponentLocalQuickFixWrapper extends AnAction implements CustomComponentAction {
private QuickFixAction myUnderlying;
public MyCustomComponentLocalQuickFixWrapper(@NotNull QuickFixAction underlying) {
myUnderlying = underlying;
copyFrom(underlying);
}
@Override
public JComponent createCustomComponent(Presentation presentation) {
final JButton button = new JButton(presentation.getText());
Icon icon = presentation.getIcon();
if (icon == null) {
icon = AllIcons.Actions.CreateFromUsage;
}
button.setEnabled(presentation.isEnabled());
button.setIcon(IconLoader.getTransparentIcon(icon, 0.75f));
new ClickListener() {
@Override
public boolean onClick(@NotNull MouseEvent event, int clickCount) {
actionPerformed(AnActionEvent.createFromAnAction(MyCustomComponentLocalQuickFixWrapper.this,
event,
"LOCAL_QUICK_FIX_WRAPPER_PANEL",
DataManager.getInstance().getDataContext(button)));
return true;
}
}.installOn(button);
return button;
}
@Override
public void update(AnActionEvent e) {
myUnderlying.update(e);
}
@Override
public void actionPerformed(AnActionEvent e) {
myUnderlying.actionPerformed(e);
return new AnAction[] {fixComboBox};
}
return fixes;
}
}
@@ -29,6 +29,7 @@ import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.actionSystem.ex.QuickList;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.TransactionGuard;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapManager;
@@ -250,10 +251,9 @@ public class GotoActionAction extends GotoActionBase implements DumbAware {
public static void performAction(Object element, @Nullable final Component component, @Nullable final AnActionEvent e) {
// element could be AnAction (SearchEverywhere)
final AnAction action = element instanceof AnAction ? (AnAction)element : ((GotoActionModel.ActionWrapper)element).getAction();
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
if (component == null) return;
ApplicationManager.getApplication().invokeLater(() -> {
if (component == null) return;
TransactionGuard.getInstance().performUserActivity(() -> {
DataManager instance = DataManager.getInstance();
DataContext context = instance != null ? instance.getDataContext(component) : DataContext.EMPTY_CONTEXT;
InputEvent inputEvent = e == null ? null : e.getInputEvent();
@@ -270,12 +270,12 @@ public class GotoActionAction extends GotoActionBase implements DumbAware {
else {
popup.showInFocusCenter();
}
}
}
else {
ActionUtil.performActionDumbAware(action, event);
}
}
}
});
}, ModalityState.NON_MODAL);
}
@@ -19,12 +19,19 @@ import com.intellij.ide.util.PropertiesComponent;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageUtil;
import com.intellij.lang.PerFileMappings;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.command.undo.BasicUndoableAction;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.command.undo.UnexpectedUndoException;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.*;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.ReadonlyStatusHandler;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Consumer;
@@ -38,10 +45,9 @@ import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.Collections;
import java.util.Comparator;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.Map;
/**
* @author gregsh
@@ -62,13 +68,23 @@ public abstract class LRUPopupBuilder<T> {
private JBIterable<T> myExtraItems = JBIterable.empty();
@NotNull
public static ListPopup forFileLanguages(@NotNull Project project, @NotNull final Iterable<VirtualFile> files, @NotNull final PerFileMappings<Language> mappings) {
public static ListPopup forFileLanguages(@NotNull Project project, @NotNull Iterable<VirtualFile> files, @NotNull final PerFileMappings<Language> mappings) {
final VirtualFile[] filesCopy = VfsUtilCore.toVirtualFileArray(JBIterable.from(files).toList());
Arrays.sort(filesCopy, new Comparator<VirtualFile>() {
@Override
public int compare(VirtualFile o1, VirtualFile o2) {
return StringUtil.compare(o1.getName(), o2.getName(), !o1.getFileSystem().isCaseSensitive());
}
});
return forFileLanguages(project, null, new Consumer<Language>() {
@Override
public void consume(Language t) {
for (VirtualFile file : files) {
mappings.setMapping(file, t);
}
public void consume(final Language t) {
new WriteCommandAction(project, "Change Language") {
@Override
protected void run(@NotNull Result result) throws Throwable {
changeLanguageWithUndo(project, t, filesCopy, mappings);
}
}.execute();
}
});
}
@@ -260,4 +276,47 @@ public abstract class LRUPopupBuilder<T> {
return getClass().getName() + "/" + myTitle;
}
private static void changeLanguageWithUndo(@NotNull Project project,
@NotNull final Language t,
@NotNull final VirtualFile[] sortedFiles,
@NotNull final PerFileMappings<Language> mappings) throws UnexpectedUndoException {
ReadonlyStatusHandler.OperationStatus status = ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(sortedFiles);
if (status.hasReadonlyFiles()) return;
final Set<VirtualFile> matchedExtensions = ContainerUtil.newLinkedHashSet();
final Map<VirtualFile, Language> oldMapping = ContainerUtil.newHashMap();
for (VirtualFile file : sortedFiles) {
oldMapping.put(file, mappings.getMapping(file));
if (ScratchUtil.hasMatchingExtension(project, file)) {
matchedExtensions.add(file);
}
}
BasicUndoableAction action = new BasicUndoableAction(sortedFiles) {
@Override
public void undo() throws UnexpectedUndoException {
for (VirtualFile file : sortedFiles) {
mappings.setMapping(file, oldMapping.get(file));
}
}
@Override
public void redo() throws UnexpectedUndoException {
for (VirtualFile file : sortedFiles) {
mappings.setMapping(file, t);
}
}
};
action.redo();
UndoManager.getInstance(project).undoableActionPerformed(action);
for (VirtualFile file : matchedExtensions) {
try {
ScratchUtil.updateFileExtension(project, file);
}
catch (IOException ignored) {
}
}
}
}
@@ -26,6 +26,7 @@ import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
@@ -37,6 +38,7 @@ import com.intellij.psi.PsiFile;
import com.intellij.util.Consumer;
import com.intellij.util.Function;
import com.intellij.util.ObjectUtils;
import com.intellij.util.PathUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.JBIterable;
import org.jetbrains.annotations.NotNull;
@@ -111,9 +113,11 @@ public class ScratchFileActions {
static void doCreateNewScratch(@NotNull Project project, boolean buffer, @NotNull Language language, @NotNull String text) {
FeatureUsageTracker.getInstance().triggerFeatureUsed("scratch");
LanguageFileType fileType = language.getAssociatedFileType();
String ext = buffer || fileType == null? "" : fileType.getDefaultExtension();
String fileName = buffer ? "buffer" + nextBufferIndex() : "scratch";
ScratchFileService.Option option = buffer ? ScratchFileService.Option.create_if_missing : ScratchFileService.Option.create_new_always;
VirtualFile f = ScratchRootType.getInstance().createScratchFile(project, fileName, language, text, option);
VirtualFile f = ScratchRootType.getInstance().createScratchFile(project, PathUtil.makeFileName(fileName, ext), language, text, option);
if (f != null) {
FileEditorManager.getInstance(project).openFile(f, true);
}
@@ -15,9 +15,21 @@
*/
package com.intellij.ide.scratch;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.PathUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
/**
* @author gregsh
*/
@@ -33,4 +45,33 @@ public class ScratchUtil {
public static boolean isScratch(@Nullable VirtualFile file) {
return file != null && file.getFileType() == ScratchFileType.INSTANCE;
}
public static void updateFileExtension(@NotNull Project project, @Nullable VirtualFile file) throws IOException {
ApplicationManager.getApplication().assertWriteAccessAllowed();
if (CommandProcessor.getInstance().getCurrentCommand() == null) {
throw new AssertionError("command required");
}
if (file == null) return;
Language language = LanguageUtil.getLanguageForPsi(project, file);
String extension = file.getExtension();
FileType expected = extension == null ? null : FileTypeManager.getInstance().getFileTypeByExtension(extension);
FileType actual = language == null ? null : language.getAssociatedFileType();
if (expected == actual || actual == null) return;
String ext = actual.getDefaultExtension();
if (StringUtil.isEmpty(ext)) return;
String newName = PathUtil.makeFileName(file.getNameWithoutExtension(), ext);
VirtualFile parent = file.getParent();
newName = parent != null && parent.findChild(newName) != null ? PathUtil.makeFileName(file.getName(), ext) : newName;
file.rename(ScratchUtil.class, newName);
}
public static boolean hasMatchingExtension(@NotNull Project project, @NotNull VirtualFile file) {
String extension = file.getExtension();
Language language = LanguageUtil.getLanguageForPsi(project, file);
FileType expected = extension == null ? null : FileTypeManager.getInstance().getFileTypeByExtension(extension);
FileType actual = language == null ? null : language.getAssociatedFileType();
return expected == actual && actual != null;
}
}
@@ -30,6 +30,7 @@ import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.highlighter.HighlighterIterator;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.util.TextRange;
@@ -53,9 +54,16 @@ public class SelectWordAtCaretAction extends TextComponentEditorAction implement
@Override
public void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
SelectionModel selectionModel = editor.getSelectionModel();
Document document = editor.getDocument();
if (EditorUtil.isPasswordEditor(editor)) {
selectionModel.setSelection(0, document.getTextLength());
return;
}
int lineNumber = editor.getCaretModel().getLogicalPosition().line;
int caretOffset = editor.getCaretModel().getOffset();
Document document = editor.getDocument();
if (lineNumber >= document.getLineCount()) {
return;
}
@@ -72,10 +80,9 @@ public class SelectWordAtCaretAction extends TextComponentEditorAction implement
if (ranges.isEmpty()) return;
SelectionModel selectionModel = editor.getSelectionModel();
final TextRange selectionRange = new TextRange(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd());
TextRange minimumRange = new TextRange(0, editor.getDocument().getTextLength());
TextRange minimumRange = new TextRange(0, document.getTextLength());
for (TextRange range : ranges) {
if (range.contains(selectionRange) && !range.equals(selectionRange)) {
if (minimumRange.contains(range)) {
@@ -146,7 +146,7 @@ public class PredefinedSearchScopeProviderImpl extends PredefinedSearchScopeProv
}
if (usageView) {
if (prevSearchFiles) {
if (!prevSearchFiles) {
addHierarchyScope(project, result);
}
UsageView selectedUsageView = UsageViewManager.getInstance(project).getSelectedUsageView();
@@ -83,8 +83,8 @@ public class LanguageTextField extends EditorTextField {
}
}
private static Document createDocument(String value, @Nullable Language language, Project project,
@NotNull SimpleDocumentCreator documentCreator) {
public static Document createDocument(String value, @Nullable Language language, Project project,
@NotNull SimpleDocumentCreator documentCreator) {
if (language != null) {
final PsiFileFactory factory = PsiFileFactory.getInstance(project);
final FileType fileType = language.getAssociatedFileType();
@@ -16,20 +16,15 @@
package com.intellij.ui;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.ex.FocusChangeListener;
import com.intellij.openapi.fileTypes.PlainTextLanguage;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.util.textCompletion.TextCompletionUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -46,42 +41,39 @@ import java.util.Collection;
* @author Roman Chernyatchik
*/
public class TextFieldWithAutoCompletion<T> extends LanguageTextField {
public static final TextFieldWithAutoCompletionListProvider EMPTY_COMPLETION = new StringsCompletionProvider(null, null);
private final boolean myShowAutocompletionIsAvailableHint;
private final TextFieldWithAutoCompletionListProvider<T> myProvider;
@NotNull private final TextFieldWithAutoCompletionListProvider<T> myProvider;
private final boolean myShowCompletionHint;
@SuppressWarnings("unchecked")
public TextFieldWithAutoCompletion() {
this(null, EMPTY_COMPLETION, false, null);
}
public TextFieldWithAutoCompletion(final Project project,
@NotNull final TextFieldWithAutoCompletionListProvider<T> provider,
final boolean showAutocompletionIsAvailableHint, @Nullable final String text) {
public TextFieldWithAutoCompletion(@Nullable Project project,
@NotNull TextFieldWithAutoCompletionListProvider<T> provider,
boolean showCompletionHint,
@Nullable String text) {
super(project == null ? null : PlainTextLanguage.INSTANCE, project, text == null ? "" : text);
myShowAutocompletionIsAvailableHint = showAutocompletionIsAvailableHint;
myShowCompletionHint = showCompletionHint;
myProvider = provider;
TextFieldWithAutoCompletionContributor.installCompletion(getDocument(), project, provider, true);
if (project != null) {
installCompletion(getDocument(), project, provider, true);
}
}
public static TextFieldWithAutoCompletion<String> create(final Project project,
@NotNull final Collection<String> items,
final boolean showAutocompletionIsAvailableHint,
@Nullable final String text) {
return create(project, items, null, showAutocompletionIsAvailableHint, text);
@NotNull
public static TextFieldWithAutoCompletion<String> create(@Nullable Project project,
@NotNull Collection<String> items,
boolean showCompletionHint,
@Nullable String text) {
return create(project, items, null, showCompletionHint, text);
}
public static TextFieldWithAutoCompletion<String> create(final Project project,
@NotNull final Collection<String> items,
@Nullable final Icon icon,
final boolean showAutocompletionIsAvailableHint,
@Nullable final String text) {
return new TextFieldWithAutoCompletion<String>(project, new StringsCompletionProvider(items, icon), showAutocompletionIsAvailableHint,
text);
@NotNull
public static TextFieldWithAutoCompletion<String> create(@Nullable Project project,
@NotNull Collection<String> items,
@Nullable Icon icon,
boolean showCompletionHint,
@Nullable String text) {
return new TextFieldWithAutoCompletion<String>(project, new StringsCompletionProvider(items, icon), showCompletionHint, text);
}
public void setVariants(@NotNull Collection<T> variants) {
@@ -89,85 +81,52 @@ public class TextFieldWithAutoCompletion<T> extends LanguageTextField {
}
public <T> void installProvider(@NotNull TextFieldWithAutoCompletionListProvider<T> provider) {
TextFieldWithAutoCompletionContributor.installCompletion(getDocument(), getProject(), provider, true);
installCompletion(getDocument(), getProject(), provider, true);
}
public static void installCompletion(@NotNull Document document,
@NotNull Project project,
@NotNull TextFieldWithAutoCompletionListProvider provider,
boolean autoPopup) {
PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
if (psiFile != null) {
TextCompletionUtil.installProvider(psiFile, provider, autoPopup);
}
}
@Override
protected EditorEx createEditor() {
final EditorEx editor = super.createEditor();
EditorEx editor = super.createEditor();
if (!myShowAutocompletionIsAvailableHint) {
return editor;
if (myShowCompletionHint) {
TextCompletionUtil.installCompletionHint(editor);
}
final String completionShortcutText =
KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction(IdeActions.ACTION_CODE_COMPLETION));
if (StringUtil.isEmpty(completionShortcutText)) {
return editor;
}
final Ref<Boolean> toShowHintRef = new Ref<Boolean>(true);
editor.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
public void documentChanged(DocumentEvent e) {
toShowHintRef.set(false);
}
});
editor.addFocusListener(new FocusChangeListener() {
@Override
public void focusGained(final Editor editor) {
if (toShowHintRef.get() && getText().length() == 0) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
HintManager.getInstance().showInformationHint(editor, "Code completion available ( " + completionShortcutText + " )");
}
});
}
}
@Override
public void focusLost(Editor editor) {
// Do nothing
}
});
return editor;
}
public static class StringsCompletionProvider extends TextFieldWithAutoCompletionListProvider<String> implements DumbAware {
@Nullable private final Icon myIcon;
public StringsCompletionProvider(@Nullable final Collection<String> variants,
@Nullable final Icon icon) {
public StringsCompletionProvider(@Nullable Collection<String> variants, @Nullable Icon icon) {
super(variants);
myIcon = icon;
}
@Override
public int compare(final String item1, final String item2) {
public int compare(String item1, String item2) {
return StringUtil.compare(item1, item2, false);
}
@Override
protected Icon getIcon(@NotNull final String item) {
protected Icon getIcon(@NotNull String item) {
return myIcon;
}
@NotNull
@Override
protected String getLookupString(@NotNull final String item) {
protected String getLookupString(@NotNull String item) {
return item;
}
@Override
protected String getTailText(@NotNull final String item) {
return null;
}
@Override
protected String getTypeText(@NotNull final String item) {
return null;
}
}
}
@@ -1,154 +0,0 @@
/*
* 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.ui;
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.AutoCompletionPolicy;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.concurrency.SensitiveProgressWrapper;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Key;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* @author Roman.Chernyatchik
*/
public class TextFieldWithAutoCompletionContributor<T> extends CompletionContributor implements DumbAware {
private static final Logger LOG = Logger.getInstance("#com.intellij.ui.TextFieldWithAutoCompletionContributor");
private static final Key<TextFieldWithAutoCompletionListProvider> KEY = Key.create("text field simple completion available");
private static final Key<Boolean> AUTO_POPUP_KEY = Key.create("text Field simple completion auto-popup");
public static <T> void installCompletion(Document document,
Project project,
@Nullable TextFieldWithAutoCompletionListProvider<T> provider,
boolean autoPopup) {
PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
if (psiFile != null) {
//noinspection unchecked
psiFile.putUserData(KEY, provider == null ? TextFieldWithAutoCompletion.EMPTY_COMPLETION : provider);
psiFile.putUserData(AUTO_POPUP_KEY, autoPopup);
}
}
@Override
public void fillCompletionVariants(@NotNull final CompletionParameters parameters, @NotNull CompletionResultSet result) {
PsiFile file = parameters.getOriginalFile();
final TextFieldWithAutoCompletionListProvider<T> provider = file.getUserData(KEY);
if (provider == null || (DumbService.isDumb(file.getProject()) && !DumbService.isDumbAware(provider))) {
return;
}
String adv = provider.getAdvertisement();
if (adv == null) {
final String shortcut = getActionShortcut(IdeActions.ACTION_QUICK_JAVADOC);
if (shortcut != null) {
adv = provider.getQuickDocHotKeyAdvertisement(shortcut);
}
}
if (adv != null) {
result.addLookupAdvertisement(adv);
}
final String prefix = provider.getPrefix(parameters);
if (prefix == null) {
return;
}
if (parameters.getInvocationCount() == 0 && !file.getUserData(AUTO_POPUP_KEY)) { // is autopopup
return;
}
final PrefixMatcher prefixMatcher = provider.createPrefixMatcher(prefix);
if (prefixMatcher != null) {
result = result.withPrefixMatcher(prefixMatcher);
}
Collection<T> items = provider.getItems(prefix, true, parameters);
addCompletionElements(result, provider, items, -10000);
final ProgressManager progressManager = ProgressManager.getInstance();
ProgressIndicator mainIndicator = progressManager.getProgressIndicator();
final ProgressIndicator indicator = mainIndicator != null ? new SensitiveProgressWrapper(mainIndicator) : new EmptyProgressIndicator();
Future<Collection<T>>
future =
ApplicationManager.getApplication().executeOnPooledThread(new Callable<Collection<T>>() {
@Override
public Collection<T> call() {
return progressManager.runProcess(new Computable<Collection<T>>() {
@Override
public Collection<T> compute() {
return provider.getItems(prefix, false, parameters);
}
}, indicator);
}
});
while (true) {
try {
Collection<T> tasks = future.get(100, TimeUnit.MILLISECONDS);
if (tasks != null) {
addCompletionElements(result, provider, tasks, 0);
return;
}
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Exception ignore) {
}
ProgressManager.checkCanceled();
}
}
private static <T> void addCompletionElements(final CompletionResultSet result,
final TextFieldWithAutoCompletionListProvider<T> listProvider,
final Collection<T> items,
final int index) {
final AutoCompletionPolicy completionPolicy = ApplicationManager.getApplication().isUnitTestMode()
? AutoCompletionPolicy.ALWAYS_AUTOCOMPLETE
: AutoCompletionPolicy.NEVER_AUTOCOMPLETE;
int grouping = index;
for (final T item : items) {
if (item == null) {
LOG.error("Null item from " + listProvider);
continue;
}
LookupElementBuilder builder = listProvider.createLookupBuilder(item);
result.addElement(PrioritizedLookupElement.withGrouping(builder.withAutoCompletionPolicy(completionPolicy), grouping--));
}
}
}
@@ -15,46 +15,133 @@
*/
package com.intellij.ui;
import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.codeInsight.completion.InsertHandler;
import com.intellij.codeInsight.completion.PlainPrefixMatcher;
import com.intellij.codeInsight.completion.PrefixMatcher;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.AutoCompletionPolicy;
import com.intellij.codeInsight.lookup.CharFilter;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.concurrency.SensitiveProgressWrapper;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.Computable;
import com.intellij.util.textCompletion.DefaultTextCompletionValueDescriptor;
import com.intellij.util.textCompletion.TextCompletionProvider;
import com.intellij.util.textCompletion.TextCompletionUtil;
import com.intellij.util.textCompletion.TextCompletionValueDescriptor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* @author Roman.Chernyatchik
*/
public abstract class TextFieldWithAutoCompletionListProvider<T> implements Comparator<T> {
public abstract class TextFieldWithAutoCompletionListProvider<T> extends DefaultTextCompletionValueDescriptor<T> implements
TextCompletionProvider {
private static final Logger LOG = Logger.getInstance(TextFieldWithAutoCompletionListProvider.class);
@NotNull protected Collection<T> myVariants;
@Nullable
private String myCompletionAdvertisement;
@Nullable
protected abstract Icon getIcon(@NotNull final T item);
@NotNull
protected abstract String getLookupString(@NotNull final T item);
@Nullable
protected abstract String getTailText(@NotNull final T item);
@Nullable
protected abstract String getTypeText(@NotNull final T item);
@Override
public abstract int compare(T item1, T item2);
protected TextFieldWithAutoCompletionListProvider(@Nullable final Collection<T> variants) {
setItems(variants);
myCompletionAdvertisement = null;
}
@Nullable
@Override
public String getPrefix(@NotNull String text, int offset) {
return getCompletionPrefix(text, offset);
}
@NotNull
@Override
public CompletionResultSet applyPrefixMatcher(@NotNull CompletionResultSet result, @NotNull String prefix) {
PrefixMatcher prefixMatcher = createPrefixMatcher(prefix);
if (prefixMatcher != null) {
return result.withPrefixMatcher(prefixMatcher);
}
return result;
}
@Nullable
@Override
public CharFilter.Result acceptChar(char c) {
return null;
}
@Override
public void fillCompletionVariants(@NotNull CompletionParameters parameters,
@NotNull String prefix,
@NotNull CompletionResultSet result) {
Collection<T> items = getItems(prefix, true, parameters);
addCompletionElements(result, this, items, -10000);
final ProgressManager progressManager = ProgressManager.getInstance();
ProgressIndicator mainIndicator = progressManager.getProgressIndicator();
final ProgressIndicator indicator = mainIndicator != null ? new SensitiveProgressWrapper(mainIndicator) : new EmptyProgressIndicator();
Future<Collection<T>>
future =
ApplicationManager.getApplication().executeOnPooledThread(new Callable<Collection<T>>() {
@Override
public Collection<T> call() {
return progressManager.runProcess(new Computable<Collection<T>>() {
@Override
public Collection<T> compute() {
return getItems(prefix, false, parameters);
}
}, indicator);
}
});
while (true) {
try {
Collection<T> tasks = future.get(100, TimeUnit.MILLISECONDS);
if (tasks != null) {
addCompletionElements(result, this, tasks, 0);
return;
}
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Exception ignore) {
}
ProgressManager.checkCanceled();
}
}
private static <T> void addCompletionElements(final CompletionResultSet result,
final TextCompletionValueDescriptor<T> descriptor,
final Collection<T> items,
final int index) {
final AutoCompletionPolicy completionPolicy = ApplicationManager.getApplication().isUnitTestMode()
? AutoCompletionPolicy.ALWAYS_AUTOCOMPLETE
: AutoCompletionPolicy.NEVER_AUTOCOMPLETE;
int grouping = index;
for (final T item : items) {
if (item == null) {
LOG.error("Null item from " + descriptor);
continue;
}
LookupElementBuilder builder = descriptor.createLookupBuilder(item);
result.addElement(PrioritizedLookupElement.withGrouping(builder.withAutoCompletionPolicy(completionPolicy), grouping--));
}
}
public void setItems(@Nullable final Collection<T> variants) {
myVariants = (variants != null) ? variants : Collections.<T>emptyList();
}
@@ -71,21 +158,6 @@ public abstract class TextFieldWithAutoCompletionListProvider<T> implements Comp
return items;
}
/**
* Completion list advertisement for documentation popup
*
* @param shortcut
* @return text
*/
@Nullable
public String getQuickDocHotKeyAdvertisement(@NotNull final String shortcut) {
final String advertisementTail = getQuickDocHotKeyAdvertisementTail(shortcut);
if (advertisementTail == null) {
return null;
}
return "Pressing " + shortcut + " would show " + advertisementTail;
}
/**
* Completion list advertisement text, if null advertisement for documentation
* popup will be shown
@@ -94,10 +166,21 @@ public abstract class TextFieldWithAutoCompletionListProvider<T> implements Comp
*/
@Nullable
public String getAdvertisement() {
return myCompletionAdvertisement;
if (myCompletionAdvertisement != null) return myCompletionAdvertisement;
String shortcut = KeymapUtil.getFirstKeyboardShortcutText((IdeActions.ACTION_QUICK_JAVADOC));
String advertisementTail = getQuickDocHotKeyAdvertisementTail(shortcut);
if (advertisementTail == null) {
return null;
}
return "Pressing " + shortcut + " would show " + advertisementTail;
}
public void setAdvertisement(@Nullable final String completionAdvertisement) {
@Nullable
protected String getQuickDocHotKeyAdvertisementTail(@NotNull final String shortcut) {
return null;
}
public void setAdvertisement(@Nullable String completionAdvertisement) {
myCompletionAdvertisement = completionAdvertisement;
}
@@ -106,47 +189,17 @@ public abstract class TextFieldWithAutoCompletionListProvider<T> implements Comp
return new PlainPrefixMatcher(prefix);
}
public LookupElementBuilder createLookupBuilder(@NotNull final T item) {
LookupElementBuilder builder = LookupElementBuilder.create(item, getLookupString(item))
.withIcon(getIcon(item));
final InsertHandler<LookupElement> handler = createInsertHandler(item);
if (handler != null) {
builder = builder.withInsertHandler(handler);
}
final String tailText = getTailText(item);
if (tailText != null) {
builder = builder.withTailText(tailText, true);
}
final String typeText = getTypeText(item);
if (typeText != null) {
builder = builder.withTypeText(typeText);
}
return builder;
}
@Nullable
public String getPrefix(@NotNull final CompletionParameters parameters) {
return getCompletionPrefix(parameters);
}
@NotNull
public static String getCompletionPrefix(CompletionParameters parameters) {
String text = parameters.getOriginalFile().getText();
int offset = parameters.getOffset();
return getCompletionPrefix(text, offset);
}
@NotNull
private static String getCompletionPrefix(String text, int offset) {
int i = text.lastIndexOf(' ', offset - 1) + 1;
int j = text.lastIndexOf('\n', offset - 1) + 1;
return text.substring(Math.max(i, j), offset);
}
@Nullable
protected String getQuickDocHotKeyAdvertisementTail(@NotNull final String shortcut) {
return null;
}
@Nullable
protected InsertHandler<LookupElement> createInsertHandler(@NotNull final T item) {
return null;
}
}
@@ -1,48 +0,0 @@
package com.intellij.util;
import com.intellij.codeInsight.completion.CompletionContributor;
import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbService;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiPlainTextFile;
import org.jetbrains.annotations.NotNull;
/**
* @author sergey.evdokimov
*/
public class CompletionContributorForTextField extends CompletionContributor implements DumbAware {
@Override
public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) {
PsiFile file = parameters.getOriginalFile();
if (!(file instanceof PsiPlainTextFile)) return;
TextFieldCompletionProvider field = file.getUserData(TextFieldCompletionProvider.COMPLETING_TEXT_FIELD_KEY);
if (field == null) return;
if (!(field instanceof DumbAware) && DumbService.isDumb(file.getProject())) return;
String text = file.getText();
int offset = Math.min(text.length(), parameters.getOffset());
String prefix = field.getPrefix(text.substring(0, offset));
CompletionResultSet activeResult;
if (!result.getPrefixMatcher().getPrefix().equals(prefix)) {
activeResult = result.withPrefixMatcher(prefix);
}
else {
activeResult = result;
}
if (field.isCaseInsensitivity()) {
activeResult = activeResult.caseInsensitive();
}
field.addCompletionVariants(text, offset, prefix, activeResult);
activeResult.stopHere();
}
}
@@ -1,27 +1,29 @@
package com.intellij.util;
import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.lookup.CharFilter;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.PlainTextLanguage;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.ui.EditorTextField;
import com.intellij.ui.LanguageTextField;
import com.intellij.util.textCompletion.TextCompletionProvider;
import com.intellij.util.textCompletion.TextCompletionUtil;
import com.intellij.util.textCompletion.TextFieldWithCompletion;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author sergey.evdokimov
*/
public abstract class TextFieldCompletionProvider {
static final Key<TextFieldCompletionProvider> COMPLETING_TEXT_FIELD_KEY = Key.create("COMPLETING_TEXT_FIELD_KEY");
public abstract class TextFieldCompletionProvider implements TextCompletionProvider {
protected boolean myCaseInsensitivity;
protected TextFieldCompletionProvider() {
@@ -32,30 +34,55 @@ public abstract class TextFieldCompletionProvider {
myCaseInsensitivity = caseInsensitivity;
}
@Nullable
@Override
public String getPrefix(@NotNull String text, int offset) {
return getPrefix(text.substring(0, offset));
}
@NotNull
@Override
public CompletionResultSet applyPrefixMatcher(@NotNull CompletionResultSet result, @NotNull String prefix) {
CompletionResultSet activeResult = result;
if (!activeResult.getPrefixMatcher().getPrefix().equals(prefix)) {
activeResult = activeResult.withPrefixMatcher(prefix);
}
if (isCaseInsensitivity()) {
activeResult = activeResult.caseInsensitive();
}
return activeResult;
}
@Nullable
@Override
public CharFilter.Result acceptChar(char c) {
return null;
}
@Override
public void fillCompletionVariants(@NotNull CompletionParameters parameters,
@NotNull String prefix,
@NotNull CompletionResultSet result) {
addCompletionVariants(parameters.getOriginalFile().getText(), parameters.getOffset(), prefix, result);
result.stopHere();
}
public void apply(@NotNull EditorTextField field, @NotNull String text) {
Project project = field.getProject();
if (project != null) {
field.setDocument(createDocument(project, text));
}
}
public void apply(@NotNull EditorTextField field) {
apply(field, "");
}
private Document createDocument(final Project project, @NotNull String text) {
final FileType fileType = PlainTextLanguage.INSTANCE.getAssociatedFileType();
assert fileType != null;
final long stamp = LocalTimeCounter.currentTime();
final PsiFile psiFile = PsiFileFactory.getInstance(project)
.createFileFromText("Dummy." + fileType.getDefaultExtension(), fileType, text, stamp, true, false);
psiFile.putUserData(COMPLETING_TEXT_FIELD_KEY, this);
final Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
assert document != null;
return document;
private Document createDocument(Project project, @NotNull String text) {
return LanguageTextField.createDocument(text, PlainTextLanguage.INSTANCE, project, new TextCompletionUtil.DocumentWithCompletionCreator(this, true));
}
public boolean isCaseInsensitivity() {
@@ -67,23 +94,26 @@ public abstract class TextFieldCompletionProvider {
return currentTextPrefix;
}
protected abstract void addCompletionVariants(@NotNull String text, int offset, @NotNull String prefix, @NotNull CompletionResultSet result);
@Nullable
@Override
public String getAdvertisement() {
return null;
}
protected abstract void addCompletionVariants(@NotNull String text,
int offset,
@NotNull String prefix,
@NotNull CompletionResultSet result);
@NotNull
public EditorTextField createEditor(Project project) {
return createEditor(project, true);
return createEditor(project, true, null);
}
@NotNull
public EditorTextField createEditor(Project project, final boolean shouldHaveBorder) {
return createEditor(project, shouldHaveBorder, null);
}
@NotNull
public EditorTextField createEditor(Project project,
final boolean shouldHaveBorder,
@Nullable final Consumer<Editor> editorConstructionCallback)
{
@Nullable final Consumer<Editor> editorConstructionCallback) {
return new EditorTextField(createDocument(project, ""), project, PlainTextLanguage.INSTANCE.getAssociatedFileType()) {
@Override
protected boolean shouldHaveBorder() {
@@ -0,0 +1,86 @@
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.textCompletion;
import com.intellij.codeInsight.completion.InsertHandler;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public abstract class DefaultTextCompletionValueDescriptor<T> implements TextCompletionValueDescriptor<T> {
@NotNull
protected abstract String getLookupString(@NotNull T item);
@Nullable
protected Icon getIcon(@NotNull T item) {
return null;
}
@Nullable
protected String getTailText(@NotNull T item) {
return null;
}
@Nullable
protected String getTypeText(@NotNull T item) {
return null;
}
@Nullable
protected InsertHandler<LookupElement> createInsertHandler(@NotNull final T item) {
return null;
}
@Override
public int compare(T item1, T item2) {
return StringUtil.compare(getLookupString(item1), getLookupString(item2), false);
}
@NotNull
@Override
public LookupElementBuilder createLookupBuilder(@NotNull T item) {
LookupElementBuilder builder = LookupElementBuilder.create(item, getLookupString(item))
.withIcon(getIcon(item));
InsertHandler<LookupElement> handler = createInsertHandler(item);
if (handler != null) {
builder = builder.withInsertHandler(handler);
}
String tailText = getTailText(item);
if (tailText != null) {
builder = builder.withTailText(tailText, true);
}
String typeText = getTypeText(item);
if (typeText != null) {
builder = builder.withTypeText(typeText);
}
return builder;
}
public static class StringValueDescriptor extends DefaultTextCompletionValueDescriptor<String> {
@NotNull
@Override
public String getLookupString(@NotNull String item) {
return item;
}
}
}
@@ -0,0 +1,35 @@
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.textCompletion;
import com.intellij.codeInsight.lookup.CharFilter;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class TextCompletionCharFilter extends CharFilter {
@Nullable
@Override
public Result acceptChar(char c, int prefixLength, @NotNull Lookup lookup) {
if (!lookup.isCompletion()) return null;
PsiFile file = lookup.getPsiFile();
if (file == null) return null;
TextCompletionProvider provider = TextCompletionUtil.getProvider(file);
if (provider != null) return provider.acceptChar(c);
return null;
}
}
@@ -0,0 +1,73 @@
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.textCompletion;
import com.intellij.codeInsight.completion.CompletionContributor;
import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.lookup.CharFilter;
import com.intellij.openapi.project.DumbAware;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
import static com.intellij.codeInsight.AutoPopupController.ALWAYS_AUTO_POPUP;
/**
* @author sergey.evdokimov
*/
public class TextCompletionContributor extends CompletionContributor implements DumbAware {
@Override
public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) {
PsiFile file = parameters.getOriginalFile();
TextCompletionProvider provider = TextCompletionUtil.getProvider(file);
if (provider == null) return;
if (parameters.getInvocationCount() == 0 &&
!Boolean.TRUE.equals(file.getUserData(TextCompletionUtil.AUTO_POPUP_KEY))) {
return;
}
String advertisement = provider.getAdvertisement();
if (advertisement != null) {
result.addLookupAdvertisement(advertisement);
}
String text = file.getText();
int offset = Math.min(text.length(), parameters.getOffset());
String prefix = provider.getPrefix(text, offset);
if (prefix == null) return;
CompletionResultSet activeResult = provider.applyPrefixMatcher(result, prefix);
provider.fillCompletionVariants(parameters, prefix, activeResult);
}
@Override
public boolean invokeAutoPopup(@NotNull PsiElement position, char typeChar) {
TextCompletionProvider provider = TextCompletionUtil.getProvider(position.getContainingFile());
if (provider != null) {
if (Boolean.TRUE.equals(position.getContainingFile().getUserData(TextCompletionUtil.AUTO_POPUP_KEY))) {
return Objects.equals(CharFilter.Result.ADD_TO_PREFIX, provider.acceptChar(typeChar));
}
}
return super.invokeAutoPopup(position, typeChar);
}
}
@@ -0,0 +1,39 @@
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.textCompletion;
import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.lookup.CharFilter;
import com.intellij.openapi.util.Key;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public interface TextCompletionProvider {
@Nullable
String getAdvertisement();
@Nullable
String getPrefix(@NotNull String text, int offset);
@NotNull
CompletionResultSet applyPrefixMatcher(@NotNull CompletionResultSet result, @NotNull String prefix);
@Nullable
CharFilter.Result acceptChar(char c);
void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull String prefix, @NotNull CompletionResultSet result);
}
@@ -0,0 +1,104 @@
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.textCompletion;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.ex.FocusChangeListener;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiFile;
import com.intellij.ui.LanguageTextField;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class TextCompletionUtil {
public static final Key<TextCompletionProvider> COMPLETING_TEXT_FIELD_KEY = Key.create("COMPLETING_TEXT_FIELD_KEY");
public static final Key<Boolean> AUTO_POPUP_KEY = Key.create("AUTOPOPUP_TEXT_FIELD_KEY");
public static void installProvider(@NotNull PsiFile psiFile, @NotNull TextCompletionProvider provider, boolean autoPopup) {
psiFile.putUserData(COMPLETING_TEXT_FIELD_KEY, provider);
psiFile.putUserData(AUTO_POPUP_KEY, autoPopup);
}
@Nullable
public static TextCompletionProvider getProvider(@NotNull PsiFile file) {
TextCompletionProvider provider = file.getUserData(COMPLETING_TEXT_FIELD_KEY);
if (provider == null || (DumbService.isDumb(file.getProject()) && !DumbService.isDumbAware(provider))) {
return null;
}
return provider;
}
public static void installCompletionHint(@NotNull EditorEx editor) {
String completionShortcutText =
KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction(IdeActions.ACTION_CODE_COMPLETION));
if (!StringUtil.isEmpty(completionShortcutText)) {
final Ref<Boolean> toShowHintRef = new Ref<Boolean>(true);
editor.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
public void documentChanged(DocumentEvent e) {
toShowHintRef.set(false);
}
});
editor.addFocusListener(new FocusChangeListener() {
@Override
public void focusGained(final Editor editor) {
if (toShowHintRef.get() && editor.getDocument().getText().isEmpty()) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
HintManager.getInstance().showInformationHint(editor, "Code completion available ( " + completionShortcutText + " )");
}
});
}
}
@Override
public void focusLost(Editor editor) {
// Do nothing
}
});
}
}
public static class DocumentWithCompletionCreator extends LanguageTextField.SimpleDocumentCreator {
@NotNull private final TextCompletionProvider myProvider;
private final boolean myAutoPopup;
public DocumentWithCompletionCreator(@NotNull TextCompletionProvider provider, boolean autoPopup) {
myProvider = provider;
myAutoPopup = autoPopup;
}
@Override
public void customizePsiFile(@NotNull PsiFile file) {
installProvider(file, myProvider, myAutoPopup);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,14 +13,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.util.text;
package com.intellij.util.textCompletion;
import com.intellij.util.text.EditDistance;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import org.jetbrains.annotations.NotNull;
/** @deprecated use {@link EditDistance} (to be removed in IDEA 17) */
@SuppressWarnings("unused")
public class LevenshteinDistance {
public int calculateMetrics(CharSequence str1, CharSequence str2) {
return EditDistance.levenshtein(str1, str2, true);
}
import java.util.Comparator;
public interface TextCompletionValueDescriptor<T> extends Comparator<T> {
@NotNull
LookupElementBuilder createLookupBuilder(@NotNull T item);
}
@@ -0,0 +1,65 @@
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.textCompletion;
import com.intellij.codeInsight.AutoPopupController;
import com.intellij.openapi.editor.SpellCheckingEditorCustomizationProvider;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.fileTypes.PlainTextLanguage;
import com.intellij.openapi.project.Project;
import com.intellij.ui.EditorCustomization;
import com.intellij.ui.LanguageTextField;
import org.jetbrains.annotations.NotNull;
public class TextFieldWithCompletion extends LanguageTextField {
private final boolean myForceAutoPopup;
private final boolean myShowHint;
public TextFieldWithCompletion(@NotNull Project project,
@NotNull TextCompletionProvider provider,
@NotNull String value,
boolean oneLineMode,
boolean forceAutoPopup,
boolean showHint) {
this(project, provider, value, oneLineMode, true, forceAutoPopup, showHint);
}
public TextFieldWithCompletion(@NotNull Project project,
@NotNull TextCompletionProvider provider,
@NotNull String value,
boolean oneLineMode,
boolean autoPopup,
boolean forceAutoPopup,
boolean showHint) {
super(PlainTextLanguage.INSTANCE, project, value, new TextCompletionUtil.DocumentWithCompletionCreator(provider, autoPopup), oneLineMode);
myForceAutoPopup = forceAutoPopup;
myShowHint = showHint;
}
@Override
protected EditorEx createEditor() {
EditorEx editor = super.createEditor();
EditorCustomization disableSpellChecking = SpellCheckingEditorCustomizationProvider.getInstance().getDisabledCustomization();
if (disableSpellChecking != null) disableSpellChecking.customize(editor);
editor.putUserData(AutoPopupController.ALWAYS_AUTO_POPUP, myForceAutoPopup);
if (myShowHint) {
TextCompletionUtil.installCompletionHint(editor);
}
return editor;
}
}
@@ -0,0 +1,121 @@
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.textCompletion;
import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.completion.PlainPrefixMatcher;
import com.intellij.codeInsight.lookup.CharFilter;
import com.intellij.openapi.project.DumbAware;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class ValuesCompletionProvider<T> implements TextCompletionProvider {
@NotNull protected final TextCompletionValueDescriptor<T> myDescriptor;
@NotNull private final List<Character> mySeparators;
@NotNull protected final Collection<? extends T> myValues;
private final boolean myCaseSensitive;
public ValuesCompletionProvider(@NotNull TextCompletionValueDescriptor<T> descriptor,
@NotNull List<Character> separators,
@NotNull Collection<? extends T> values, boolean caseSensitive) {
myDescriptor = descriptor;
mySeparators = separators;
myValues = values;
myCaseSensitive = caseSensitive;
}
/*
Single-line single-value case-insensitive completion.
*/
public ValuesCompletionProvider(@NotNull TextCompletionValueDescriptor<T> presentation,
@NotNull Collection<? extends T> values) {
this(presentation, Collections.emptyList(), values, false);
}
@Nullable
@Override
public String getAdvertisement() {
return "";
}
@Nullable
@Override
public String getPrefix(@NotNull String text, int offset) {
return getPrefix(text, offset, mySeparators);
}
@NotNull
protected static String getPrefix(@NotNull String text, int offset, @NotNull Collection<Character> separators) {
int index = -1;
for (char c : separators) {
index = Math.max(text.lastIndexOf(c, offset - 1), index);
}
return text.substring(index + 1, offset);
}
@NotNull
@Override
public CompletionResultSet applyPrefixMatcher(@NotNull CompletionResultSet result, @NotNull String prefix) {
CompletionResultSet resultWithMatcher = result.withPrefixMatcher(new PlainPrefixMatcher(prefix));
if (!myCaseSensitive) resultWithMatcher = resultWithMatcher.caseInsensitive();
return resultWithMatcher;
}
@Override
@Nullable
public CharFilter.Result acceptChar(char c) {
if (!mySeparators.contains(c)) return CharFilter.Result.ADD_TO_PREFIX;
return CharFilter.Result.HIDE_LOOKUP;
}
@Override
public void fillCompletionVariants(@NotNull CompletionParameters parameters,
@NotNull String prefix,
@NotNull CompletionResultSet result) {
Collection<? extends T> values = getValues(prefix, result);
values = ContainerUtil.sorted(values, myDescriptor);
for (T completionVariant : values) {
result.addElement(myDescriptor.createLookupBuilder(completionVariant));
}
result.stopHere();
}
@NotNull
protected Collection<? extends T> getValues(@NotNull String prefix, @NotNull CompletionResultSet result) {
return myValues;
}
public static class ValuesCompletionProviderDumbAware<T> extends ValuesCompletionProvider<T> implements DumbAware {
public ValuesCompletionProviderDumbAware(@NotNull TextCompletionValueDescriptor<T> descriptor,
@NotNull List<Character> separators,
@NotNull Collection<? extends T> values,
boolean caseSensitive) {
super(descriptor, separators, values, caseSensitive);
}
public ValuesCompletionProviderDumbAware(@NotNull TextCompletionValueDescriptor<T> presentation,
@NotNull Collection<? extends T> values) {
super(presentation, values);
}
}
}
@@ -27,7 +27,6 @@ import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Pair;
import com.intellij.diff.DiffDialogHints;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.actions.ShowDiffUIContext;
import com.intellij.openapi.vcs.changes.actions.diff.ShowDiffAction;
import com.intellij.openapi.vcs.changes.actions.diff.ShowDiffContext;
import com.intellij.openapi.vcs.changes.ui.ChangeNodeDecorator;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,14 +18,21 @@ package com.intellij.application.options;
/**
* @author Denis Zhdanov
* @since 4/25/11 4:23 PM
* @deprecated
* @use com.intellij.application.options.EditorFontsConstants
*/
public class OptionsConstants {
@Deprecated
public static final int MIN_EDITOR_FONT_SIZE = 4;
@Deprecated
public static final int MAX_EDITOR_FONT_SIZE = 40;
@Deprecated
public static final int DEFAULT_EDITOR_FONT_SIZE = 12;
@Deprecated
public static final float MIN_EDITOR_LINE_SPACING = .6F;
@Deprecated
public static final float MAX_EDITOR_LINE_SPACING = 3;
@Deprecated
public static final float DEFAULT_EDITOR_LINE_SPACING = 1;
private OptionsConstants() {
@@ -94,7 +94,8 @@ public class ProcessInfo {
@Override
public String toString() {
return myPid + " '" + myCommandLine + "' '" + myExecutableName + "' '" + myArgs + "'";
return myPid + " '" + myCommandLine + "' '" + myExecutableName + "' '" + myArgs + "'" +
(myExecutablePath.isPresent() ? " " + myExecutablePath.get() : "");
}
@Override
@@ -108,6 +109,7 @@ public class ProcessInfo {
if (!myExecutableName.equals(info.myExecutableName)) return false;
if (!myArgs.equals(info.myArgs)) return false;
if (!myCommandLine.equals(info.myCommandLine)) return false;
if (!myExecutablePath.equals(info.myExecutablePath)) return false;
return true;
}
@@ -305,7 +305,7 @@ public class ProcessListUtil {
String name = line.substring(0, commandLineStart).trim();
if (name.isEmpty()) continue;
String commandLine = line.substring(commandLineStart, pidStart).trim();
String commandLine = line.substring(commandLineStart, executablePathStart).trim();
String args = "";
if (commandLine.isEmpty()) {
@@ -21,9 +21,7 @@ import com.intellij.ide.plugins.PluginManager;
import com.intellij.ide.ui.UISettings;
import com.intellij.idea.IdeaApplication;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.*;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.application.impl.LaterInvocator;
import com.intellij.openapi.diagnostic.FrequentEventDetector;
@@ -385,6 +383,7 @@ public class IdeEventQueue extends EventQueue {
}
AWTEvent oldEvent = myCurrentEvent;
myCurrentEvent = e;
AccessToken token = ((TransactionGuardImpl)TransactionGuard.getInstance()).startActivity(myIsInInputEvent);
try {
_dispatchEvent(e, false);
@@ -393,6 +392,7 @@ public class IdeEventQueue extends EventQueue {
processException(t);
}
finally {
token.finish();
myIsInInputEvent = wasInputEvent;
myCurrentEvent = oldEvent;
@@ -0,0 +1,147 @@
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.ui;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.util.ui.ImageUtil;
import com.intellij.util.ui.JBDimension;
import com.intellij.util.ui.JBInsets;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.awt.image.ImageFilter;
/**
* @author Sergey.Malenkov
*/
public class ColorBlindnessInternalAction extends DumbAwareAction {
@Override
public void actionPerformed(AnActionEvent event) {
new ColorDialog(event).show();
}
private static final class ColorDialog extends DialogWrapper {
private final ColorView myView = new ColorView();
private ColorDialog(AnActionEvent event) {
super(event.getProject());
init();
setTitle("ColorBlindness");
}
@Override
protected JComponent createCenterPanel() {
myView.setMinimumSize(new JBDimension(360, 200));
myView.setPreferredSize(new JBDimension(720, 400));
JComboBox combo = new ComboBox<>(FilterItem.ALL);
combo.addItemListener(myView);
JPanel panel = new JPanel(new BorderLayout(10, 10));
panel.add(BorderLayout.CENTER, myView);
panel.add(BorderLayout.SOUTH, combo);
return panel;
}
@NotNull
@Override
protected Action[] createActions() {
return new Action[]{getCancelAction()};
}
}
private static final class FilterItem {
private final ImageFilter myFilter;
public FilterItem(ImageFilter filter) {
myFilter = filter;
}
@Override
public String toString() {
return myFilter == null ? "No filtering" : myFilter.toString();
}
private static final FilterItem[] ALL = new FilterItem[]{
new FilterItem(null),
new FilterItem(DaltonizationFilter.protanopia),
new FilterItem(DaltonizationFilter.forProtanopia(.5)),
new FilterItem(DaltonizationFilter.deuteranopia),
new FilterItem(DaltonizationFilter.forDeuteranopia(.5)),
new FilterItem(DaltonizationFilter.tritanopia),
new FilterItem(DaltonizationFilter.forTritanopia(.5)),
new FilterItem(SimulationFilter.protanopia),
new FilterItem(SimulationFilter.forProtanopia(.5)),
new FilterItem(SimulationFilter.deuteranopia),
new FilterItem(SimulationFilter.forDeuteranopia(.5)),
new FilterItem(SimulationFilter.tritanopia),
new FilterItem(SimulationFilter.forTritanopia(.5)),
new FilterItem(SimulationFilter.achromatopsia),
new FilterItem(SimulationFilter.forAchromatopsia(.5)),
};
}
private static final class ColorView extends JComponent implements ItemListener {
private ImageFilter myFilter;
private Image myImage;
@Override
protected void paintComponent(Graphics g) {
Rectangle bounds = new Rectangle(getWidth(), getHeight());
JBInsets.removeFrom(bounds, getInsets());
if (bounds.isEmpty()) return;
if (myImage == null || bounds.width != myImage.getWidth(this) || bounds.height != myImage.getHeight(this)) {
int[] array = new int[bounds.width * bounds.height];
float width = (float)(bounds.width - 1);
float height = (float)(bounds.height - 1);
for (int i = 0, h = 0; h < bounds.height; h++) {
for (int w = 0; w < bounds.width; w++, i++) {
float level = 2 * h / height;
float saturation = (level > 1f) ? 1 : level;
float brightness = (level > 1f) ? 2 - level : 1;
array[i] = Color.HSBtoRGB(w / width, saturation, brightness);
}
}
BufferedImage image = UIUtil.createImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_RGB);
image.setRGB(0, 0, bounds.width, bounds.height, array, 0, bounds.width);
myImage = ImageUtil.filter(image, myFilter);
}
g.drawImage(myImage, bounds.x, bounds.y, bounds.width, bounds.height, this);
}
@Override
public void itemStateChanged(ItemEvent event) {
if (ItemEvent.SELECTED == event.getStateChange()) {
Object object = event.getItem();
if (object instanceof FilterItem) {
FilterItem item = (FilterItem)object;
myFilter = item.myFilter;
myImage = null;
repaint();
}
}
}
}
}
@@ -29,10 +29,7 @@ import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.actionSystem.ex.AnActionListener;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationActivationListener;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.*;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.PluginId;
@@ -1298,15 +1295,14 @@ public final class ActionManagerImpl extends ActionManagerEx implements Disposab
private void tryToExecuteNow(final AnAction action, final InputEvent inputEvent, final Component contextComponent, final String place, final ActionCallback result) {
final Presentation presentation = action.getTemplatePresentation().clone();
IdeFocusManager.findInstanceByContext(getContextBy(contextComponent)).doWhenFocusSettlesDown(new Runnable() {
@Override
public void run() {
IdeFocusManager.findInstanceByContext(getContextBy(contextComponent)).doWhenFocusSettlesDown(
() -> TransactionGuard.getInstance().performUserActivity(() -> {
final DataContext context = getContextBy(contextComponent);
AnActionEvent event = new AnActionEvent(
inputEvent, context,
place != null ? place : ActionPlaces.UNKNOWN,
presentation, ActionManagerImpl.this,
presentation, this,
inputEvent.getModifiersEx()
);
@@ -1346,7 +1342,7 @@ public final class ActionManagerImpl extends ActionManagerEx implements Disposab
result.setDone();
queueActionPerformedEvent(action, context, event);
}
});
));
}
private class MyTimer extends Timer implements ActionListener {
@@ -1229,9 +1229,9 @@ public class ApplicationImpl extends PlatformComponentManagerImpl implements App
private void startWrite(/*@NotNull*/ Class clazz) {
assertIsDispatchThread(getStatus(), "Write access is allowed from event dispatch thread only");
HeavyProcessLatch.INSTANCE.stopThreadPrioritizing(); // let non-cancellable read actions complete faster, if present
if (Registry.is("ide.require.transaction.for.model.changes", false)) {
TransactionGuard.getInstance().assertInsideTransaction(
true, "Write access is allowed from model transactions only, see TransactionGuard documentation for details");
if (!((TransactionGuardImpl)TransactionGuard.getInstance()).isWriteActionAllowed()) {
// please assign exceptions here to Peter
LOG.error("Write access is allowed from model transactions only, see TransactionGuard documentation for details");
}
boolean writeActionPending = myWriteActionPending;
if (gatherWriteActionStatistics && myWriteActionsStack.isEmpty() && !writeActionPending) {
@@ -28,12 +28,11 @@ import com.intellij.injected.editor.EditorWindow;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.actionSystem.EditorAction;
import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler;
import com.intellij.util.ui.MacUIUtil;
import org.jetbrains.annotations.NotNull;
public class BackspaceAction extends EditorAction {
public class BackspaceAction extends TextComponentEditorAction {
public BackspaceAction() {
super(new Handler());
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,7 +15,7 @@
*/
package com.intellij.openapi.editor.actions;
import com.intellij.application.options.OptionsConstants;
import com.intellij.application.options.EditorFontsConstants;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
@@ -41,7 +41,7 @@ public abstract class ChangeEditorFontSizeAction extends AnAction implements Dum
final EditorImpl editor = getEditor(e);
if (editor != null) {
final int size = editor.getFontSize() + myStep;
if (size >= 8 && size <= OptionsConstants.MAX_EDITOR_FONT_SIZE) {
if (size >= 8 && size <= EditorFontsConstants.getMaxEditorFontSize()) {
editor.setFontSize(size);
}
}
@@ -20,6 +20,7 @@ import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.VisualPosition;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import org.jetbrains.annotations.Nullable;
class NextPrevWordHandler extends EditorActionHandler {
@@ -37,21 +38,28 @@ class NextPrevWordHandler extends EditorActionHandler {
@Override
protected void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
assert caret != null;
VisualPosition currentPosition = caret.getVisualPosition();
if (caret.isAtBidiRunBoundary() && (myNext ^ currentPosition.leansRight)) {
if (EditorUtil.isPasswordEditor(editor)) {
int selectionStartOffset = caret.getLeadSelectionOffset();
VisualPosition selectionStartPosition = caret.getLeadSelectionPosition();
caret.moveToVisualPosition(currentPosition.leanRight(!currentPosition.leansRight));
if (myWithSelection) {
caret.setSelection(selectionStartPosition, selectionStartOffset, caret.getVisualPosition(), caret.getOffset());
}
caret.moveToOffset(myNext ? editor.getDocument().getTextLength() : 0);
if (myWithSelection) caret.setSelection(selectionStartOffset, caret.getOffset());
}
else {
if (myNext ^ caret.isAtRtlLocation()) {
EditorActionUtil.moveCaretToNextWord(editor, myWithSelection, myInDifferentHumpsMode ^ editor.getSettings().isCamelWords());
VisualPosition currentPosition = caret.getVisualPosition();
if (caret.isAtBidiRunBoundary() && (myNext ^ currentPosition.leansRight)) {
int selectionStartOffset = caret.getLeadSelectionOffset();
VisualPosition selectionStartPosition = caret.getLeadSelectionPosition();
caret.moveToVisualPosition(currentPosition.leanRight(!currentPosition.leansRight));
if (myWithSelection) {
caret.setSelection(selectionStartPosition, selectionStartOffset, caret.getVisualPosition(), caret.getOffset());
}
}
else {
EditorActionUtil.moveCaretToPreviousWord(editor, myWithSelection, myInDifferentHumpsMode ^ editor.getSettings().isCamelWords());
if (myNext ^ caret.isAtRtlLocation()) {
EditorActionUtil.moveCaretToNextWord(editor, myWithSelection, myInDifferentHumpsMode ^ editor.getSettings().isCamelWords());
}
else {
EditorActionUtil.moveCaretToPreviousWord(editor, myWithSelection, myInDifferentHumpsMode ^ editor.getSettings().isCamelWords());
}
}
}
}
@@ -65,6 +65,10 @@ public final class EditorUtil {
return editor != null && TextEditorProvider.getInstance().getTextEditor(editor) instanceof TextEditorImpl;
}
public static boolean isPasswordEditor(@Nullable Editor editor) {
return editor != null && editor.getContentComponent() instanceof JPasswordField;
}
public static int getLastVisualLineColumnNumber(@NotNull Editor editor, final int line) {
if (editor instanceof EditorImpl && ((EditorImpl)editor).myUseNewRendering) {
LogicalPosition lineEndPosition = editor.visualToLogicalPosition(new VisualPosition(line, Integer.MAX_VALUE));
@@ -15,7 +15,7 @@
*/
package com.intellij.openapi.editor.impl;
import com.intellij.application.options.OptionsConstants;
import com.intellij.application.options.EditorFontsConstants;
import com.intellij.codeInsight.hint.DocumentFragmentTooltipRenderer;
import com.intellij.codeInsight.hint.EditorFragmentComponent;
import com.intellij.codeInsight.hint.TooltipController;
@@ -30,7 +30,8 @@ import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.impl.MouseGestureManager;
import com.intellij.openapi.application.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.diagnostic.Logger;
@@ -6338,7 +6339,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi
private final Map<ColorKey, Color> myOwnColors = ContainerUtilRt.newHashMap();
private final EditorColorsScheme myCustomGlobalScheme;
private Map<EditorFontType, Font> myFontsMap;
private int myMaxFontSize = OptionsConstants.MAX_EDITOR_FONT_SIZE;
private int myMaxFontSize = EditorFontsConstants.getMaxEditorFontSize();
private int myFontSize = -1;
private int myConsoleFontSize = -1;
private String myFaceName;
@@ -6510,7 +6511,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi
public void setDelegate(@NotNull EditorColorsScheme delegate) {
super.setDelegate(delegate);
int globalFontSize = getDelegate().getEditorFontSize();
myMaxFontSize = Math.max(OptionsConstants.MAX_EDITOR_FONT_SIZE, globalFontSize);
myMaxFontSize = Math.max(EditorFontsConstants.getMaxEditorFontSize(), globalFontSize);
reinitFonts();
clearSettingsCache();
}
@@ -148,9 +148,13 @@ public class ScrollingModelImpl implements ScrollingModelEx {
}
private void scrollTo(@NotNull VisualPosition pos, @NotNull ScrollType scrollType) {
Point targetLocation = myEditor.visualPositionToXY(pos);
scrollTo(targetLocation, scrollType);
}
private void scrollTo(@NotNull Point targetLocation, @NotNull ScrollType scrollType) {
AnimatedScrollingRunnable canceledThread = cancelAnimatedScrolling(false);
Rectangle viewRect = canceledThread != null ? canceledThread.getTargetVisibleArea() : getVisibleArea();
Point targetLocation = myEditor.visualPositionToXY(pos);
Point p = calcOffsetsToScroll(targetLocation, scrollType, viewRect);
scrollToOffsets(p.x, p.y);
}
@@ -159,11 +163,8 @@ public class ScrollingModelImpl implements ScrollingModelEx {
public void scrollTo(@NotNull LogicalPosition pos, @NotNull ScrollType scrollType) {
assertIsDispatchThread();
AnimatedScrollingRunnable canceledThread = cancelAnimatedScrolling(false);
Rectangle viewRect = canceledThread != null ? canceledThread.getTargetVisibleArea() : getVisibleArea();
Point targetLocation = myEditor.logicalPositionToXY(pos);
Point p = calcOffsetsToScroll(targetLocation, scrollType, viewRect);
scrollToOffsets(p.x, p.y);
scrollTo(targetLocation, scrollType);
}
private static void assertIsDispatchThread() {
@@ -15,18 +15,21 @@
*/
package com.intellij.openapi.fileChooser.actions;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.fileChooser.FileSystemTree;
import com.intellij.openapi.vfs.newvfs.ManagingFS;
import com.intellij.openapi.vfs.newvfs.RefreshQueue;
/**
* @author yole
*/
public class RefreshFileChooserAction extends AnAction implements DumbAware {
public void actionPerformed(final AnActionEvent e) {
*/
public class RefreshFileChooserAction extends FileChooserAction {
protected void update(FileSystemTree fileChooser, AnActionEvent e) {
}
@Override
protected void actionPerformed(FileSystemTree fileChooser, AnActionEvent e) {
RefreshQueue.getInstance().refresh(true, true, null, ModalityState.current(), ManagingFS.getInstance().getLocalRoots());
}
}
@@ -868,17 +868,15 @@ public final class IdeKeyEventDispatcher implements Disposable {
}
private static void invokeAction(@NotNull final AnAction action, final DataContext ctx) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().invokeLater(
() -> TransactionGuard.getInstance().performUserActivity(() -> {
final AnActionEvent event =
new AnActionEvent(null, ctx, ActionPlaces.UNKNOWN, action.getTemplatePresentation().clone(),
ActionManager.getInstance(), 0);
if (ActionUtil.lastUpdateAndCheckDumb(action, event, true)) {
ActionUtil.performActionDumbAware(action, event);
}
}
});
}));
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,6 +24,7 @@ import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.LicensingFacade;
import com.intellij.util.text.DateFormatUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -32,6 +33,7 @@ import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.awt.*;
import java.util.Date;
/**
* @author anna
@@ -40,8 +42,6 @@ public abstract class AbstractUpdateDialog extends DialogWrapper {
private final boolean myEnableLink;
protected String myLicenseInfo = null;
protected boolean myPaidUpgrade;
protected boolean mySubscriptionLicense = false;
protected AbstractUpdateDialog(boolean enableLink) {
super(true);
@@ -71,56 +71,44 @@ public abstract class AbstractUpdateDialog extends DialogWrapper {
}
protected void restart() {
final ApplicationEx app = ApplicationManagerEx.getApplicationEx();
// do not stack several modal dialogs (native & swing)
app.invokeLater(new Runnable() {
@Override
public void run() {
app.restart(true);
}
});
ApplicationEx app = ApplicationManagerEx.getApplicationEx();
app.invokeLater(() -> app.restart(true));
}
protected void initLicensingInfo(@NotNull UpdateChannel channel, @NotNull BuildInfo build) {
protected void initLicensingInfo(@NotNull UpdateChannel channel, @SuppressWarnings("UnusedParameters") @NotNull BuildInfo build) {
LicensingFacade facade = LicensingFacade.getInstance();
if (facade != null) {
mySubscriptionLicense = facade.isSubscriptionLicense();
if (!channel.getLicensing().equals(UpdateChannel.LICENSING_EAP)) {
int majorVersion = build.getMajorVersion();
if (majorVersion < 0) {
majorVersion = channel.getMajorVersion(); // fallback
}
final Boolean paidUpgrade = facade.isPaidUpgrade(majorVersion, build.getReleaseDate());
if (paidUpgrade == Boolean.TRUE) {
myPaidUpgrade = true;
myLicenseInfo = IdeBundle.message("updates.channel.key.needed", channel.getEvalDays());
}
else if (paidUpgrade == Boolean.FALSE) {
myLicenseInfo = IdeBundle.message("updates.channel.existing.key");
}
if (channel.getLicensing().equals(UpdateChannel.LICENSING_EAP)) {
myLicenseInfo = IdeBundle.message("updates.channel.bundled.key");
}
else {
myLicenseInfo = IdeBundle.message("updates.channel.bundled.key");
Date buildDate = build.getReleaseDate();
Date expiration = facade.getLicenseExpirationDate();
if (buildDate != null && facade.isPerpetualForProduct(buildDate)) {
myLicenseInfo = IdeBundle.message("updates.fallback.build");
}
else if (expiration != null && expiration.after(new Date())) {
myLicenseInfo = IdeBundle.message("updates.subscription.active.till", DateFormatUtil.formatAboutDialogDate(expiration));
}
}
}
}
protected void configureMessageArea(@NotNull JEditorPane area) {
String messageBody = myEnableLink ? IdeBundle.message("updates.configure.label", ShowSettingsUtil.getSettingsMenuName()) : "";
configureMessageArea(area, messageBody, null, null);
}
protected void configureMessageArea(final @NotNull JEditorPane area,
protected void configureMessageArea(@NotNull JEditorPane area,
@NotNull String messageBody,
@Nullable Color fontColor,
@Nullable HyperlinkListener listener) {
String text = "<html><head>" +
UIUtil.getCssFontDeclaration(UIUtil.getLabelFont(), fontColor, null, null) +
"<style>body {background: #" + ColorUtil.toHex(UIUtil.getPanelBackground()) + ";}</style>" +
"</head><body>" +
messageBody +
"</body></html>";
String text =
"<html><head>" +
UIUtil.getCssFontDeclaration(UIUtil.getLabelFont(), fontColor, null, null) +
"<style>body {background: #" + ColorUtil.toHex(UIUtil.getPanelBackground()) + ";}</style>" +
"</head><body>" + messageBody + "</body></html>";
area.setBackground(UIUtil.getPanelBackground());
area.setBorder(IdeBorderFactory.createEmptyBorder());
@@ -128,13 +116,9 @@ public abstract class AbstractUpdateDialog extends DialogWrapper {
area.setEditable(false);
if (listener == null && myEnableLink) {
listener = new HyperlinkListener() {
@Override
public void hyperlinkUpdate(final HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
UpdateSettingsConfigurable settings = new UpdateSettingsConfigurable(false);
ShowSettingsUtil.getInstance().editConfigurable(area, settings);
}
listener = (e) -> {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
ShowSettingsUtil.getInstance().editConfigurable(area, new UpdateSettingsConfigurable(false));
}
};
}
@@ -142,4 +126,4 @@ public abstract class AbstractUpdateDialog extends DialogWrapper {
area.addHyperlinkListener(listener);
}
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,13 +18,11 @@ package com.intellij.openapi.updateSettings.impl;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.IdeBundle;
import com.intellij.ui.BrowserHyperlinkListener;
import com.intellij.ui.LicensingFacade;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.List;
import java.util.Objects;
/**
* @author yole
@@ -52,31 +50,19 @@ class NewChannelDialog extends AbstractUpdateDialog {
@NotNull
@Override
protected Action[] createActions() {
List<Action> actions = ContainerUtil.newArrayList(getOKAction());
return new Action[]{
getOKAction(),
if (myPaidUpgrade) {
actions.add(new AbstractAction(IdeBundle.message("updates.buy.online.button")) {
new AbstractAction(IdeBundle.message("updates.remind.later.button")) {
@Override
public void actionPerformed(ActionEvent e) {
LicensingFacade facade = LicensingFacade.getInstance();
assert facade != null;
BrowserUtil.browse(facade.getUpgradeUrl());
UpdateSettings.getInstance().forgetChannelId(myChannel.getId());
doCancelAction();
}
});
}
},
actions.add(new AbstractAction(IdeBundle.message("updates.remind.later.button")) {
@Override
public void actionPerformed(ActionEvent e) {
UpdateSettings.getInstance().forgetChannelId(myChannel.getId());
doCancelAction();
}
});
actions.add(getCancelAction());
return actions.toArray(new Action[actions.size()]);
getCancelAction()
};
}
@Override
@@ -91,7 +77,7 @@ class NewChannelDialog extends AbstractUpdateDialog {
@Override
protected void doOKAction() {
BrowserUtil.browse(myChannel.getHomePageUrl());
BrowserUtil.browse(Objects.requireNonNull(myChannel.getHomePageUrl(), "missing URL for channel " + myChannel.getId()));
super.doOKAction();
}
@@ -112,4 +98,4 @@ class NewChannelDialog extends AbstractUpdateDialog {
}
}
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -236,7 +236,7 @@ class UpdateInfoDialog extends AbstractUpdateDialog {
}
if (myLicenseInfo != null) {
configureMessageArea(myLicenseArea, myLicenseInfo, myPaidUpgrade ? JBColor.RED : null, null);
configureMessageArea(myLicenseArea, myLicenseInfo, null, null);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,6 +15,7 @@
*/
package com.intellij.ui;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Date;
@@ -32,11 +33,13 @@ public abstract class LicensingFacade {
}
public abstract String getLicensedToMessage();
public abstract List<String> getLicenseRestrictionsMessages();
public abstract boolean isEvaluationLicense();
public abstract boolean isSubscriptionLicense();
public abstract boolean isPerpetualForProduct(@NotNull Date productBuildDate);
@Nullable
public abstract Boolean isPaidUpgrade(int majorVersion, Date releaseDate);
public abstract String getUpgradeUrl();
}
public abstract Date getLicenseExpirationDate();
}
@@ -28,6 +28,7 @@ import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.TransactionGuard;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
@@ -1392,7 +1393,7 @@ public class AbstractPopup implements JBPopup {
//noinspection SSBasedInspection
SwingUtilities.invokeLater(() -> {
if (ModalityState.current().equals(modalityState)) {
finalRunnable.run();
TransactionGuard.getInstance().performUserActivity(finalRunnable::run);
}
// Otherwise the UI has changed unexpectedly and the action is likely not applicable.
// And we don't want finalRunnable to perform potentially destructive actions
@@ -57,6 +57,8 @@ select.external.diff.program.dialog.title=Select External Diff Program
select.external.merge.program.dialog.title=Select External Merge Program
diff.contents.are.identical.message.text=Contents are identical
diff.contents.have.differences.only.in.line.separators.message.text=Contents have differences only in line separators
diff.contents.have.differences.only.in.charset.message.text=Contents have differences only in encoding
diff.contents.have.differences.only.in.charset.and.line.separators.message.text=Contents have differences only in line separators and encoding
diff.contents.have.differences.only.in.line.separators.or.whitespaces=Contents have differences only in line separators or whitespaces
show.diff.anyway.dialog.message=Show diff anyway?
no.differences.dialog.title=No Differences
@@ -907,9 +907,9 @@ updates.error.plugin.description.failed=Failed to load plugin descriptions from:
update.notifications.title=Platform and Plugin Updates
update.notifications.group=Platform and Plugin Updates
updates.channel.name.message=<b>{0}</b>: {1}
updates.channel.key.needed=You can evaluate the new version for {0} days or buy a license key or an upgrade online.
updates.channel.existing.key=The new version can be used with your existing license key.
updates.channel.bundled.key=The new version has an expiration date and does not require a license key.
updates.fallback.build=You have perpetual fallback license for the new version.
updates.subscription.active.till=Your subscription is active until {0}.
updates.ready.message={0} is ready to <a href=\"update\">update</a>.
updates.plugins.ready.message=The following plugin{0,choice,1# is|2#s are} ready to <a href=\"update\">update</a>: {1}
updates.no.updates.message=You already have the latest version of {0} installed.
@@ -923,7 +923,6 @@ updates.more.info.button=&More Info...
updates.download.page.button=Open &Download Page
updates.ignore.update.button=&Ignore This Update
updates.remind.later.button=&Remind Me Later
updates.buy.online.button=&Buy Upgrade Online
updates.new.version.available=<b>A new version of {0} is <a href=\"#\">available</a>!</b>
updates.current.version=Current version:
updates.available.version=New version:
@@ -877,11 +877,9 @@
<customFoldingProvider implementation="com.intellij.lang.customFolding.NetBeansCustomFoldingProvider"/>
<customFoldingProvider implementation="com.intellij.lang.customFolding.VisualStudioCustomFoldingProvider"/>
<completion.contributor language="TEXT" implementationClass="com.intellij.ui.TextFieldWithAutoCompletionContributor"
order="first, before commitCompletion"/>
<completion.contributor language="TEXT" implementationClass="com.intellij.util.CompletionContributorForTextField"
<completion.contributor language="TEXT" implementationClass="com.intellij.util.textCompletion.TextCompletionContributor"
order="first, before commitCompletion"/>
<lookup.charFilter implementation="com.intellij.util.textCompletion.TextCompletionCharFilter"/>
<completion.contributor language="any" implementationClass="com.intellij.codeInsight.completion.CustomFileTypeCompletionContributor"/>
@@ -692,9 +692,6 @@
<action id="XDebugger.SetValue">
<keyboard-shortcut first-keystroke="F2"/>
</action>
<action id="XDebugger.EditWatch">
<keyboard-shortcut first-keystroke="F2"/>
</action>
<action id="XDebugger.NewWatch">
<keyboard-shortcut first-keystroke="INSERT"/>
</action>
@@ -725,7 +725,7 @@
<action id="Debugger.Tree.EvaluateInConsole" class="com.intellij.xdebugger.impl.ui.tree.actions.EvaluateInConsoleFromTreeAction"/>
<action id="XDebugger.NewWatch" class="com.intellij.xdebugger.impl.frame.actions.XNewWatchAction" icon="AllIcons.Debugger.NewWatch"/>
<action id="XDebugger.EditWatch" class="com.intellij.xdebugger.impl.frame.actions.XEditWatchAction"/>
<action id="XDebugger.EditWatch" class="com.intellij.xdebugger.impl.frame.actions.XEditWatchAction" use-shortcut-of="XDebugger.SetValue"/>
<action id="XDebugger.CopyWatch" class="com.intellij.xdebugger.impl.frame.actions.XCopyWatchAction" icon="AllIcons.Actions.Copy"
text="Copy Watch" use-shortcut-of="EditorDuplicate"/>
<action id="XDebugger.RemoveWatch" class="com.intellij.xdebugger.impl.frame.actions.XRemoveWatchAction" icon="AllIcons.Actions.Delete"
@@ -702,6 +702,7 @@
<action id="ShowSplash" internal="true" class="com.intellij.ui.ShowSplashAction" text="Show Splash" />
<action id="ValidationTest" internal="true" class="com.intellij.internal.validation.TestDialogWithValidationAction" text="Validation Dialog Test" />
<action id="MacMessagesTest" internal="true" class="com.intellij.internal.validation.TestMacMessagesAction" text="Test Mac Messages" />
<action id="ColorBlindnessTest" internal="true" class="com.intellij.ide.ui.ColorBlindnessInternalAction" text="Test ColorBlindness" />
<action id="TreeExpandAll" internal="true" class="com.intellij.internal.tree.ExpandAll" text="Expand Tree" />
<action id="UIDefaults" internal="true" class="com.intellij.ui.ShowUIDefaultsAction" text="LaF Defaults">
<abbreviation value="laf"/>
@@ -45,9 +45,9 @@ public class ProcessListTest extends UsefulTestCase {
" 3 S user ./dir/dir/file param param"
);
assertOrderedEquals(infos,
new ProcessInfo(1, "/dir/file", "file", ""),
new ProcessInfo(2, "./dir/dir/file", "file", ""),
new ProcessInfo(3, "./dir/dir/file param param", "file", "param param"));
new ProcessInfo(1, "/dir/file", "file", "", "/dir/file"),
new ProcessInfo(2, "./dir/dir/file", "file", "", "./dir/dir/file"),
new ProcessInfo(3, "./dir/dir/file param param", "file", "param param", "./dir/dir/file"));
}
public void testMac_DoNotIncludeProcessedMissingOnTheSecondPSRun() throws Exception {
@@ -59,7 +59,7 @@ public class ProcessListTest extends UsefulTestCase {
" 1 S user /dir/file\n" +
" 5 S user /dir/file\n"
);
assertOrderedEquals(infos, new ProcessInfo(1, "/dir/file", "file", ""));
assertOrderedEquals(infos, new ProcessInfo(1, "/dir/file", "file", "", "/dir/file"));
}
public void testMac_DoNotIncludeProcessedChangedOnTheSecondPSRun() throws Exception {
@@ -75,7 +75,7 @@ public class ProcessListTest extends UsefulTestCase {
" 3 S user /dir/file1\n" +
" 4 S user /dir/file/1\n"
);
assertOrderedEquals(infos, new ProcessInfo(1, "/dir/file param", "file", "param"));
assertOrderedEquals(infos, new ProcessInfo(1, "/dir/file param", "file", "param", "/dir/file"));
}
public void testMac_DoNotIncludeZombies() throws Exception {
@@ -89,7 +89,7 @@ public class ProcessListTest extends UsefulTestCase {
" 2 Z user /dir/file\n" +
" 3 SZ user /dir/file\n"
);
assertOrderedEquals(infos, new ProcessInfo(1, "/dir/file", "file", ""));
assertOrderedEquals(infos, new ProcessInfo(1, "/dir/file", "file", "", "/dir/file"));
}
public void testMac_VariousFormsPidStatUser() throws Exception {
@@ -102,8 +102,8 @@ public class ProcessListTest extends UsefulTestCase {
" 101 Ss user_name /dir/file\n"
);
assertOrderedEquals(infos,
new ProcessInfo(1, "/dir/file", "file", ""),
new ProcessInfo(101, "/dir/file", "file", ""));
new ProcessInfo(1, "/dir/file", "file", "", "/dir/file"),
new ProcessInfo(101, "/dir/file", "file", "", "/dir/file"));
}
public void testMac_WrongFormat() throws Exception {
@@ -146,28 +146,28 @@ public class ProcessListTest extends UsefulTestCase {
public void testWindows_WMIC() throws Exception {
List<ProcessInfo> infos = ProcessListUtil.parseWMICOutput(
"Caption CommandLine ProcessId \n" +
"smss.exe 304 \n" +
"sihost.exe sihost.exe 3052 \n" +
"taskhostw.exe taskhostw.exe {222A245B-E637-4AE9-A93F-A59CA119A75E} 3068 \n" +
"explorer.exe C:\\WINDOWS\\Explorer.EXE 3164 \n" +
"TPAutoConnect.exe TPAutoConnect.exe -q -i vmware -a COM1 -F 30 3336 \n" +
"conhost.exe \\??\\C:\\WINDOWS\\system32\\conhost.exe 0x4 3348 \n");
"Caption CommandLine ExecutablePath ProcessId \n" +
"smss.exe 304 \n" +
"sihost.exe sihost.exe 3052 \n" +
"taskhostw.exe taskhostw.exe {222A245B-E637-4AE9-A93F-A59CA119A75E} 3068 \n" +
"explorer.exe C:\\WINDOWS\\Explorer.EXE C:\\WINDOWS\\Explorer.EXE 3164 \n" +
"TPAutoConnect.exe TPAutoConnect.exe -q -i vmware -a COM1 -F 30 3336 \n" +
"conhost.exe \\??\\C:\\WINDOWS\\system32\\conhost.exe 0x4 \\??\\C:\\WINDOWS\\system32\\conhost.exe 3348 \n");
assertOrderedEquals(infos,
new ProcessInfo(304, "smss.exe", "smss.exe", ""),
new ProcessInfo(3052, "sihost.exe", "sihost.exe", ""),
new ProcessInfo(3068, "taskhostw.exe {222A245B-E637-4AE9-A93F-A59CA119A75E}", "taskhostw.exe", "{222A245B-E637-4AE9-A93F-A59CA119A75E}"),
new ProcessInfo(3164, "C:\\WINDOWS\\Explorer.EXE", "explorer.exe", ""),
new ProcessInfo(3164, "C:\\WINDOWS\\Explorer.EXE", "explorer.exe", "", "C:\\WINDOWS\\Explorer.EXE"),
new ProcessInfo(3336, "TPAutoConnect.exe -q -i vmware -a COM1 -F 30", "TPAutoConnect.exe", "-q -i vmware -a COM1 -F 30"),
new ProcessInfo(3348, "\\??\\C:\\WINDOWS\\system32\\conhost.exe 0x4", "conhost.exe", "0x4"));
new ProcessInfo(3348, "\\??\\C:\\WINDOWS\\system32\\conhost.exe 0x4", "conhost.exe", "0x4", "\\??\\C:\\WINDOWS\\system32\\conhost.exe"));
}
public void testOnWindows_WMIC_DoNotIncludeSystemIdleProcess() throws Exception {
List<ProcessInfo> infos = ProcessListUtil.parseWMICOutput(
"Caption CommandLine ProcessId \n" +
"System Idle Process 0 \n" +
"System 4 \n" +
"smss.exe 304 \n");
"Caption CommandLine ExecutablePath ProcessId \n" +
"System Idle Process 0 \n" +
"System 4 \n" +
"smss.exe 304 \n");
assertOrderedEquals(infos,
new ProcessInfo(4, "System", "System", ""),
new ProcessInfo(304, "smss.exe", "smss.exe", ""));
@@ -179,19 +179,19 @@ public class ProcessListTest extends UsefulTestCase {
assertNull(ProcessListUtil.parseWMICOutput(
"wrong format"));
assertEmpty(ProcessListUtil.parseWMICOutput(
"Caption CommandLine ProcessId \n"));
"Caption CommandLine ExecutablePath ProcessId \n"));
assertNull(ProcessListUtil.parseWMICOutput(
"smss.exe 304 \n"));
assertNull(ProcessListUtil.parseWMICOutput(
"Caption XXX ProcessId \n" +
"smss.exe 304 \n"));
"Caption XXX ExecutablePath ProcessId \n" +
"smss.exe 304 \n"));
assertNull(ProcessListUtil.parseWMICOutput(
"Caption CommandLine XXX \n" +
"smss.exe 304 \n"));
"Caption CommandLine ExecutablePath XXX \n" +
"smss.exe 304 \n"));
assertEmpty(ProcessListUtil.parseWMICOutput(
"Caption CommandLine ProcessId \n" +
" \n"));
"Caption CommandLine ExecutablePath ProcessId \n" +
" \n"));
}
public void testWindows_TaskList() throws Exception {
@@ -15,8 +15,10 @@
*/
package com.intellij.execution.testframework.autotest;
import com.intellij.execution.DelayedDocumentWatcher;
import com.intellij.execution.ExecutionManager;
import com.intellij.execution.*;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.impl.RunManagerImpl;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessHandler;
@@ -31,7 +33,7 @@ import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.*;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
@@ -39,24 +41,35 @@ import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.content.Content;
import com.intellij.util.Consumer;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xmlb.annotations.AbstractCollection;
import com.intellij.util.xmlb.annotations.Attribute;
import com.intellij.util.xmlb.annotations.Tag;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.List;
import java.util.Set;
/**
* @author yole
*/
public class AutoTestManager {
@State(
name = "AutoTestManager",
storages = {@Storage(StoragePathMacros.WORKSPACE_FILE)}
)
public class AutoTestManager implements PersistentStateComponent<AutoTestManager.State> {
private static final String AUTO_TEST_MANAGER_DELAY = "auto.test.manager.delay";
private static final int AUTO_TEST_MANAGER_DELAY_DEFAULT = 3000;
private static final Key<ProcessListener> ON_TERMINATION_RESTARTER_KEY = Key.create("auto.test.manager.on.termination.restarter");
private static final Key<ExecutionEnvironment> EXECUTION_ENVIRONMENT_KEY = Key.create("auto.test.manager.execution.environment");
private final Project myProject;
private int myDelayMillis;
private DelayedDocumentWatcher myDocumentWatcher;
private final Set<RunProfile> myEnabledRunProfiles = ContainerUtil.newHashSet();
@NotNull
public static AutoTestManager getInstance(Project project) {
@@ -92,11 +105,11 @@ public class AutoTestManager {
Content content = descriptor.getAttachedContent();
if (content != null) {
if (enabled) {
EXECUTION_ENVIRONMENT_KEY.set(content, environment);
myEnabledRunProfiles.add(environment.getRunProfile());
myDocumentWatcher.activate();
}
else {
EXECUTION_ENVIRONMENT_KEY.set(content, null);
myEnabledRunProfiles.remove(environment.getRunProfile());
if (!hasEnabledAutoTests()) {
myDocumentWatcher.deactivate();
}
@@ -122,19 +135,11 @@ public class AutoTestManager {
return isAutoTestEnabledForDescriptor(descriptor);
}
private static boolean isAutoTestEnabledForDescriptor(@NotNull RunContentDescriptor descriptor) {
private boolean isAutoTestEnabledForDescriptor(@NotNull RunContentDescriptor descriptor) {
Content content = descriptor.getAttachedContent();
if (content != null) {
ExecutionEnvironment watched = EXECUTION_ENVIRONMENT_KEY.get(content);
if (watched != null) {
ExecutionEnvironment current = getCurrentEnvironment(content);
boolean result = current != null && equals(current, watched);
if (!result) {
// let GC do its work
EXECUTION_ENVIRONMENT_KEY.set(content, null);
}
return result;
}
ExecutionEnvironment environment = getCurrentEnvironment(content);
return environment != null && myEnabledRunProfiles.contains(environment.getRunProfile());
}
return false;
}
@@ -148,13 +153,6 @@ public class AutoTestManager {
return LangDataKeys.EXECUTION_ENVIRONMENT.getData(DataManager.getInstance().getDataContext(component));
}
private static boolean equals(@NotNull ExecutionEnvironment env1, @NotNull ExecutionEnvironment env2) {
return env1.getRunProfile() == env2.getRunProfile() &&
env1.getRunner() == env2.getRunner() &&
env1.getExecutor() == env2.getExecutor() &&
env1.getExecutionTarget() == env2.getExecutionTarget();
}
private static void clearRestarterListener(@NotNull ProcessHandler processHandler) {
ProcessListener restarterListener = ON_TERMINATION_RESTARTER_KEY.get(processHandler, null);
if (restarterListener != null) {
@@ -177,9 +175,9 @@ public class AutoTestManager {
}
}
private static void restartAutoTest(@NotNull RunContentDescriptor descriptor,
int modificationStamp,
@NotNull DelayedDocumentWatcher documentWatcher) {
private void restartAutoTest(@NotNull RunContentDescriptor descriptor,
int modificationStamp,
@NotNull DelayedDocumentWatcher documentWatcher) {
ProcessHandler processHandler = descriptor.getProcessHandler();
if (processHandler != null && !processHandler.isProcessTerminated()) {
scheduleRestartOnTermination(descriptor, processHandler, modificationStamp, documentWatcher);
@@ -189,10 +187,10 @@ public class AutoTestManager {
}
}
private static void scheduleRestartOnTermination(@NotNull final RunContentDescriptor descriptor,
@NotNull final ProcessHandler processHandler,
final int modificationStamp,
@NotNull final DelayedDocumentWatcher documentWatcher) {
private void scheduleRestartOnTermination(@NotNull final RunContentDescriptor descriptor,
@NotNull final ProcessHandler processHandler,
final int modificationStamp,
@NotNull final DelayedDocumentWatcher documentWatcher) {
ProcessListener restarterListener = ON_TERMINATION_RESTARTER_KEY.get(processHandler);
if (restarterListener != null) {
clearRestarterListener(processHandler);
@@ -234,4 +232,51 @@ public class AutoTestManager {
}
PropertiesComponent.getInstance(myProject).setValue(AUTO_TEST_MANAGER_DELAY, myDelayMillis, AUTO_TEST_MANAGER_DELAY_DEFAULT);
}
@Nullable
@Override
public State getState() {
State state = new State();
for (RunProfile profile : myEnabledRunProfiles) {
RunConfiguration runConfiguration = ObjectUtils.tryCast(profile, RunConfiguration.class);
if (runConfiguration != null) {
RunConfigurationDescriptor descriptor = new RunConfigurationDescriptor();
descriptor.myType = runConfiguration.getType().getId();
descriptor.myName = runConfiguration.getName();
state.myEnabledRunConfigurations.add(descriptor);
}
}
return state;
}
@Override
public void loadState(State state) {
List<RunConfiguration> configurations = ContainerUtil.newArrayList();
RunManagerImpl runManager = RunManagerImpl.getInstanceImpl(myProject);
for (RunConfigurationDescriptor descriptor : state.myEnabledRunConfigurations) {
RunnerAndConfigurationSettings settings = runManager.findConfigurationByTypeAndName(descriptor.myType,
descriptor.myName);
RunConfiguration configuration = settings != null ? settings.getConfiguration() : null;
if (configuration != null) {
configurations.add(configuration);
}
}
myEnabledRunProfiles.clear();
myEnabledRunProfiles.addAll(configurations);
}
static class State {
@Tag("enabled-run-configurations")
@AbstractCollection(surroundWithTag = false)
List<RunConfigurationDescriptor> myEnabledRunConfigurations = ContainerUtil.newArrayList();
}
@Tag("run-configuration")
static class RunConfigurationDescriptor {
@Attribute("type")
String myType;
@Attribute("name")
String myName;
}
}
@@ -195,7 +195,7 @@ debugger.breakpoint.message.full.trace.description='Log message to console' brea
for the thread that hit the breakpoint.
debugger.batch.evaluation=false
debugger.compiling.evaluator=true
debugger.watches.in.variables=false
debugger.watches.in.variables=true
debugger.auto.fetch.icons=true
debugger.close.dialog.on.navigate=true
debugger.close.dialog.on.navigate.description=Close evaluate dialog on Jump to (type) source action
@@ -2407,7 +2407,7 @@ public class ContainerUtil extends ContainerUtilRt {
return true;
}
@Nullable
@Contract("null -> null; !null -> !null")
public static <T> List<T> trimToSize(@Nullable List<T> list) {
if (list == null) return null;
if (list.isEmpty()) return emptyList();
@@ -40,6 +40,7 @@ public class EditDistanceTest {
@Test
public void optimalAlignment() {
assertEquals(0, EditDistance.optimalAlignment("", "", true));
assertEquals(1, EditDistance.optimalAlignment("ab", "ba", true));
assertEquals(2, EditDistance.optimalAlignment("AB", "ba", true));
assertEquals(3, EditDistance.optimalAlignment("ca", "abc", true));
@@ -48,6 +49,7 @@ public class EditDistanceTest {
@Test
public void optimalAlignmentCaseInsensitive() {
assertEquals(0, EditDistance.optimalAlignment("", "", false));
assertEquals(1, EditDistance.optimalAlignment("ab", "ba", false));
assertEquals(1, EditDistance.optimalAlignment("AB", "ba", false));
assertEquals(3, EditDistance.optimalAlignment("ca", "abc", false));
@@ -1,49 +0,0 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.changes;
import com.intellij.openapi.diff.DiffContent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.actions.DiffRequestFromChange;
import com.intellij.openapi.vcs.changes.actions.ShowDiffAction;
import com.intellij.util.BeforeAfter;
import java.util.Collections;
import java.util.List;
/**
* @author irengrig
* Date: 6/15/11
* Time: 5:48 PM
*/
public class BinaryDiffRequestFromChange implements DiffRequestFromChange<DiffContent> {
private final Project myProject;
public BinaryDiffRequestFromChange(Project project) {
myProject = project;
}
@Override
public boolean canCreateRequest(Change change) {
return ShowDiffAction.isBinaryChangeAndCanShow(myProject, change);
}
@Override
public List<BeforeAfter<DiffContent>> createRequestForChange(Change change, int extraLines) throws VcsException {
return Collections.singletonList(ShowDiffAction.createBinaryDiffContents(myProject, change));
}
}
@@ -1,35 +0,0 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.changes.actions;
import com.intellij.openapi.diff.DiffContent;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.util.BeforeAfter;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* @author irengrig
* Date: 6/10/11
* Time: 6:39 PM
*/
public interface DiffRequestFromChange<T extends DiffContent> {
boolean canCreateRequest(final Change change);
@Nullable
List<BeforeAfter<T>> createRequestForChange(final Change change, int extraLines) throws VcsException;
}
@@ -1,338 +0,0 @@
/*
* 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.vcs.changes.actions;
import com.intellij.icons.AllIcons;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.diff.*;
import com.intellij.openapi.diff.impl.external.BinaryDiffTool;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.VcsDataKeys;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.util.ArrayUtil;
import com.intellij.util.BeforeAfter;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.*;
/**
* @author max
*/
public class ShowDiffAction extends AnAction implements DumbAware {
private static final Logger LOG = Logger.getInstance(ShowDiffAction.class);
private static final String ourText = ActionsBundle.actionText("ChangesView.Diff");
public ShowDiffAction() {
super(ourText,
ActionsBundle.actionDescription("ChangesView.Diff"),
AllIcons.Actions.Diff);
}
public void update(AnActionEvent e) {
Change[] changes = e.getData(VcsDataKeys.CHANGES);
Project project = e.getData(CommonDataKeys.PROJECT);
e.getPresentation().setEnabled(project != null && canShowDiff(changes));
}
protected static boolean canShowDiff(Change[] changes) {
if (changes == null || changes.length == 0) return false;
for (Change change : changes) {
if (!ChangesUtil.getFilePath(change).isDirectory() || change.hasOtherLayers()) return true;
}
return false;
}
public void actionPerformed(final AnActionEvent e) {
final Project project = e.getData(CommonDataKeys.PROJECT);
if (project == null) return;
if (ChangeListManager.getInstance(project).isFreezedWithNotification(null)) return;
final Change[] changes = e.getData(VcsDataKeys.CHANGES);
if (changes == null) return;
final boolean needsConvertion = checkIfThereAreFakeRevisions(project, changes);
final List<Change> changesInList = e.getData(VcsDataKeys.CHANGES_IN_LIST_KEY);
// this trick is essential since we are under some conditions to refresh changes;
// but we can only rely on callback after refresh
final Runnable performer = new Runnable() {
public void run() {
Change[] convertedChanges;
if (needsConvertion) {
convertedChanges = loadFakeRevisions(project, changes);
} else {
convertedChanges = changes;
}
if (convertedChanges == null || convertedChanges.length == 0) {
return;
}
List<Change> changesInListCopy = changesInList;
int index = 0;
if (convertedChanges.length == 1) {
final Change selectedChange = convertedChanges[0];
ChangeList changeList = ((ChangeListManagerImpl) ChangeListManager.getInstance(project)).getIdentityChangeList(selectedChange);
if (changeList != null) {
if (changesInListCopy == null) {
changesInListCopy = new ArrayList<Change>(changeList.getChanges());
Collections.sort(changesInListCopy, new Comparator<Change>() {
public int compare(final Change o1, final Change o2) {
return ChangesUtil.getFilePath(o1).getName().compareToIgnoreCase(ChangesUtil.getFilePath(o2).getName());
}
});
}
convertedChanges = changesInListCopy.toArray(new Change[changesInListCopy.size()]);
index = Math.max(0, ContainerUtil.indexOfIdentity(changesInListCopy, selectedChange));
}
}
showDiffForChange(convertedChanges, index, project);
}
};
if (needsConvertion) {
ChangeListManager.getInstance(project).invokeAfterUpdate(performer, InvokeAfterUpdateMode.BACKGROUND_CANCELLABLE, ourText, ModalityState.current());
} else {
performer.run();
}
}
public static void showDiffForChange(final Change[] changes, final int index, final Project project) {
showDiffForChange(changes, index, project, new ShowDiffUIContext(true));
}
private static boolean checkIfThereAreFakeRevisions(final Project project, final Change[] changes) {
boolean needsConversion = false;
for(Change change: changes) {
final ContentRevision beforeRevision = change.getBeforeRevision();
final ContentRevision afterRevision = change.getAfterRevision();
if (beforeRevision instanceof FakeRevision) {
VcsDirtyScopeManager.getInstance(project).fileDirty(beforeRevision.getFile());
needsConversion = true;
}
if (afterRevision instanceof FakeRevision) {
VcsDirtyScopeManager.getInstance(project).fileDirty(afterRevision.getFile());
needsConversion = true;
}
}
return needsConversion;
}
@Nullable
private static Change[] loadFakeRevisions(final Project project, final Change[] changes) {
List<Change> matchingChanges = new ArrayList<Change>();
for(Change change: changes) {
matchingChanges.addAll(ChangeListManager.getInstance(project).getChangesIn(ChangesUtil.getFilePath(change)));
}
return matchingChanges.toArray(new Change[matchingChanges.size()]);
}
public static void showDiffForChange(final Iterable<Change> changes, final Condition<Change> selectionChecker,
final Project project, @NotNull ShowDiffUIContext context) {
int newIndex = -1;
ChangeForDiffConvertor convertor = new ChangeForDiffConvertor(project, true);
final List<DiffRequestPresentable> changeList = ContainerUtil.newArrayList();
for (Change change : changes) {
if (! directoryOrBinary(change)) { //todo
DiffRequestPresentable presentable = convertor.convert(change);
if (presentable != null) {
if ((newIndex == -1) && selectionChecker.value(change)) {
newIndex = changeList.size();
}
changeList.add(presentable);
}
}
}
if (changeList.isEmpty()) {
return;
}
if (newIndex < 0) {
newIndex = 0;
}
showDiffImpl(project, changeList, newIndex, context);
}
public static void showDiffForChange(final Change[] changes, int index, final Project project, @NotNull ShowDiffUIContext context) {
final Change selected = index >= 0 ? changes[index] : null;
/*if (isBinaryDiff(project, changes, index)) {
showBinaryDiff(project, changes[index]);
return;
}*/
showDiffForChange(Arrays.asList(changes), new Condition<Change>() {
@Override
public boolean value(final Change change) {
return selected != null && selected.equals(change);
}
}, project, context);
}
private static FileContent createBinaryFileContent(final Project project, final ContentRevision contentRevision, final String fileName)
throws VcsException, IOException {
final FileContent fileContent;
if (contentRevision == null) {
fileContent = FileContent.createFromTempFile(project,
fileName,
fileName,
ArrayUtil.EMPTY_BYTE_ARRAY);
} else {
byte[] content = ((BinaryContentRevision)contentRevision).getBinaryContent();
fileContent = FileContent.createFromTempFile(project,
contentRevision.getFile().getName(),
contentRevision.getFile().getName(),
content == null ? ArrayUtil.EMPTY_BYTE_ARRAY : content);
}
return fileContent;
}
private static SimpleDiffRequest createBinaryDiffRequest(final Project project, final Change change) throws VcsException {
final FilePath filePath = ChangesUtil.getFilePath(change);
final SimpleDiffRequest request = new SimpleDiffRequest(project, filePath.getPath());
try {
request.setContents(createBinaryFileContent(project, change.getBeforeRevision(), filePath.getName()),
createBinaryFileContent(project, change.getAfterRevision(), filePath.getName()));
return request;
}
catch (IOException e) {
throw new VcsException(e);
}
}
public static BeforeAfter<DiffContent> createBinaryDiffContents(final Project project, final Change change) throws VcsException {
final FilePath filePath = ChangesUtil.getFilePath(change);
try {
return new BeforeAfter<DiffContent>(createBinaryFileContent(project, change.getBeforeRevision(), filePath.getName()),
createBinaryFileContent(project, change.getAfterRevision(), filePath.getName()));
}
catch (IOException e) {
throw new VcsException(e);
}
}
private static void showBinaryDiff(Project project, Change change) {
try {
final SimpleDiffRequest request = createBinaryDiffRequest(project, change);
if (DiffManager.getInstance().getDiffTool().canShow(request)) {
DiffManager.getInstance().getDiffTool().show(request);
}
}
catch (VcsException e) {
Messages.showWarningDialog(e.getMessage(), "Show Diff");
LOG.info(e);
}
}
private static boolean isBinaryDiff(Project project, Change[] changes, int index) {
if (index >= 0 && index < changes.length) {
final Change change = changes[index];
return isBinaryChangeAndCanShow(project, change);
}
return false;
}
public static boolean isBinaryChange(Change change) {
if (change.hasOtherLayers()) return false; // +-
final ContentRevision bRev = change.getBeforeRevision();
final ContentRevision aRev = change.getAfterRevision();
return (aRev == null || aRev instanceof BinaryContentRevision)
&& (bRev == null || bRev instanceof BinaryContentRevision);
}
public static boolean isBinaryChangeAndCanShow(Project project, Change change) {
// todo bug here would appear when there would be another diff providers for bimary revisions
return isBinaryChange(change) && (change.getAfterRevision() == null || BinaryDiffTool.canShow(project, change.getVirtualFile()));
}
public static void showDiffImpl(final Project project, @NotNull List<DiffRequestPresentable> changeList, int index,
@NotNull final ShowDiffUIContext context) {
final ChangeDiffRequest request = new ChangeDiffRequest(project, changeList, context.getActionsFactory(), context.isShowFrame());
final DiffTool tool = DiffManager.getInstance().getDiffTool();
final DiffRequest simpleRequest;
try {
request.quickCheckHaveStuff();
simpleRequest = request.init(index);
}
catch (VcsException e) {
Messages.showWarningDialog(e.getMessage(), "Show Diff");
LOG.info(e);
return;
}
if (simpleRequest != null) {
final DiffNavigationContext navigationContext = context.getDiffNavigationContext();
if (navigationContext != null) {
simpleRequest.passForDataContext(DiffTool.SCROLL_TO_LINE, navigationContext);
}
tool.show(simpleRequest);
}
}
private static boolean directoryOrBinary(final Change change) {
// todo instead for repository tab, filter directories (? ask remotely ? non leaf nodes)
/*if ((change.getBeforeRevision() instanceof BinaryContentRevision) || (change.getAfterRevision() instanceof BinaryContentRevision)) {
changesList.remove(i);
continue;
}*/
final FilePath path = ChangesUtil.getFilePath(change);
if (path.isDirectory()) {
return ! change.hasOtherLayers();
}
/*final FileType type = path.getFileType();
if ((! FileTypes.UNKNOWN.equals(type)) && (type.isBinary())) {
return true;
}*/
return false;
}
private static boolean checkNotifyBinaryDiff(final Change selectedChange) {
final ContentRevision beforeRevision = selectedChange.getBeforeRevision();
final ContentRevision afterRevision = selectedChange.getAfterRevision();
if (beforeRevision instanceof BinaryContentRevision &&
afterRevision instanceof BinaryContentRevision) {
try {
byte[] beforeContent = ((BinaryContentRevision)beforeRevision).getBinaryContent();
byte[] afterContent = ((BinaryContentRevision)afterRevision).getBinaryContent();
if (Arrays.equals(beforeContent, afterContent)) {
Messages.showInfoMessage(VcsBundle.message("message.text.binary.versions.are.identical"), VcsBundle.message("message.title.diff"));
} else {
Messages.showInfoMessage(VcsBundle.message("message.text.binary.versions.are.different"), VcsBundle.message("message.title.diff"));
}
}
catch (VcsException e) {
Messages.showInfoMessage(e.getMessage(), VcsBundle.message("message.title.diff"));
}
return true;
}
return false;
}
}
@@ -1,58 +0,0 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.changes.actions;
import com.intellij.openapi.diff.DiffNavigationContext;
import org.jetbrains.annotations.NotNull;
public class ShowDiffUIContext {
private DiffExtendUIFactory myActionsFactory;
private boolean myShowFrame;
private DiffNavigationContext myDiffNavigationContext;
public ShowDiffUIContext() {
myActionsFactory = DiffExtendUIFactory.NONE;
}
public ShowDiffUIContext(boolean showFrame) {
myShowFrame = showFrame;
myActionsFactory = DiffExtendUIFactory.NONE;
}
public DiffExtendUIFactory getActionsFactory() {
return myActionsFactory;
}
public void setActionsFactory(@NotNull DiffExtendUIFactory actionsFactory) {
this.myActionsFactory = actionsFactory;
}
public DiffNavigationContext getDiffNavigationContext() {
return myDiffNavigationContext;
}
public void setDiffNavigationContext(DiffNavigationContext diffNavigationContext) {
myDiffNavigationContext = diffNavigationContext;
}
public boolean isShowFrame() {
return myShowFrame;
}
public void setShowFrame(boolean showFrame) {
this.myShowFrame = showFrame;
}
}
@@ -15,7 +15,6 @@
*/
package com.intellij.openapi.vcs.changes.actions.diff;
import com.intellij.diff.DiffDialogHints;
import com.intellij.diff.DiffManager;
import com.intellij.diff.chains.DiffRequestChain;
import com.intellij.diff.util.DiffUserDataKeys;
@@ -33,7 +32,6 @@ import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vcs.VcsDataKeys;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.changes.actions.ShowDiffUIContext;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -219,16 +217,4 @@ public class ShowDiffAction extends AnAction implements DumbAware {
DiffManager.getInstance().showDiff(project, chain, context.getDialogHints());
}
//
// Compatibility
//
@NotNull
public static ShowDiffContext convertContext(@NotNull ShowDiffUIContext uiContext) {
if (uiContext.getActionsFactory() != null) LOG.warn("DiffExtendUIFactory ignored");
if (uiContext.getDiffNavigationContext() != null) LOG.warn("DiffNavigationContext ignored");
return new ShowDiffContext(uiContext.isShowFrame() ? DiffDialogHints.FRAME : DiffDialogHints.MODAL);
}
}

Some files were not shown because too many files have changed in this diff Show More