Merge branch 'master' into upsource-master

Conflicts:
	build/scripts/libLicenses.gant
	images/src/org/intellij/images/index/ImageInfoIndex.java
	java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java
	java/execution/impl/src/com/intellij/execution/actions/AbstractRerunFailedTestsAction.java
	jps/jps-builders/src/org/jetbrains/jps/cmdline/BuildSession.java
	jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java
	jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java
	jps/jps-builders/src/org/jetbrains/jps/javac/JavacMain.java
	jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager.java
	jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager17.java
	jps/model/src/org/jetbrains/jps/idea/IdeaProjectLoader.groovy
	platform/lang-api/src/com/intellij/execution/runners/ExecutionEnvironment.java
	platform/lang-impl/src/com/intellij/codeInsight/editorActions/CopyPasteIndentProcessor.java
	platform/platform-impl/src/com/intellij/featureStatistics/actions/ShowFeatureUsageStatisticsDialog.java
	platform/platform-resources-en/src/messages/ActionsBundle.properties
	platform/util/src/com/intellij/icons/AllIcons.java
	plugins/IdeaTestAssistant/src/com/intellij/testAssistant/TestDataHighlightingPass.java
	plugins/java-i18n/src/com/intellij/spellchecker/LiteralExpressionTokenizer.java
	plugins/junit/src/com/intellij/execution/junit/JUnitConfigurationType.java
	plugins/spellchecker/src/com/intellij/spellchecker/tokenizer/EscapeSequenceTokenizer.java
This commit is contained in:
Evgeny Pasynkov
2012-07-04 11:45:53 +02:00
68 changed files with 16778 additions and 15221 deletions
+7 -5
View File
@@ -90,11 +90,6 @@
<XML>
<option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
</XML>
<ADDITIONAL_INDENT_OPTIONS fileType="html">
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="4" />
<option name="TAB_SIZE" value="8" />
</ADDITIONAL_INDENT_OPTIONS>
<ADDITIONAL_INDENT_OPTIONS fileType="rb">
<option name="INDENT_SIZE" value="2" />
</ADDITIONAL_INDENT_OPTIONS>
@@ -185,6 +180,13 @@
<option name="INDENT_SIZE" value="2" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="HTML">
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="4" />
<option name="TAB_SIZE" value="8" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JAVA">
<option name="LINE_COMMENT_AT_FIRST_COLUMN" value="false" />
<option name="BLOCK_COMMENT_AT_FIRST_COLUMN" value="false" />
+4 -1
View File
@@ -157,7 +157,10 @@ def layoutFull(String home, String targetDirectory, String patchedDescriptorDir
module("jps-model")
}
fileset(dir: "$home/jps/lib", includes: "optimizedFileManager.jar")
fileset(dir: "$home/jps/lib") {
include(name: "optimizedFileManager.jar")
include(name: "ecj-*.jar")
}
fileset(dir: "$home/lib", includesfile: "${home}/lib/required_for_dist.txt")
+246 -245
View File
@@ -1,245 +1,246 @@
/*
* 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.
*/
import org.jetbrains.jps.ClasspathKind
import org.jetbrains.jps.Library
import org.jetbrains.jps.Module
class LibraryLicense {
String name, url, version
List<String> libraryNames
String license, licenseUrl
String attachedTo
}
List<LibraryLicense> licensesList = []
List<String> jetbrainsLibraries = []
Map<String, String> predefinedLicenseUrls = ["Apache 2.0": "http://www.apache.org/licenses/LICENSE-2.0"]
binding.setVariable("libraryLicense", {Map args ->
if (args.libraryNames == null) {
args.libraryNames = [args.libraryName?:args.name]
args.remove("libraryName")
}
if (args.licenseUrl == null) {
args.licenseUrl = predefinedLicenseUrls[args.license]
}
licensesList << new LibraryLicense(args)
})
binding.setVariable("jetbrainsLibrary", {String name ->
jetbrainsLibraries << name
})
def String getLibraryName(Library lib) {
def name = lib.name
if (name.startsWith("moduleLibrary#")) {
if (lib.classpath.size() != 1) {
project.warning("Non-single entry module library $name: $lib.classpath");
}
String filePath = lib.classpath[0]
return filePath.substring(filePath.lastIndexOf('/')+1)
}
return name
}
binding.setVariable("checkLibLicenses", {
def libraries = new HashSet<Library>()
def lib2Module = new HashMap<Library, Module>();
project.modules.values().each {Module module ->
module.getClasspath(ClasspathKind.PRODUCTION_RUNTIME).each {
if (it instanceof Library) {
lib2Module[it] = module
libraries << it
}
}
}
def libWithLicenses = licensesList.collectAll {it.libraryNames}.flatten() as Set
libWithLicenses.addAll(jetbrainsLibraries)
List<String> withoutLicenses = []
libraries.each {Library lib ->
def name = getLibraryName(lib)
if (!libWithLicenses.contains(name)) {
withoutLicenses << "$name (used in module ${lib2Module[lib].name})".toString()
}
}
if (!withoutLicenses.isEmpty()) {
def errorMessage = []
errorMessage << "Licenses aren't specified for ${withoutLicenses.size()} libraries:"
withoutLicenses.sort(String.CASE_INSENSITIVE_ORDER)
withoutLicenses.each { errorMessage << it}
errorMessage << "If a library is packaged into IDEA installation information about its license must be added to libLicenses.gant file"
errorMessage << "If a library is used in tests only change its scope to 'Test'"
errorMessage << "If a library is used for compilation only change its scope to 'Provided'"
project.error(errorMessage.join("\n"))
}
});
binding.setVariable("generateLicensesTable", {String filePath, Set<String> usedModulesNames ->
project.info("Generating licenses table")
project.info("Used modules: $usedModulesNames")
Set<Module> usedModules = project.modules.values().findAll {usedModulesNames.contains(it.name)}
Map<String, String> usedLibraries = [:]
usedModules.each {Module module ->
module.getClasspath(ClasspathKind.PRODUCTION_RUNTIME).each {item ->
if (item instanceof Library) {
usedLibraries[getLibraryName(item)] = module.name
}
}
}
Map<LibraryLicense, String> licenses = [:]
licensesList.each {LibraryLicense lib ->
if (usedModulesNames.contains(lib.attachedTo)) {
licenses[lib] = lib.attachedTo
}
else {
lib.libraryNames.each {
String module = usedLibraries[it]
if (module != null) {
licenses[lib] = module
}
}
}
}
project.info("Used libraries:")
List<String> lines = []
licenses.entrySet().each {
LibraryLicense lib = it.key
String moduleName = it.value
def name = lib.url != null ? "[$lib.name|$lib.url]" : lib.name
def license = lib.licenseUrl != null ? "[$lib.license|$lib.licenseUrl]" : lib.license
project.info(" $lib.name (in module $moduleName)")
lines << "|$name| ${lib.version?:""}|$license|".toString()
}
//project.info("Unused libraries:")
//licensesList.findAll {!licenses.containsKey(it)}.each {LibraryLicense lib ->
// project.info(" $lib.name")
//}
lines.sort(String.CASE_INSENSITIVE_ORDER)
File file = new File(filePath)
file.parentFile.mkdirs()
FileWriter out = new FileWriter(file)
try {
out.println("|| Software || Version || License ||")
lines.each {
out.println(it)
}
}
finally {
out.close()
}
notifyArtifactBuilt(filePath)
})
libraryLicense(name: "Alloy L&F", libraryName: "alloy.jar", version: "1.4.4", license: "link (company license)", url: "http://www.incors.com/lookandfeel/", licenseUrl: "http://lookandfeel.incors.com/display_licence.php?back=purchase.php&selMenu=Purchase")
libraryLicense(name: "Ant", version: "1.7", license: "Apache 2.0", url: "http://ant.apache.org/", licenseUrl: "http://ant.apache.org/license.html")
libraryLicense(name: "ASM Bytecode Manipulation Framework", libraryName: "asm", version: "3.3", license: "BSD", url: "http://asm.objectweb.org/", licenseUrl: "http://asm.objectweb.org/license.html")
libraryLicense(name: "ASM Bytecode Manipulation Framework", libraryName: "asm4", version: "4.0", license: "BSD", url: "http://asm.objectweb.org/", licenseUrl: "http://asm.objectweb.org/license.html")
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: "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: "Android SDK Tools", libraryName: "android-sdk-tools", license: "Apache 2.0", url: "http://source.android.com/")
libraryLicense(name: "Android SDK Tools JPS", libraryName: "android-sdk-tools-jps", license: "Apache 2.0", url: "http://source.android.com/")
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.3", license: "Apache 2.0", url: "http://commons.apache.org/codec/", licenseUrl: "http://commons.apache.org/license.html")
libraryLicense(name: "Apache Commons Collections", libraryName: "commons-collections", version: "3.1", license: "Apache 2.0", url: "http://commons.apache.org/collections/", 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://commons.apache.org/license.html")
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 Net", libraryName: "commons-net", version: "2.0", license: "Apache 2.0", url: "http://commons.apache.org/net/")
libraryLicense(name: "Apache Commons Lang", libraryName: "commons-lang", version: "2.4", license: "Apache 2.0", url: "http://commons.apache.org/lang/", licenseUrl: "http://commons.apache.org/lang/license.html")
libraryLicense(name: "Apache Commons Logging", libraryName: "commons-logging", version: "1.1.1", license: "Apache 2.0", url: "http://commons.apache.org/logging/")
libraryLicense(name: "Apache Lucene", libraryName: "lucene-core-2.4.1.jar", version: "2.4.1", license: "Apache 2.0", url: "http://lucene.apache.org/java")
libraryLicense(name: "Apache Sanselan", libraryName: "Sanselan", version: "0.98", license: "Apache 2.0", url: "http://commons.apache.org/sanselan/")
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: "DTDParser", version: "1.13", license: "LGPL", url: "http://sourceforge.net/projects/dtdparser/", licenseUrl: "http://www.opensource.org/licenses/lgpl-2.1")
libraryLicense(name: "Ganymed", version: "bundled with SVNKit", libraryName: "svnkit.jar", license: "BSD", url: "http://www.ganymed.ethz.ch/ssh2/", licenseUrl: "http://www.ganymed.ethz.ch/ssh2/LICENSE.txt")
libraryLicense(name: "sqljet", version: "bundled with SVNKit", libraryName: "sqljet.jar", license: "GPLv2", url: "http://sqljet.com", licenseUrl: "http://www.opensource.org/licenses/lgpl-2.1")
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: "javahl", version: "1.7.2", libraryName: "javahl.jar", license: "Apache", url: "http://subversion.apache.org", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Apache Commons HTTPClient", libraryName: "httpclient-4.1.1.jar", version:"4.1.1", license: "Apache 2.0",
url: "http://hc.apache.org/httpcomponents-client-ga/index.html", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Apache Commons HTTPCore", libraryName: "httpcore-4.1.jar", version: "4.1", license: "Apache 2.0",
url: "http://hc.apache.org/httpcomponents-core-ga/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Antlr", libraryName: "antlr.jar", version: "3.1.3", license: "BSD", url: "http://www.antlr.org",
licenseUrl: "http://www.antlr.org/license.html")
libraryLicense(name: "Guava", version: "12.0", license: "Apache 2.0", url: "http://code.google.com/p/guava-libraries/", licenseUrl: "http://ant.apache.org/license.html")
libraryLicense(name: "Groovy", version: "1.7.3", license: "Apache 2.0", url: "http://groovy.codehaus.org/")
libraryLicense(name: "Gson", libraryName: "gson", license: "Apache 2.0", url: "http://code.google.com/p/google-gson/")
libraryLicense(name: "ini4j", libraryName: "ini4j-0.5.2-patched", version: "0.5.2 (with a patch by JetBrains)", license: "Apache 2.0", url: "http://ini4j.sourceforge.net/", attachedTo: "git4idea")
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: "JavaCVS", attachedTo: "javacvs-src", version: "no version number available (with patches by JetBrains)", license: "Sun Public License", url: "http://javacvs.netbeans.org/library/", licenseUrl: "http://www.netbeans.org/about/legal/spl.html")
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")
libraryLicense(name: "Jaxen", version: "", license: "modified Apache", url: "http://www.jaxen.org/", licenseUrl: "http://www.jaxen.org/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: "JCIP Annotations", libraryName: "jcip", license: "Creative Commons Attribution License", url: "http://www.jcip.net", licenseUrl: "http://creativecommons.org/licenses/by/2.5")
libraryLicense(name: "JDOM", version: "1.1 (with patches by JetBrains)", license: "modified Apache", url: "http://www.jdom.org/", licenseUrl: "http://www.jdom.org/docs/faq.html#a0030")
libraryLicense(name: "jgit-1.1.0", version: "1.1.0.201109151100", license: "EDL/BSD", url: "http://www.eclipse.org/jgit/", licenseUrl: "http://www.eclipse.org/org/documents/edl-v10.php", attachedTo: "git4idea")
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/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/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/looks/", licenseUrl: "http://www.jgoodies.com/downloads/libraries.html")
libraryLicense(name: "JNA", libraryName: "jna", version: "3.4.0", license: "LGPL 2.1", url: "https://jna.dev.java.net/", licenseUrl: "http://www.opensource.org/licenses/lgpl-2.1.php")
libraryLicense(name: "JSch", libraryName: "JSch", version: "0.1.44", license: "BSD", url: "http://www.jcraft.com/jsch/", licenseUrl: "http://www.jcraft.com/jsch/LICENSE.txt")
libraryLicense(name: "JUnit", libraryName: "JUnit3", version: "3.8.1", license: "CPL 1.0", url: "http://junit.org/")
libraryLicense(name: "JUnit", libraryName: "JUnit4", version: "4.8", license: "CPL 1.0", url: "http://junit.org/")
libraryLicense(name: "Log4j", libraryName: "Log4J", version: "1.2", license: "Apache 2.0", url: "http://logging.apache.org/log4j/1.2/index.html", licenseUrl: "http://logging.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"], version: "3.0.3", 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: "http://markdownj.org/", licenseUrl: "http://www.opensource.org/licenses/bsd-license.php")
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")
libraryLicense(name: "NanoXML", version: "2.2.3", license: "zlib/libpng", url: "http://nanoxml.cyberelf.be/", licenseUrl: "http://devkix.com/nanoxml.php")
libraryLicense(name: "nekohtml", libraryName: "nekohtml", version: "1.9.14", license: "Apache 2.0", url: "http://nekohtml.sourceforge.net/", licenseUrl: "http://apache.org/licenses/LICENSE-2.0.txt")
libraryLicense(name: "Eclipse JDT Core", libraryName: "Eclipse", version: "3.3", license: "CPL 1.0", url: "http://www.eclipse.org/jdt/core/index.php")
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: "PicoContainer", libraryName: "picocontainer", version: "1.2", license: "BSD", url: "http://www.picocontainer.org/", licenseUrl: "http://docs.codehaus.org/display/PICO/License")
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: "Quaqua L&F", attachedTo: "platform-impl", version: "6.2", license: "BSD", url: "http://www.randelshofer.ch/quaqua/", licenseUrl: "http://www.randelshofer.ch/quaqua/license.html")
libraryLicense(name: "Relax NG Object Model", libraryName: "rngom-20051226-patched.jar", license: "MIT", url: "http://java.net/projects/rngom/", licenseUrl: "http://www.opensource.org/licenses/mit-license.php")
libraryLicense(name: "RMI Stubs", attachedTo: "xslt-debugger-engine", license: "Apache 2.0", url: "http://confluence.jetbrains.net/display/CONTEST/XSLT-Debugger", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Saxon-9HE", version: "9", license: "Mozilla Public License", url: "http://saxon.sourceforge.net/", licenseUrl: "http://www.mozilla.org/MPL/")
libraryLicense(name: "Saxon-6.5.5", version: "6.5.5", license: "Mozilla Public License", url: "http://saxon.sourceforge.net/", licenseUrl: "http://www.mozilla.org/MPL/")
libraryLicense(name: "Sonatype Nexus: Indexer", libraryName: "nexus-indexer-1.2.3.jar", version: "1.2.3", license: "Eclipse Public License v1.0", url: "http://nexus.sonatype.org/", licenseUrl: "http://www.eclipse.org/org/documents/epl-v10.html")
libraryLicense(name: "Sonatype Nexus: Indexer", libraryName: "nexus-indexer-3.0.4.jar", version: "3.0.4", license: "Eclipse Public License v1.0", url: "http://nexus.sonatype.org/", licenseUrl: "http://www.eclipse.org/org/documents/epl-v10.html")
libraryLicense(name: "SVNKit", libraryName: "svnkit.jar", version: "SVN version, 1.1 branch as of 1 Oct 2007", license: "link (commercial license)", url: "http://www.svnkit.com/", licenseUrl: "http://svnkit.com/license.html")
libraryLicense(name: "Sequence", libraryName: "sequence-library.jar", version: "bundled with SVNKit", license: "", url:"http://www.syntevo.com", licenseUrl: "http://svn.jetbrains.org/idea/Trunk/bundled/svn4idea/lib/SEQUENCE-LICENSE")
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: "5.7 snapshot", license: "Apache 2.0", url: "http://testng.org/doc/", licenseUrl: "http://code.google.com/p/testng/")
libraryLicense(name: "Trilead SSH", libraryName: "trilead-ssh2", version: "build 213", license: "BSD style (see LICENSE.txt in trilead.jar)", url: "http://www.trilead.com/SSH_Library/")
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: "winp", version: "1.16 (patched)", license: "MIT", url: "http://winp.dev.java.net/", licenseUrl: "https://winp.dev.java.net/license.html")
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.9.1", license: "Apache 2.0", url: "http://xerces.apache.org/xerces2-j/", licenseUrl: "http://xerces.apache.org/xerces2-j/")
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: "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: "XStream", version: "1.2.1", license: "BSD", url: "http://xstream.codehaus.org/", licenseUrl: "http://xstream.codehaus.org/license.html")
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")
libraryLicense(name: "protobuf", version: "2.3.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: "Netty", libraryName: "Netty", version: "3.3.1", license: "Apache 2.0", url: "http://netty.io", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Kryo", libraryName: "Kryo", version: "1.04", license: "New BSD License", url: "http://code.google.com/p/kryo/", licenseUrl: "http://www.opensource.org/licenses/bsd-license.php")
libraryLicense(name: "Snappy-Java", libraryName: "Snappy-Java", version: "1.0.4.1", license: "Apache 2.0", url: "http://code.google.com/p/snappy-java/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
jetbrainsLibrary("JPS")
jetbrainsLibrary("Maven Embedder")
jetbrainsLibrary("tcServiceMessages")
jetbrainsLibrary("optimizedFileManager.jar")
/*
* 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.
*/
import org.jetbrains.jps.ClasspathKind
import org.jetbrains.jps.Library
import org.jetbrains.jps.Module
class LibraryLicense {
String name, url, version
List<String> libraryNames
String license, licenseUrl
String attachedTo
}
List<LibraryLicense> licensesList = []
List<String> jetbrainsLibraries = []
Map<String, String> predefinedLicenseUrls = ["Apache 2.0": "http://www.apache.org/licenses/LICENSE-2.0"]
binding.setVariable("libraryLicense", {Map args ->
if (args.libraryNames == null) {
args.libraryNames = [args.libraryName?:args.name]
args.remove("libraryName")
}
if (args.licenseUrl == null) {
args.licenseUrl = predefinedLicenseUrls[args.license]
}
licensesList << new LibraryLicense(args)
})
binding.setVariable("jetbrainsLibrary", {String name ->
jetbrainsLibraries << name
})
def String getLibraryName(Library lib) {
def name = lib.name
if (name.startsWith("moduleLibrary#")) {
if (lib.classpath.size() != 1) {
project.warning("Non-single entry module library $name: $lib.classpath");
}
String filePath = lib.classpath[0]
return filePath.substring(filePath.lastIndexOf('/')+1)
}
return name
}
binding.setVariable("checkLibLicenses", {
def libraries = new HashSet<Library>()
def lib2Module = new HashMap<Library, Module>();
project.modules.values().each {Module module ->
module.getClasspath(ClasspathKind.PRODUCTION_RUNTIME).each {
if (it instanceof Library) {
lib2Module[it] = module
libraries << it
}
}
}
def libWithLicenses = licensesList.collectAll {it.libraryNames}.flatten() as Set
libWithLicenses.addAll(jetbrainsLibraries)
List<String> withoutLicenses = []
libraries.each {Library lib ->
def name = getLibraryName(lib)
if (!libWithLicenses.contains(name)) {
withoutLicenses << "$name (used in module ${lib2Module[lib].name})".toString()
}
}
if (!withoutLicenses.isEmpty()) {
def errorMessage = []
errorMessage << "Licenses aren't specified for ${withoutLicenses.size()} libraries:"
withoutLicenses.sort(String.CASE_INSENSITIVE_ORDER)
withoutLicenses.each { errorMessage << it}
errorMessage << "If a library is packaged into IDEA installation information about its license must be added to libLicenses.gant file"
errorMessage << "If a library is used in tests only change its scope to 'Test'"
errorMessage << "If a library is used for compilation only change its scope to 'Provided'"
project.error(errorMessage.join("\n"))
}
});
binding.setVariable("generateLicensesTable", {String filePath, Set<String> usedModulesNames ->
project.info("Generating licenses table")
project.info("Used modules: $usedModulesNames")
Set<Module> usedModules = project.modules.values().findAll {usedModulesNames.contains(it.name)}
Map<String, String> usedLibraries = [:]
usedModules.each {Module module ->
module.getClasspath(ClasspathKind.PRODUCTION_RUNTIME).each {item ->
if (item instanceof Library) {
usedLibraries[getLibraryName(item)] = module.name
}
}
}
Map<LibraryLicense, String> licenses = [:]
licensesList.each {LibraryLicense lib ->
if (usedModulesNames.contains(lib.attachedTo)) {
licenses[lib] = lib.attachedTo
}
else {
lib.libraryNames.each {
String module = usedLibraries[it]
if (module != null) {
licenses[lib] = module
}
}
}
}
project.info("Used libraries:")
List<String> lines = []
licenses.entrySet().each {
LibraryLicense lib = it.key
String moduleName = it.value
def name = lib.url != null ? "[$lib.name|$lib.url]" : lib.name
def license = lib.licenseUrl != null ? "[$lib.license|$lib.licenseUrl]" : lib.license
project.info(" $lib.name (in module $moduleName)")
lines << "|$name| ${lib.version?:""}|$license|".toString()
}
//project.info("Unused libraries:")
//licensesList.findAll {!licenses.containsKey(it)}.each {LibraryLicense lib ->
// project.info(" $lib.name")
//}
lines.sort(String.CASE_INSENSITIVE_ORDER)
File file = new File(filePath)
file.parentFile.mkdirs()
FileWriter out = new FileWriter(file)
try {
out.println("|| Software || Version || License ||")
lines.each {
out.println(it)
}
}
finally {
out.close()
}
notifyArtifactBuilt(filePath)
})
libraryLicense(name: "Alloy L&F", libraryName: "alloy.jar", version: "1.4.4", license: "link (company license)", url: "http://www.incors.com/lookandfeel/", licenseUrl: "http://lookandfeel.incors.com/display_licence.php?back=purchase.php&selMenu=Purchase")
libraryLicense(name: "Ant", version: "1.7", license: "Apache 2.0", url: "http://ant.apache.org/", licenseUrl: "http://ant.apache.org/license.html")
libraryLicense(name: "ASM Bytecode Manipulation Framework", libraryName: "asm", version: "3.3", license: "BSD", url: "http://asm.objectweb.org/", licenseUrl: "http://asm.objectweb.org/license.html")
libraryLicense(name: "ASM Bytecode Manipulation Framework", libraryName: "asm4", version: "4.0", license: "BSD", url: "http://asm.objectweb.org/", licenseUrl: "http://asm.objectweb.org/license.html")
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: "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: "Android SDK Tools", libraryName: "android-sdk-tools", license: "Apache 2.0", url: "http://source.android.com/")
libraryLicense(name: "Android SDK Tools JPS", libraryName: "android-sdk-tools-jps", license: "Apache 2.0", url: "http://source.android.com/")
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.3", license: "Apache 2.0", url: "http://commons.apache.org/codec/", licenseUrl: "http://commons.apache.org/license.html")
libraryLicense(name: "Apache Commons Collections", libraryName: "commons-collections", version: "3.1", license: "Apache 2.0", url: "http://commons.apache.org/collections/", 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://commons.apache.org/license.html")
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 Net", libraryName: "commons-net", version: "2.0", license: "Apache 2.0", url: "http://commons.apache.org/net/")
libraryLicense(name: "Apache Commons Lang", libraryName: "commons-lang", version: "2.4", license: "Apache 2.0", url: "http://commons.apache.org/lang/", licenseUrl: "http://commons.apache.org/lang/license.html")
libraryLicense(name: "Apache Commons Logging", libraryName: "commons-logging", version: "1.1.1", license: "Apache 2.0", url: "http://commons.apache.org/logging/")
libraryLicense(name: "Apache Lucene", libraryName: "lucene-core-2.4.1.jar", version: "2.4.1", license: "Apache 2.0", url: "http://lucene.apache.org/java")
libraryLicense(name: "Apache Sanselan", libraryName: "Sanselan", version: "0.98", license: "Apache 2.0", url: "http://commons.apache.org/sanselan/")
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: "DTDParser", version: "1.13", license: "LGPL", url: "http://sourceforge.net/projects/dtdparser/", licenseUrl: "http://www.opensource.org/licenses/lgpl-2.1")
libraryLicense(name: "Ganymed", version: "bundled with SVNKit", libraryName: "svnkit.jar", license: "BSD", url: "http://www.ganymed.ethz.ch/ssh2/", licenseUrl: "http://www.ganymed.ethz.ch/ssh2/LICENSE.txt")
libraryLicense(name: "sqljet", version: "bundled with SVNKit", libraryName: "sqljet.jar", license: "GPLv2", url: "http://sqljet.com", licenseUrl: "http://www.opensource.org/licenses/lgpl-2.1")
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: "javahl", version: "1.7.2", libraryName: "javahl.jar", license: "Apache", url: "http://subversion.apache.org", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Apache Commons HTTPClient", libraryName: "httpclient-4.1.1.jar", version:"4.1.1", license: "Apache 2.0",
url: "http://hc.apache.org/httpcomponents-client-ga/index.html", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Apache Commons HTTPCore", libraryName: "httpcore-4.1.jar", version: "4.1", license: "Apache 2.0",
url: "http://hc.apache.org/httpcomponents-core-ga/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Antlr", libraryName: "antlr.jar", version: "3.1.3", license: "BSD", url: "http://www.antlr.org",
licenseUrl: "http://www.antlr.org/license.html")
libraryLicense(name: "Guava", version: "12.0", license: "Apache 2.0", url: "http://code.google.com/p/guava-libraries/", licenseUrl: "http://ant.apache.org/license.html")
libraryLicense(name: "Groovy", version: "1.7.3", license: "Apache 2.0", url: "http://groovy.codehaus.org/")
libraryLicense(name: "Gson", libraryName: "gson", license: "Apache 2.0", url: "http://code.google.com/p/google-gson/")
libraryLicense(name: "ini4j", libraryName: "ini4j-0.5.2-patched", version: "0.5.2 (with a patch by JetBrains)", license: "Apache 2.0", url: "http://ini4j.sourceforge.net/", attachedTo: "git4idea")
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: "JavaCVS", attachedTo: "javacvs-src", version: "no version number available (with patches by JetBrains)", license: "Sun Public License", url: "http://javacvs.netbeans.org/library/", licenseUrl: "http://www.netbeans.org/about/legal/spl.html")
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")
libraryLicense(name: "Jaxen", version: "", license: "modified Apache", url: "http://www.jaxen.org/", licenseUrl: "http://www.jaxen.org/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: "JCIP Annotations", libraryName: "jcip", license: "Creative Commons Attribution License", url: "http://www.jcip.net", licenseUrl: "http://creativecommons.org/licenses/by/2.5")
libraryLicense(name: "JDOM", version: "1.1 (with patches by JetBrains)", license: "modified Apache", url: "http://www.jdom.org/", licenseUrl: "http://www.jdom.org/docs/faq.html#a0030")
libraryLicense(name: "jgit-1.1.0", version: "1.1.0.201109151100", license: "EDL/BSD", url: "http://www.eclipse.org/jgit/", licenseUrl: "http://www.eclipse.org/org/documents/edl-v10.php", attachedTo: "git4idea")
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/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/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/looks/", licenseUrl: "http://www.jgoodies.com/downloads/libraries.html")
libraryLicense(name: "JNA", libraryName: "jna", version: "3.4.0", license: "LGPL 2.1", url: "https://jna.dev.java.net/", licenseUrl: "http://www.opensource.org/licenses/lgpl-2.1.php")
libraryLicense(name: "JSch", libraryName: "JSch", version: "0.1.44", license: "BSD", url: "http://www.jcraft.com/jsch/", licenseUrl: "http://www.jcraft.com/jsch/LICENSE.txt")
libraryLicense(name: "JUnit", libraryName: "JUnit3", version: "3.8.1", license: "CPL 1.0", url: "http://junit.org/")
libraryLicense(name: "JUnit", libraryName: "JUnit4", version: "4.8", license: "CPL 1.0", url: "http://junit.org/")
libraryLicense(name: "Log4j", libraryName: "Log4J", version: "1.2", license: "Apache 2.0", url: "http://logging.apache.org/log4j/1.2/index.html", licenseUrl: "http://logging.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"], version: "3.0.3", 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: "http://markdownj.org/", licenseUrl: "http://www.opensource.org/licenses/bsd-license.php")
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")
libraryLicense(name: "NanoXML", version: "2.2.3", license: "zlib/libpng", url: "http://nanoxml.cyberelf.be/", licenseUrl: "http://devkix.com/nanoxml.php")
libraryLicense(name: "nekohtml", libraryName: "nekohtml", version: "1.9.14", license: "Apache 2.0", url: "http://nekohtml.sourceforge.net/", licenseUrl: "http://apache.org/licenses/LICENSE-2.0.txt")
libraryLicense(name: "Eclipse JDT Core", libraryName: "Eclipse", version: "3.3", license: "CPL 1.0", url: "http://www.eclipse.org/jdt/core/index.php")
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: "PicoContainer", libraryName: "picocontainer", version: "1.2", license: "BSD", url: "http://www.picocontainer.org/", licenseUrl: "http://docs.codehaus.org/display/PICO/License")
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: "Quaqua L&F", attachedTo: "platform-impl", version: "6.2", license: "BSD", url: "http://www.randelshofer.ch/quaqua/", licenseUrl: "http://www.randelshofer.ch/quaqua/license.html")
libraryLicense(name: "Relax NG Object Model", libraryName: "rngom-20051226-patched.jar", license: "MIT", url: "http://java.net/projects/rngom/", licenseUrl: "http://www.opensource.org/licenses/mit-license.php")
libraryLicense(name: "RMI Stubs", attachedTo: "xslt-debugger-engine", license: "Apache 2.0", url: "http://confluence.jetbrains.net/display/CONTEST/XSLT-Debugger", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Saxon-9HE", version: "9", license: "Mozilla Public License", url: "http://saxon.sourceforge.net/", licenseUrl: "http://www.mozilla.org/MPL/")
libraryLicense(name: "Saxon-6.5.5", version: "6.5.5", license: "Mozilla Public License", url: "http://saxon.sourceforge.net/", licenseUrl: "http://www.mozilla.org/MPL/")
libraryLicense(name: "Sonatype Nexus: Indexer", libraryName: "nexus-indexer-1.2.3.jar", version: "1.2.3", license: "Eclipse Public License v1.0", url: "http://nexus.sonatype.org/", licenseUrl: "http://www.eclipse.org/org/documents/epl-v10.html")
libraryLicense(name: "Sonatype Nexus: Indexer", libraryName: "nexus-indexer-3.0.4.jar", version: "3.0.4", license: "Eclipse Public License v1.0", url: "http://nexus.sonatype.org/", licenseUrl: "http://www.eclipse.org/org/documents/epl-v10.html")
libraryLicense(name: "SVNKit", libraryName: "svnkit.jar", version: "SVN version, 1.1 branch as of 1 Oct 2007", license: "link (commercial license)", url: "http://www.svnkit.com/", licenseUrl: "http://svnkit.com/license.html")
libraryLicense(name: "Sequence", libraryName: "sequence-library.jar", version: "bundled with SVNKit", license: "", url:"http://www.syntevo.com", licenseUrl: "http://svn.jetbrains.org/idea/Trunk/bundled/svn4idea/lib/SEQUENCE-LICENSE")
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: "5.7 snapshot", license: "Apache 2.0", url: "http://testng.org/doc/", licenseUrl: "http://code.google.com/p/testng/")
libraryLicense(name: "Trilead SSH", libraryName: "trilead-ssh2", version: "build 213", license: "BSD style (see LICENSE.txt in trilead.jar)", url: "http://www.trilead.com/SSH_Library/")
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: "winp", version: "1.16 (patched)", license: "MIT", url: "http://winp.dev.java.net/", licenseUrl: "https://winp.dev.java.net/license.html")
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.9.1", license: "Apache 2.0", url: "http://xerces.apache.org/xerces2-j/", licenseUrl: "http://xerces.apache.org/xerces2-j/")
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: "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: "XStream", version: "1.2.1", license: "BSD", url: "http://xstream.codehaus.org/", licenseUrl: "http://xstream.codehaus.org/license.html")
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")
libraryLicense(name: "protobuf", version: "2.3.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: "Netty", libraryName: "Netty", version: "3.3.1", license: "Apache 2.0", url: "http://netty.io", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Kryo", libraryName: "Kryo", version: "1.04", license: "New BSD License", url: "http://code.google.com/p/kryo/", licenseUrl: "http://www.opensource.org/licenses/bsd-license.php")
libraryLicense(name: "Snappy-Java", libraryName: "Snappy-Java", version: "1.0.4.1", license: "Apache 2.0", url: "http://code.google.com/p/snappy-java/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "ecj-4.2.jar", libraryName: "ecj-4.2.jar", version: "4.2", license: "CPL 1.0", url: "http://www.eclipse.org/jdt/core/index.php")
jetbrainsLibrary("JPS")
jetbrainsLibrary("Maven Embedder")
jetbrainsLibrary("tcServiceMessages")
jetbrainsLibrary("optimizedFileManager.jar")
@@ -1,149 +1,146 @@
/*
* 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 org.intellij.images.index;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.ex.temp.TempFileSystem;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.indexing.*;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.DataInputOutputUtil;
import org.intellij.images.fileTypes.ImageFileTypeManager;
import org.intellij.images.util.ImageInfoReader;
import org.jetbrains.annotations.NotNull;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* @author spleaner
*/
public class ImageInfoIndex extends SingleEntryFileBasedIndexExtension<ImageInfoIndex.ImageInfo> {
public static final ID<Integer, ImageInfo> INDEX_ID = ID.create("ImageFileInfoIndex");
private final FileBasedIndex.InputFilter myInputFilter = new FileBasedIndex.InputFilter() {
@Override
public boolean acceptInput(final VirtualFile file) {
return (file.getFileSystem() == LocalFileSystem.getInstance() || file.getFileSystem() instanceof TempFileSystem) &&
file.getFileType() == ImageFileTypeManager.getInstance().getImageFileType();
}
};
private final DataExternalizer<ImageInfo> myValueExternalizer = new DataExternalizer<ImageInfo>() {
@Override
public void save(final DataOutput out, final ImageInfo info) throws IOException {
DataInputOutputUtil.writeINT(out, info.width);
DataInputOutputUtil.writeINT(out, info.height);
DataInputOutputUtil.writeINT(out, info.bpp);
}
@Override
public ImageInfo read(final DataInput in) throws IOException {
return new ImageInfo(DataInputOutputUtil.readINT(in), DataInputOutputUtil.readINT(in), DataInputOutputUtil.readINT(in));
}
};
private final SingleEntryIndexer<ImageInfo> myDataIndexer = new SingleEntryIndexer<ImageInfo>(false) {
@Override
protected ImageInfo computeValue(@NotNull FileContent inputData) {
VirtualFile file = inputData.getFile();
final ImageInfoReader.Info info;
if (file.getFileSystem() == TempFileSystem.getInstance()) { // for tests load content directly as we are now not requiring content index
try {
info = ImageInfoReader.getInfo(file.contentsToByteArray());
} catch (IOException ex) { return null; }
}
else {
info = ImageInfoReader.getInfo(file.getPath());
}
return info != null? new ImageInfo(info.width, info.height, info.bpp) : null;
}
};
@Override
@NotNull
public ID<Integer, ImageInfo> getName() {
return INDEX_ID;
}
@Override
@NotNull
public SingleEntryIndexer<ImageInfo> getIndexer() {
return myDataIndexer;
}
public static void processValues(VirtualFile virtualFile, FileBasedIndex.ValueProcessor<ImageInfo> processor, Project project) {
FileBasedIndex.getInstance().processValues(INDEX_ID, Math.abs(FileBasedIndex.getFileId(virtualFile)), virtualFile, processor, GlobalSearchScope
.fileScope(project, virtualFile));
}
@Override
public DataExternalizer<ImageInfo> getValueExternalizer() {
return myValueExternalizer;
}
@Override
public FileBasedIndex.InputFilter getInputFilter() {
return myInputFilter;
}
@Override
public boolean dependsOnFileContent() {
return false;
}
@Override
public int getVersion() {
return 4;
}
public static class ImageInfo {
public int width;
public int height;
public int bpp;
public ImageInfo(int width, int height, int bpp) {
this.width = width;
this.height = height;
this.bpp = bpp;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ImageInfo imageInfo = (ImageInfo)o;
if (bpp != imageInfo.bpp) return false;
if (height != imageInfo.height) return false;
if (width != imageInfo.width) return false;
return true;
}
@Override
public int hashCode() {
int result = width;
result = 31 * result + height;
result = 31 * result + bpp;
return result;
}
}
}
/*
* 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 org.intellij.images.index;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.ex.temp.TempFileSystem;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.indexing.*;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.DataInputOutputUtil;
import org.intellij.images.fileTypes.ImageFileTypeManager;
import org.intellij.images.util.ImageInfoReader;
import org.jetbrains.annotations.NotNull;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* @author spleaner
*/
public class ImageInfoIndex extends SingleEntryFileBasedIndexExtension<ImageInfoIndex.ImageInfo> {
private static final int ourMaxImageSize;
static {
int maxImageSize = 200;
try {
maxImageSize = Integer.parseInt(System.getProperty("idea.max.image.filesize", Integer.toString(maxImageSize)), 10);
} catch (NumberFormatException ex) {}
ourMaxImageSize = maxImageSize;
}
public static final ID<Integer, ImageInfo> INDEX_ID = ID.create("ImageFileInfoIndex");
private final FileBasedIndex.InputFilter myInputFilter = new FileBasedIndex.InputFilter() {
@Override
public boolean acceptInput(final VirtualFile file) {
return (file.getFileSystem() == LocalFileSystem.getInstance() || file.getFileSystem() instanceof TempFileSystem) &&
file.getFileType() == ImageFileTypeManager.getInstance().getImageFileType() &&
(file.getLength() / 1024) < ourMaxImageSize
;
}
};
private final DataExternalizer<ImageInfo> myValueExternalizer = new DataExternalizer<ImageInfo>() {
@Override
public void save(final DataOutput out, final ImageInfo info) throws IOException {
DataInputOutputUtil.writeINT(out, info.width);
DataInputOutputUtil.writeINT(out, info.height);
DataInputOutputUtil.writeINT(out, info.bpp);
}
@Override
public ImageInfo read(final DataInput in) throws IOException {
return new ImageInfo(DataInputOutputUtil.readINT(in), DataInputOutputUtil.readINT(in), DataInputOutputUtil.readINT(in));
}
};
private final SingleEntryIndexer<ImageInfo> myDataIndexer = new SingleEntryIndexer<ImageInfo>(false) {
@Override
protected ImageInfo computeValue(@NotNull FileContent inputData) {
final ImageInfoReader.Info info = ImageInfoReader.getInfo(inputData.getContent());
return info != null? new ImageInfo(info.width, info.height, info.bpp) : null;
}
};
@Override
@NotNull
public ID<Integer, ImageInfo> getName() {
return INDEX_ID;
}
@Override
@NotNull
public SingleEntryIndexer<ImageInfo> getIndexer() {
return myDataIndexer;
}
public static void processValues(VirtualFile virtualFile, FileBasedIndex.ValueProcessor<ImageInfo> processor, Project project) {
FileBasedIndex.getInstance().processValues(INDEX_ID, Math.abs(FileBasedIndex.getFileId(virtualFile)), virtualFile, processor, GlobalSearchScope
.fileScope(project, virtualFile));
}
@Override
public DataExternalizer<ImageInfo> getValueExternalizer() {
return myValueExternalizer;
}
@Override
public FileBasedIndex.InputFilter getInputFilter() {
return myInputFilter;
}
@Override
public int getVersion() {
return 5;
}
public static class ImageInfo {
public int width;
public int height;
public int bpp;
public ImageInfo(int width, int height, int bpp) {
this.width = width;
this.height = height;
this.bpp = bpp;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ImageInfo imageInfo = (ImageInfo)o;
if (bpp != imageInfo.bpp) return false;
if (height != imageInfo.height) return false;
if (width != imageInfo.width) return false;
return true;
}
@Override
public int hashCode() {
int result = width;
result = 31 * result + height;
result = 31 * result + bpp;
return result;
}
}
}
@@ -50,9 +50,20 @@ public class EclipseCompiler extends ExternalCompiler {
private final Project myProject;
private final List<File> myTempFiles = new ArrayList<File>();
private static final String COMPILER_CLASS_NAME = "org.eclipse.jdt.core.compiler.batch.BatchCompiler";
@NonNls private static final String PATH_TO_COMPILER_JAR = findJarPah();
private static String findJarPah() {
try {
final Class<?> aClass = Class.forName(COMPILER_CLASS_NAME);
final String path = PathManager.getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class");
if (path != null) {
return path;
}
}
catch (ClassNotFoundException ignored) {
}
File dir = new File(PathManager.getLibPath());
File[] jars = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
File diff suppressed because it is too large Load Diff
@@ -1,188 +1,191 @@
/*
* 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.
*/
/*
* User: anna
* Date: 24-Dec-2008
*/
package com.intellij.execution.actions;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.Executor;
import com.intellij.execution.RunnerRegistry;
import com.intellij.execution.configurations.*;
import com.intellij.execution.executors.DefaultDebugExecutor;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.ProgramRunner;
import com.intellij.execution.testframework.*;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Getter;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class AbstractRerunFailedTestsAction extends AnAction {
private static final Logger LOG = Logger.getInstance("#com.intellij.execution.junit2.ui.actions.RerunFailedTestsAction");
private TestFrameworkRunningModel myModel;
private Getter<TestFrameworkRunningModel> myModelProvider;
protected TestConsoleProperties myConsoleProperties;
protected ExecutionEnvironment myEnvironment;
public void init(final TestConsoleProperties consoleProperties,
final ExecutionEnvironment environment) {
myEnvironment = environment;
myConsoleProperties = consoleProperties;
}
public void setModel(TestFrameworkRunningModel model) {
myModel = model;
}
public void setModelProvider(Getter<TestFrameworkRunningModel> modelProvider) {
myModelProvider = modelProvider;
}
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(isActive(e));
}
private boolean isActive(AnActionEvent e) {
DataContext dataContext = e.getDataContext();
Project project = PlatformDataKeys.PROJECT.getData(dataContext);
if (project == null) return false;
TestFrameworkRunningModel model = getModel();
if (model == null || model.getRoot() == null) return false;
List<AbstractTestProxy> failed = getFailedTests(project);
return !failed.isEmpty();
}
@NotNull
protected List<AbstractTestProxy> getFailedTests(Project project) {
final List<? extends AbstractTestProxy> myAllTests = getModel().getRoot().getAllTests();
return Filter.FAILED_OR_INTERRUPTED.and(JavaAwareFilter.METHOD(project)).select(myAllTests);
}
public void actionPerformed(AnActionEvent e) {
final DataContext dataContext = e.getDataContext();
boolean isDebug = myConsoleProperties.isDebug();
final MyRunProfile profile = getRunProfile();
try {
final Executor executor = isDebug ? DefaultDebugExecutor.getDebugExecutorInstance() : DefaultRunExecutor.getRunExecutorInstance();
final ProgramRunner runner = RunnerRegistry.getInstance().getRunner(executor.getId(), profile);
assert runner != null;
runner.execute(executor, new ExecutionEnvironment(runner, myEnvironment.getExecutionTarget(),
myEnvironment.getRunnerAndConfigurationSettings(),
myEnvironment.getProject()));
}
catch (ExecutionException e1) {
LOG.error(e1);
}
finally {
profile.clear();
}
}
public MyRunProfile getRunProfile() {
return null;
}
public TestFrameworkRunningModel getModel() {
if (myModel != null) {
return myModel;
}
if (myModelProvider != null) {
return myModelProvider.get();
}
return null;
}
protected static abstract class MyRunProfile extends RunConfigurationBase implements ModuleRunProfile{
private final RunConfigurationBase myConfiguration;
public MyRunProfile(RunConfigurationBase configuration) {
super(configuration.getProject(), configuration.getFactory(), ActionsBundle.message("action.RerunFailedTests.text"));
myConfiguration = configuration;
}
public void clear() { }
public void checkConfiguration() throws RuntimeConfigurationException {}
///////////////////////////////////Delegates
public void readExternal(final Element element) throws InvalidDataException {
myConfiguration.readExternal(element);
}
public void writeExternal(final Element element) throws WriteExternalException {
myConfiguration.writeExternal(element);
}
public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
return myConfiguration.getConfigurationEditor();
}
@NotNull
public ConfigurationType getType() {
return myConfiguration.getType();
}
public JDOMExternalizable createRunnerSettings(final ConfigurationInfoProvider provider) {
return myConfiguration.createRunnerSettings(provider);
}
public SettingsEditor<JDOMExternalizable> getRunnerSettingsEditor(final ProgramRunner runner) {
return myConfiguration.getRunnerSettingsEditor(runner);
}
public RunConfiguration clone() {
return myConfiguration.clone();
}
public int getUniqueID() {
return myConfiguration.getUniqueID();
}
public LogFileOptions getOptionsForPredefinedLogFile(PredefinedLogFile predefinedLogFile) {
return myConfiguration.getOptionsForPredefinedLogFile(predefinedLogFile);
}
public ArrayList<PredefinedLogFile> getPredefinedLogFiles() {
return myConfiguration.getPredefinedLogFiles();
}
public ArrayList<LogFileOptions> getAllLogFiles() {
return myConfiguration.getAllLogFiles();
}
public ArrayList<LogFileOptions> getLogFiles() {
return myConfiguration.getLogFiles();
}
}
/*
* 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.
*/
/*
* User: anna
* Date: 24-Dec-2008
*/
package com.intellij.execution.actions;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.Executor;
import com.intellij.execution.RunnerRegistry;
import com.intellij.execution.configurations.*;
import com.intellij.execution.executors.DefaultDebugExecutor;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.ProgramRunner;
import com.intellij.execution.testframework.*;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Getter;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class AbstractRerunFailedTestsAction extends AnAction {
private static final Logger LOG = Logger.getInstance("#com.intellij.execution.junit2.ui.actions.RerunFailedTestsAction");
private TestFrameworkRunningModel myModel;
private Getter<TestFrameworkRunningModel> myModelProvider;
protected TestConsoleProperties myConsoleProperties;
protected ExecutionEnvironment myEnvironment;
public void init(final TestConsoleProperties consoleProperties,
final ExecutionEnvironment environment) {
myEnvironment = environment;
myConsoleProperties = consoleProperties;
}
public void setModel(TestFrameworkRunningModel model) {
myModel = model;
}
public void setModelProvider(Getter<TestFrameworkRunningModel> modelProvider) {
myModelProvider = modelProvider;
}
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(isActive(e));
}
private boolean isActive(AnActionEvent e) {
DataContext dataContext = e.getDataContext();
Project project = PlatformDataKeys.PROJECT.getData(dataContext);
if (project == null) return false;
TestFrameworkRunningModel model = getModel();
if (model == null || model.getRoot() == null) return false;
List<AbstractTestProxy> failed = getFailedTests(project);
return !failed.isEmpty();
}
@NotNull
protected List<AbstractTestProxy> getFailedTests(Project project) {
final List<? extends AbstractTestProxy> myAllTests = getModel().getRoot().getAllTests();
return Filter.FAILED_OR_INTERRUPTED.and(JavaAwareFilter.METHOD(project)).select(myAllTests);
}
public void actionPerformed(AnActionEvent e) {
final DataContext dataContext = e.getDataContext();
boolean isDebug = myConsoleProperties.isDebug();
final MyRunProfile profile = getRunProfile();
try {
final Executor executor = isDebug ? DefaultDebugExecutor.getDebugExecutorInstance() : DefaultRunExecutor.getRunExecutorInstance();
final ProgramRunner runner = RunnerRegistry.getInstance().getRunner(executor.getId(), profile);
assert runner != null;
runner.execute(executor, new ExecutionEnvironment(profile,
myEnvironment.getExecutionTarget(),
profile.getProject(),
myEnvironment.getRunnerSettings(),
myEnvironment.getConfigurationSettings(),
null));
}
catch (ExecutionException e1) {
LOG.error(e1);
}
finally {
profile.clear();
}
}
public MyRunProfile getRunProfile() {
return null;
}
public TestFrameworkRunningModel getModel() {
if (myModel != null) {
return myModel;
}
if (myModelProvider != null) {
return myModelProvider.get();
}
return null;
}
protected static abstract class MyRunProfile extends RunConfigurationBase implements ModuleRunProfile{
private final RunConfigurationBase myConfiguration;
public MyRunProfile(RunConfigurationBase configuration) {
super(configuration.getProject(), configuration.getFactory(), ActionsBundle.message("action.RerunFailedTests.text"));
myConfiguration = configuration;
}
public void clear() { }
public void checkConfiguration() throws RuntimeConfigurationException {}
///////////////////////////////////Delegates
public void readExternal(final Element element) throws InvalidDataException {
myConfiguration.readExternal(element);
}
public void writeExternal(final Element element) throws WriteExternalException {
myConfiguration.writeExternal(element);
}
public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
return myConfiguration.getConfigurationEditor();
}
@NotNull
public ConfigurationType getType() {
return myConfiguration.getType();
}
public JDOMExternalizable createRunnerSettings(final ConfigurationInfoProvider provider) {
return myConfiguration.createRunnerSettings(provider);
}
public SettingsEditor<JDOMExternalizable> getRunnerSettingsEditor(final ProgramRunner runner) {
return myConfiguration.getRunnerSettingsEditor(runner);
}
public RunConfiguration clone() {
return myConfiguration.clone();
}
public int getUniqueID() {
return myConfiguration.getUniqueID();
}
public LogFileOptions getOptionsForPredefinedLogFile(PredefinedLogFile predefinedLogFile) {
return myConfiguration.getOptionsForPredefinedLogFile(predefinedLogFile);
}
public ArrayList<PredefinedLogFile> getPredefinedLogFiles() {
return myConfiguration.getPredefinedLogFiles();
}
public ArrayList<LogFileOptions> getAllLogFiles() {
return myConfiguration.getAllLogFiles();
}
public ArrayList<LogFileOptions> getLogFiles() {
return myConfiguration.getLogFiles();
}
}
}
@@ -101,12 +101,7 @@ public class DuplicatesImpl {
private static boolean replaceMatch(final Project project, final MatchProvider provider, final Match match, @NotNull final Editor editor,
final int idx, final int size, Ref<Boolean> showAll, final String confirmDuplicatePrompt) {
final ArrayList<RangeHighlighter> highlighters = new ArrayList<RangeHighlighter>();
highlightMatch(project, editor, match, highlighters);
final TextRange textRange = match.getTextRange();
final LogicalPosition logicalPosition = editor.offsetToLogicalPosition(textRange.getStartOffset());
expandAllRegionsCoveringRange(project, editor, textRange);
editor.getScrollingModel().scrollTo(logicalPosition, ScrollType.MAKE_VISIBLE);
final ArrayList<RangeHighlighter> highlighters = previewMatch(project, match, editor);
if (!ApplicationManager.getApplication().isUnitTestMode()) {
if (size > 1 && (showAll.get() == null || !showAll.get())) {
final String prompt = provider.getConfirmDuplicatePrompt(match);
@@ -145,6 +140,16 @@ public class DuplicatesImpl {
return false;
}
public static ArrayList<RangeHighlighter> previewMatch(Project project, Match match, Editor editor) {
final ArrayList<RangeHighlighter> highlighters = new ArrayList<RangeHighlighter>();
highlightMatch(project, editor, match, highlighters);
final TextRange textRange = match.getTextRange();
final LogicalPosition logicalPosition = editor.offsetToLogicalPosition(textRange.getStartOffset());
expandAllRegionsCoveringRange(project, editor, textRange);
editor.getScrollingModel().scrollTo(logicalPosition, ScrollType.MAKE_VISIBLE);
return highlighters;
}
private static void expandAllRegionsCoveringRange(final Project project, Editor editor, final TextRange textRange) {
final FoldRegion[] foldRegions = CodeFoldingManager.getInstance(project).getFoldRegionsAtOffset(editor, textRange.getStartOffset());
boolean anyCollapsed = false;
@@ -177,9 +182,13 @@ public class DuplicatesImpl {
public static void processDuplicates(@NotNull MatchProvider provider, @NotNull Project project, @NotNull Editor editor) {
boolean hasDuplicates = provider.hasDuplicates();
if (hasDuplicates) {
List<Match> duplicates = provider.getDuplicates();
if (duplicates.size() == 1) {
previewMatch(project, duplicates.get(0), editor);
}
final int answer = Messages.showYesNoDialog(project,
RefactoringBundle.message("0.has.detected.1.code.fragments.in.this.file.that.can.be.replaced.with.a.call.to.extracted.method",
ApplicationNamesInfo.getInstance().getProductName(), provider.getDuplicates().size()),
ApplicationNamesInfo.getInstance().getProductName(), duplicates.size()),
"Process Duplicates", Messages.getQuestionIcon());
if (answer == 0) {
invoke(project, editor, provider);
+9
View File
@@ -41,6 +41,15 @@
</library>
</orderEntry>
<orderEntry type="module" module-name="testFramework" scope="TEST" />
<orderEntry type="module-library" scope="RUNTIME">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../lib/ecj-4.2.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
</component>
</module>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -419,8 +419,9 @@ public class JavaBuilder extends ModuleLevelBuilder {
try {
final boolean rc;
if (USE_EMBEDDED_JAVAC) {
final boolean useEclipse = useEclipseCompiler(context);
rc = JavacMain.compile(
options, files, classpath, platformCp, sourcePath, outs, diagnosticSink, classesConsumer, context.getCancelStatus()
options, files, classpath, platformCp, sourcePath, outs, diagnosticSink, classesConsumer, context.getCancelStatus(), useEclipse
);
}
else {
@@ -442,6 +443,10 @@ public class JavaBuilder extends ModuleLevelBuilder {
}
}
private static boolean useEclipseCompiler(CompileContext context) {
return USE_EMBEDDED_JAVAC && "Eclipse".equalsIgnoreCase(context.getProject().getCompilerConfiguration().getOptions().get("DEFAULT_COMPILER"));
}
private void ensurePendingTasksCompleted() {
synchronized (myCounterLock) {
while (myTasksInProgress > 0) {
@@ -563,8 +568,9 @@ public class JavaBuilder extends ModuleLevelBuilder {
private static int getJavacServerHeapSize(CompileContext context) {
int heapSize = 512;
final Project project = context.getProject();
final Map<String, String> javacOpts = project.getCompilerConfiguration().getJavacOptions();
final String hSize = javacOpts.get("MAXIMUM_HEAP_SIZE");
final CompilerConfiguration config = project.getCompilerConfiguration();
final Map<String, String> opts = useEclipseCompiler(context)? config.getEclipseOptions() : config.getJavacOptions();
final String hSize = opts.get("MAXIMUM_HEAP_SIZE");
if (hSize != null) {
try {
heapSize = Integer.parseInt(hSize);
@@ -765,10 +771,10 @@ public class JavaBuilder extends ModuleLevelBuilder {
//options.add("-verbose");
final Project project = context.getProject();
final CompilerConfiguration compilerConfig = project.getCompilerConfiguration();
final Map<String, String> javacOpts = compilerConfig.getJavacOptions();
final boolean debugInfo = !"false".equals(javacOpts.get("DEBUGGING_INFO"));
final boolean nowarn = "true".equals(javacOpts.get("GENERATE_NO_WARNINGS"));
final boolean deprecation = !"false".equals(javacOpts.get("DEPRECATION"));
final Map<String, String> opts = useEclipseCompiler(context)? compilerConfig.getEclipseOptions() : compilerConfig.getJavacOptions();
final boolean debugInfo = !"false".equals(opts.get("DEBUGGING_INFO"));
final boolean nowarn = "true".equals(opts.get("GENERATE_NO_WARNINGS"));
final boolean deprecation = !"false".equals(opts.get("DEPRECATION"));
if (debugInfo) {
options.add("-g");
}
@@ -779,7 +785,7 @@ public class JavaBuilder extends ModuleLevelBuilder {
options.add("-nowarn");
}
final String customArgs = javacOpts.get("ADDITIONAL_OPTIONS_STRING");
final String customArgs = opts.get("ADDITIONAL_OPTIONS_STRING");
if (customArgs != null) {
final StringTokenizer customOptsTokenizer = new StringTokenizer(customArgs, " \t\r\n");
boolean skip = false;
@@ -1,310 +1,311 @@
package org.jetbrains.jps.incremental.storage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.io.FileUtil;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.ether.dependencyView.Mappings;
import org.jetbrains.jps.Module;
import org.jetbrains.jps.ModuleChunk;
import org.jetbrains.jps.incremental.artifacts.ArtifactsBuildData;
import java.io.*;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* @author Eugene Zhuravlev
* Date: 10/7/11
*/
public class BuildDataManager implements StorageOwner {
private static final int VERSION = 7;
private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.incremental.storage.BuildDataManager");
private static final String SRC_TO_OUTPUTS_STORAGE = "src-out";
private static final String SRC_TO_FORM_STORAGE = "src-form";
private static final String MAPPINGS_STORAGE = "mappings";
private final Object mySourceToOutputLock = new Object();
private final Map<String, SourceToOutputMapping> myProductionSourceToOutputs = new HashMap<String, SourceToOutputMapping>();
private final Map<String, SourceToOutputMapping> myTestSourceToOutputs = new HashMap<String, SourceToOutputMapping>();
private final SourceToFormMapping mySrcToFormMap;
private final ArtifactsBuildData myArtifactsBuildData;
private final ModuleOutputRootsLayout myOutputRootsLayout;
private final Mappings myMappings;
private final File myDataStorageRoot;
private final File myVersionFile;
public BuildDataManager(final File dataStorageRoot, final boolean useMemoryTempCaches) throws IOException {
myDataStorageRoot = dataStorageRoot;
mySrcToFormMap = new SourceToFormMapping(new File(getSourceToFormsRoot(), "data"));
myOutputRootsLayout = new ModuleOutputRootsLayout(new File(getOutputsLayoutRoot(), "data"));
myMappings = new Mappings(getMappingsRoot(), useMemoryTempCaches);
myArtifactsBuildData = new ArtifactsBuildData(new File(dataStorageRoot, "artifacts"));
myVersionFile = new File(myDataStorageRoot, "version.dat");
}
private File getOutputsLayoutRoot() {
return new File(myDataStorageRoot, "output-roots");
}
public SourceToOutputMapping getSourceToOutputMap(final String moduleName, final boolean testSources) throws IOException {
String lowerCaseModuleName = moduleName.toLowerCase(Locale.US);
final Map<String, SourceToOutputMapping> storageMap = testSources ? myTestSourceToOutputs : myProductionSourceToOutputs;
SourceToOutputMapping mapping;
synchronized (mySourceToOutputLock) {
mapping = storageMap.get(lowerCaseModuleName);
if (mapping == null) {
mapping = new SourceToOutputMapping(new File(getSourceToOutputRoot(lowerCaseModuleName, testSources), "data"));
storageMap.put(lowerCaseModuleName, mapping);
}
}
return mapping;
}
public ArtifactsBuildData getArtifactsBuildData() {
return myArtifactsBuildData;
}
public SourceToFormMapping getSourceToFormMap() {
return mySrcToFormMap;
}
public ModuleOutputRootsLayout getOutputRootsLayout() {
return myOutputRootsLayout;
}
public Mappings getMappings() {
return myMappings;
}
public void clean() throws IOException {
try {
myArtifactsBuildData.clean();
}
finally {
try {
synchronized (mySourceToOutputLock) {
try {
closeSourceToOutputStorages();
}
finally {
FileUtil.delete(getSourceToOutputsRoot());
}
}
}
finally {
try {
wipeStorage(getSourceToFormsRoot(), mySrcToFormMap);
}
finally {
try {
wipeStorage(getOutputsLayoutRoot(), myOutputRootsLayout);
}
finally {
final Mappings mappings = myMappings;
if (mappings != null) {
synchronized (mappings) {
mappings.clean();
}
}
else {
FileUtil.delete(getMappingsRoot());
}
}
}
}
}
}
public void flush(boolean memoryCachesOnly) {
myArtifactsBuildData.flush(memoryCachesOnly);
synchronized (mySourceToOutputLock) {
for (Map.Entry<String, SourceToOutputMapping> entry : myProductionSourceToOutputs.entrySet()) {
final SourceToOutputMapping mapping = entry.getValue();
mapping.flush(memoryCachesOnly);
}
for (Map.Entry<String, SourceToOutputMapping> entry : myTestSourceToOutputs.entrySet()) {
final SourceToOutputMapping mapping = entry.getValue();
mapping.flush(memoryCachesOnly);
}
}
mySrcToFormMap.flush(memoryCachesOnly);
myOutputRootsLayout.flush(memoryCachesOnly);
final Mappings mappings = myMappings;
if (mappings != null) {
synchronized (mappings) {
mappings.flush(memoryCachesOnly);
}
}
}
public void close() throws IOException {
try {
myArtifactsBuildData.close();
}
finally {
try {
synchronized (mySourceToOutputLock) {
closeSourceToOutputStorages();
}
}
finally {
try {
closeStorage(mySrcToFormMap);
}
finally {
try {
closeStorage(myOutputRootsLayout);
}
finally {
final Mappings mappings = myMappings;
if (mappings != null) {
try {
mappings.close();
}
catch (RuntimeException e) {
final Throwable cause = e.getCause();
if (cause instanceof IOException) {
throw ((IOException)cause);
}
throw e;
}
}
}
}
}
}
}
public void closeSourceToOutputStorages(ModuleChunk chunk, boolean testSources) throws IOException {
final Map<String, SourceToOutputMapping> storageMap = testSources? myTestSourceToOutputs : myProductionSourceToOutputs;
synchronized (mySourceToOutputLock) {
for (Module module : chunk.getModules()) {
final String moduleName = module.getName().toLowerCase(Locale.US);
final SourceToOutputMapping mapping = storageMap.remove(moduleName);
if (mapping != null) {
mapping.close();
}
}
}
}
private void closeSourceToOutputStorages() throws IOException {
IOException ex = null;
try {
for (Map.Entry<String, SourceToOutputMapping> entry : myProductionSourceToOutputs.entrySet()) {
try {
entry.getValue().close();
}
catch (IOException e) {
if (e != null) {
ex = e;
}
}
}
for (Map.Entry<String, SourceToOutputMapping> entry : myTestSourceToOutputs.entrySet()) {
try {
entry.getValue().close();
}
catch (IOException e) {
if (e != null) {
ex = e;
}
}
}
}
finally {
myProductionSourceToOutputs.clear();
myTestSourceToOutputs.clear();
}
if (ex != null) {
throw ex;
}
}
public File getSourceToFormsRoot() {
return new File(myDataStorageRoot, SRC_TO_FORM_STORAGE);
}
public File getSourceToOutputRoot(String moduleName, boolean forTests) {
return new File(getSourceToOutputsRoot(), (forTests? "tests" : "production") + "/" + moduleName);
}
private File getSourceToOutputsRoot() {
return new File(myDataStorageRoot, SRC_TO_OUTPUTS_STORAGE);
}
public File getMappingsRoot() {
return new File(myDataStorageRoot, MAPPINGS_STORAGE);
}
public File getDataStorageRoot() {
return myDataStorageRoot;
}
private static void wipeStorage(File root, @Nullable AbstractStateStorage<?, ?> storage) {
if (storage != null) {
synchronized (storage) {
storage.wipe();
}
}
else {
FileUtil.delete(root);
}
}
private static void closeStorage(@Nullable AbstractStateStorage<?, ?> storage) throws IOException {
if (storage != null) {
synchronized (storage) {
storage.close();
}
}
}
private Boolean myVersionDiffers = null;
public boolean versionDiffers() {
final Boolean cached = myVersionDiffers;
if (cached != null) {
return cached;
}
try {
final DataInputStream is = new DataInputStream(new FileInputStream(myVersionFile));
try {
final boolean diff = is.readInt() != VERSION;
myVersionDiffers = diff;
return diff;
}
finally {
is.close();
}
}
catch (FileNotFoundException ignored) {
return false; // treat it as a new dir
}
catch (IOException ex) {
LOG.info(ex);
}
return true;
}
public void saveVersion() {
final Boolean differs = myVersionDiffers;
if (differs == null || differs) {
try {
FileUtil.createIfDoesntExist(myVersionFile);
final DataOutputStream os = new DataOutputStream(new FileOutputStream(myVersionFile));
try {
os.writeInt(VERSION);
myVersionDiffers = Boolean.FALSE;
}
finally {
os.close();
}
}
catch (IOException ignored) {
}
}
}
}
package org.jetbrains.jps.incremental.storage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.io.FileUtil;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.ether.dependencyView.Mappings;
import org.jetbrains.jps.Module;
import org.jetbrains.jps.ModuleChunk;
import org.jetbrains.jps.incremental.artifacts.ArtifactsBuildData;
import java.io.*;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* @author Eugene Zhuravlev
* Date: 10/7/11
*/
public class BuildDataManager implements StorageOwner {
private static final int VERSION = 7;
private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.incremental.storage.BuildDataManager");
private static final String SRC_TO_OUTPUTS_STORAGE = "src-out";
private static final String SRC_TO_FORM_STORAGE = "src-form";
private static final String MAPPINGS_STORAGE = "mappings";
private final Object mySourceToOutputLock = new Object();
private final Map<String, SourceToOutputMapping> myProductionSourceToOutputs = new HashMap<String, SourceToOutputMapping>();
private final Map<String, SourceToOutputMapping> myTestSourceToOutputs = new HashMap<String, SourceToOutputMapping>();
private final SourceToFormMapping mySrcToFormMap;
private final ArtifactsBuildData myArtifactsBuildData;
private final ModuleOutputRootsLayout myOutputRootsLayout;
private final Mappings myMappings;
private final File myDataStorageRoot;
private final File myVersionFile;
public BuildDataManager(final File dataStorageRoot, final boolean useMemoryTempCaches) throws IOException {
myDataStorageRoot = dataStorageRoot;
mySrcToFormMap = new SourceToFormMapping(new File(getSourceToFormsRoot(), "data"));
myOutputRootsLayout = new ModuleOutputRootsLayout(new File(getOutputsLayoutRoot(), "data"));
myMappings = new Mappings(getMappingsRoot(), useMemoryTempCaches);
myArtifactsBuildData = new ArtifactsBuildData(new File(dataStorageRoot, "artifacts"));
myVersionFile = new File(myDataStorageRoot, "version.dat");
}
private File getOutputsLayoutRoot() {
return new File(myDataStorageRoot, "output-roots");
}
public SourceToOutputMapping getSourceToOutputMap(final String moduleName, final boolean testSources) throws IOException {
String lowerCaseModuleName = moduleName.toLowerCase(Locale.US);
final Map<String, SourceToOutputMapping> storageMap = testSources ? myTestSourceToOutputs : myProductionSourceToOutputs;
SourceToOutputMapping mapping;
synchronized (mySourceToOutputLock) {
mapping = storageMap.get(lowerCaseModuleName);
if (mapping == null) {
mapping = new SourceToOutputMapping(new File(getSourceToOutputRoot(lowerCaseModuleName, testSources), "data"));
storageMap.put(lowerCaseModuleName, mapping);
}
}
return mapping;
}
public ArtifactsBuildData getArtifactsBuildData() {
return myArtifactsBuildData;
}
public SourceToFormMapping getSourceToFormMap() {
return mySrcToFormMap;
}
public ModuleOutputRootsLayout getOutputRootsLayout() {
return myOutputRootsLayout;
}
public Mappings getMappings() {
return myMappings;
}
public void clean() throws IOException {
try {
myArtifactsBuildData.clean();
}
finally {
try {
synchronized (mySourceToOutputLock) {
try {
closeSourceToOutputStorages();
}
finally {
FileUtil.delete(getSourceToOutputsRoot());
}
}
}
finally {
try {
wipeStorage(getSourceToFormsRoot(), mySrcToFormMap);
}
finally {
try {
wipeStorage(getOutputsLayoutRoot(), myOutputRootsLayout);
}
finally {
final Mappings mappings = myMappings;
if (mappings != null) {
synchronized (mappings) {
mappings.clean();
}
}
else {
FileUtil.delete(getMappingsRoot());
}
}
}
}
}
saveVersion();
}
public void flush(boolean memoryCachesOnly) {
myArtifactsBuildData.flush(memoryCachesOnly);
synchronized (mySourceToOutputLock) {
for (Map.Entry<String, SourceToOutputMapping> entry : myProductionSourceToOutputs.entrySet()) {
final SourceToOutputMapping mapping = entry.getValue();
mapping.flush(memoryCachesOnly);
}
for (Map.Entry<String, SourceToOutputMapping> entry : myTestSourceToOutputs.entrySet()) {
final SourceToOutputMapping mapping = entry.getValue();
mapping.flush(memoryCachesOnly);
}
}
mySrcToFormMap.flush(memoryCachesOnly);
myOutputRootsLayout.flush(memoryCachesOnly);
final Mappings mappings = myMappings;
if (mappings != null) {
synchronized (mappings) {
mappings.flush(memoryCachesOnly);
}
}
}
public void close() throws IOException {
try {
myArtifactsBuildData.close();
}
finally {
try {
synchronized (mySourceToOutputLock) {
closeSourceToOutputStorages();
}
}
finally {
try {
closeStorage(mySrcToFormMap);
}
finally {
try {
closeStorage(myOutputRootsLayout);
}
finally {
final Mappings mappings = myMappings;
if (mappings != null) {
try {
mappings.close();
}
catch (RuntimeException e) {
final Throwable cause = e.getCause();
if (cause instanceof IOException) {
throw ((IOException)cause);
}
throw e;
}
}
}
}
}
}
}
public void closeSourceToOutputStorages(ModuleChunk chunk, boolean testSources) throws IOException {
final Map<String, SourceToOutputMapping> storageMap = testSources? myTestSourceToOutputs : myProductionSourceToOutputs;
synchronized (mySourceToOutputLock) {
for (Module module : chunk.getModules()) {
final String moduleName = module.getName().toLowerCase(Locale.US);
final SourceToOutputMapping mapping = storageMap.remove(moduleName);
if (mapping != null) {
mapping.close();
}
}
}
}
private void closeSourceToOutputStorages() throws IOException {
IOException ex = null;
try {
for (Map.Entry<String, SourceToOutputMapping> entry : myProductionSourceToOutputs.entrySet()) {
try {
entry.getValue().close();
}
catch (IOException e) {
if (e != null) {
ex = e;
}
}
}
for (Map.Entry<String, SourceToOutputMapping> entry : myTestSourceToOutputs.entrySet()) {
try {
entry.getValue().close();
}
catch (IOException e) {
if (e != null) {
ex = e;
}
}
}
}
finally {
myProductionSourceToOutputs.clear();
myTestSourceToOutputs.clear();
}
if (ex != null) {
throw ex;
}
}
public File getSourceToFormsRoot() {
return new File(myDataStorageRoot, SRC_TO_FORM_STORAGE);
}
public File getSourceToOutputRoot(String moduleName, boolean forTests) {
return new File(getSourceToOutputsRoot(), (forTests? "tests" : "production") + "/" + moduleName);
}
private File getSourceToOutputsRoot() {
return new File(myDataStorageRoot, SRC_TO_OUTPUTS_STORAGE);
}
public File getMappingsRoot() {
return new File(myDataStorageRoot, MAPPINGS_STORAGE);
}
public File getDataStorageRoot() {
return myDataStorageRoot;
}
private static void wipeStorage(File root, @Nullable AbstractStateStorage<?, ?> storage) {
if (storage != null) {
synchronized (storage) {
storage.wipe();
}
}
else {
FileUtil.delete(root);
}
}
private static void closeStorage(@Nullable AbstractStateStorage<?, ?> storage) throws IOException {
if (storage != null) {
synchronized (storage) {
storage.close();
}
}
}
private Boolean myVersionDiffers = null;
public boolean versionDiffers() {
final Boolean cached = myVersionDiffers;
if (cached != null) {
return cached;
}
try {
final DataInputStream is = new DataInputStream(new FileInputStream(myVersionFile));
try {
final boolean diff = is.readInt() != VERSION;
myVersionDiffers = diff;
return diff;
}
finally {
is.close();
}
}
catch (FileNotFoundException ignored) {
return false; // treat it as a new dir
}
catch (IOException ex) {
LOG.info(ex);
}
return true;
}
public void saveVersion() {
final Boolean differs = myVersionDiffers;
if (differs == null || differs) {
try {
FileUtil.createIfDoesntExist(myVersionFile);
final DataOutputStream os = new DataOutputStream(new FileOutputStream(myVersionFile));
try {
os.writeInt(VERSION);
myVersionDiffers = Boolean.FALSE;
}
finally {
os.close();
}
}
catch (IOException ignored) {
}
}
}
}
@@ -1,188 +1,216 @@
package org.jetbrains.jps.javac;
import com.intellij.openapi.util.SystemInfo;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.api.CanceledStatus;
import org.jetbrains.jps.server.ClasspathBootstrap;
import javax.tools.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
/**
* @author Eugene Zhuravlev
* Date: 1/21/12
*/
public class JavacMain {
private static final boolean IS_VM_6_VERSION = System.getProperty("java.version", "1.6").contains("1.6");
private static final Set<String> FILTERED_OPTIONS = new HashSet<String>(Arrays.<String>asList(
"-d", "-classpath", "-cp", "-bootclasspath"
));
private static final Set<String> FILTERED_SINGLE_OPTIONS = new HashSet<String>(Arrays.<String>asList(
"-verbose", "-proc:only", "-implicit:class", "-implicit:none"
));
public static boolean compile(Collection<String> options,
final Collection<File> sources,
Collection<File> classpath,
Collection<File> platformClasspath,
Collection<File> sourcePath,
Map<File, Set<File>> outputDirToRoots,
final DiagnosticOutputConsumer outConsumer,
final OutputFileConsumer outputSink,
CanceledStatus canceledStatus) {
final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
for (File outputDir : outputDirToRoots.keySet()) {
outputDir.mkdirs();
}
final JavacFileManager fileManager = new JavacFileManager(new ContextImpl(compiler, outConsumer, outputSink, canceledStatus));
fileManager.handleOption("-bootclasspath", Collections.singleton("").iterator()); // this will clear cached stuff
fileManager.handleOption("-extdirs", Collections.singleton("").iterator()); // this will clear cached stuff
try {
fileManager.setOutputDirectories(outputDirToRoots);
}
catch (IOException e) {
fileManager.getContext().reportMessage(Diagnostic.Kind.ERROR, e.getMessage());
return false;
}
if (!classpath.isEmpty()) {
try {
fileManager.setLocation(StandardLocation.CLASS_PATH, classpath);
}
catch (IOException e) {
fileManager.getContext().reportMessage(Diagnostic.Kind.ERROR, e.getMessage());
return false;
}
}
if (!platformClasspath.isEmpty()) {
try {
fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, platformClasspath);
}
catch (IOException e) {
fileManager.getContext().reportMessage(Diagnostic.Kind.ERROR, e.getMessage());
return false;
}
}
if (!sourcePath.isEmpty()) {
try {
fileManager.setLocation(StandardLocation.SOURCE_PATH, sourcePath);
}
catch (IOException e) {
fileManager.getContext().reportMessage(Diagnostic.Kind.ERROR, e.getMessage());
return false;
}
}
//noinspection IOResourceOpenedButNotSafelyClosed
final LineOutputWriter out = new LineOutputWriter() {
protected void lineAvailable(String line) {
outConsumer.outputLineAvailable(line);
}
};
try {
final Collection<String> _options = prepareOptions(options);
final JavaCompiler.CompilationTask task = compiler.getTask(
out, fileManager, outConsumer, _options, null, fileManager.toJavaFileObjects(sources)
);
//if (!IS_VM_6_VERSION) { //todo!
// // Do not add the processor for JDK 1.6 because of the bugs in javac
// // The processor's presence may lead to NPE and resolve bugs in compiler
// final JavacASTAnalyser analyzer = new JavacASTAnalyser(outConsumer, !annotationProcessingEnabled);
// task.setProcessors(Collections.singleton(analyzer));
//}
return task.call();
}
catch(IllegalArgumentException e) {
outConsumer.report(new PlainMessageDiagnostic(Diagnostic.Kind.ERROR, e.getMessage()));
}
finally {
fileManager.close();
}
return false;
}
private static boolean isAnnotationProcessingEnabled(final Collection<String> options) {
for (String option : options) {
if ("-proc:none".equals(option)) {
return false;
}
}
return true;
}
private static Collection<String> prepareOptions(final Collection<String> options) {
final List<String> result = new ArrayList<String>();
result.add("-implicit:class");
boolean skip = false;
for (String option : options) {
if (FILTERED_OPTIONS.contains(option)) {
skip = true;
continue;
}
if (!skip) {
if (!FILTERED_SINGLE_OPTIONS.contains(option)) {
result.add(option);
}
}
skip = false;
}
return result;
}
private static class ContextImpl implements JavacFileManager.Context {
private final StandardJavaFileManager myStdManager;
private final DiagnosticOutputConsumer myOutConsumer;
private final OutputFileConsumer myOutputFileSink;
private final CanceledStatus myCanceledStatus;
public ContextImpl(@NotNull JavaCompiler compiler,
@NotNull DiagnosticOutputConsumer outConsumer,
@NotNull OutputFileConsumer sink,
CanceledStatus canceledStatus) {
myOutConsumer = outConsumer;
myOutputFileSink = sink;
myCanceledStatus = canceledStatus;
StandardJavaFileManager stdManager = null;
final Class<StandardJavaFileManager> optimizedManagerClass = ClasspathBootstrap.getOptimizedFileManagerClass();
if (optimizedManagerClass != null) {
try {
stdManager = optimizedManagerClass.newInstance();
}
catch (Throwable e) {
if (SystemInfo.isWindows) {
System.err.println("Failed to load JPS optimized file manager for javac: " + e.getMessage());
}
}
}
if (stdManager != null) {
myStdManager = stdManager;
}
else {
myStdManager = compiler.getStandardFileManager(outConsumer, Locale.US, null);
}
}
public boolean isCanceled() {
return myCanceledStatus.isCanceled();
}
public StandardJavaFileManager getStandardFileManager() {
return myStdManager;
}
public void reportMessage(final Diagnostic.Kind kind, String message) {
myOutConsumer.report(new PlainMessageDiagnostic(kind, message));
}
public void consumeOutputFile(@NotNull final OutputFileObject cls) {
myOutputFileSink.save(cls);
}
}
}
package org.jetbrains.jps.javac;
import com.intellij.openapi.util.SystemInfo;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.api.CanceledStatus;
import org.jetbrains.jps.server.ClasspathBootstrap;
import javax.tools.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
/**
* @author Eugene Zhuravlev
* Date: 1/21/12
*/
public class JavacMain {
private static final boolean IS_VM_6_VERSION = System.getProperty("java.version", "1.6").contains("1.6");
private static final Set<String> FILTERED_OPTIONS = new HashSet<String>(Arrays.<String>asList(
"-d", "-classpath", "-cp", "-bootclasspath"
));
private static final Set<String> FILTERED_SINGLE_OPTIONS = new HashSet<String>(Arrays.<String>asList(
"-verbose", "-proc:only", "-implicit:class", "-implicit:none"
));
private static final JavaCompiler SYSTEM_JAVA_COMPILER = ToolProvider.getSystemJavaCompiler();
public static boolean compile(Collection<String> options,
final Collection<File> sources,
Collection<File> classpath,
Collection<File> platformClasspath,
Collection<File> sourcePath,
Map<File, Set<File>> outputDirToRoots,
final DiagnosticOutputConsumer outConsumer,
final OutputFileConsumer outputSink,
CanceledStatus canceledStatus, boolean useEclipseCompiler) {
JavaCompiler compiler = null;
if (useEclipseCompiler) {
for (JavaCompiler javaCompiler : ServiceLoader.load(JavaCompiler.class)) {
compiler = javaCompiler;
break;
}
if (compiler == null) {
compiler = SYSTEM_JAVA_COMPILER;
}
}
else {
compiler = SYSTEM_JAVA_COMPILER;
}
final boolean nowUsingJavac = compiler == SYSTEM_JAVA_COMPILER;
if (nowUsingJavac && useEclipseCompiler) {
final String message = "Eclipse Batch Compiler was not found in classpath";
outConsumer.report(new PlainMessageDiagnostic(Diagnostic.Kind.ERROR, message));
return false;
}
for (File outputDir : outputDirToRoots.keySet()) {
outputDir.mkdirs();
}
final JavacFileManager fileManager = new JavacFileManager(new ContextImpl(compiler, outConsumer, outputSink, canceledStatus));
fileManager.handleOption("-bootclasspath", Collections.singleton("").iterator()); // this will clear cached stuff
fileManager.handleOption("-extdirs", Collections.singleton("").iterator()); // this will clear cached stuff
try {
fileManager.setOutputDirectories(outputDirToRoots);
}
catch (IOException e) {
fileManager.getContext().reportMessage(Diagnostic.Kind.ERROR, e.getMessage());
return false;
}
if (!classpath.isEmpty()) {
try {
fileManager.setLocation(StandardLocation.CLASS_PATH, classpath);
}
catch (IOException e) {
fileManager.getContext().reportMessage(Diagnostic.Kind.ERROR, e.getMessage());
return false;
}
}
if (!platformClasspath.isEmpty()) {
try {
fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, platformClasspath);
}
catch (IOException e) {
fileManager.getContext().reportMessage(Diagnostic.Kind.ERROR, e.getMessage());
return false;
}
}
if (!sourcePath.isEmpty()) {
try {
fileManager.setLocation(StandardLocation.SOURCE_PATH, sourcePath);
}
catch (IOException e) {
fileManager.getContext().reportMessage(Diagnostic.Kind.ERROR, e.getMessage());
return false;
}
}
//noinspection IOResourceOpenedButNotSafelyClosed
final LineOutputWriter out = new LineOutputWriter() {
protected void lineAvailable(String line) {
if (nowUsingJavac) {
outConsumer.outputLineAvailable(line);
}
else {
// todo: filter too verbose eclipse output?
}
}
};
try {
final Collection<String> _options = prepareOptions(options, compiler);
final JavaCompiler.CompilationTask task = compiler.getTask(
out, fileManager, outConsumer, _options, null, fileManager.toJavaFileObjects(sources)
);
//if (!IS_VM_6_VERSION) { //todo!
// // Do not add the processor for JDK 1.6 because of the bugs in javac
// // The processor's presence may lead to NPE and resolve bugs in compiler
// final JavacASTAnalyser analyzer = new JavacASTAnalyser(outConsumer, !annotationProcessingEnabled);
// task.setProcessors(Collections.singleton(analyzer));
//}
return task.call();
}
catch(IllegalArgumentException e) {
outConsumer.report(new PlainMessageDiagnostic(Diagnostic.Kind.ERROR, e.getMessage()));
}
finally {
fileManager.close();
}
return false;
}
private static boolean isAnnotationProcessingEnabled(final Collection<String> options) {
for (String option : options) {
if ("-proc:none".equals(option)) {
return false;
}
}
return true;
}
private static Collection<String> prepareOptions(final Collection<String> options, JavaCompiler compiler) {
final List<String> result = new ArrayList<String>();
if (compiler == SYSTEM_JAVA_COMPILER) {
result.add("-implicit:class"); // the option supported by javac only
}
boolean skip = false;
for (String option : options) {
if (FILTERED_OPTIONS.contains(option)) {
skip = true;
continue;
}
if (!skip) {
if (!FILTERED_SINGLE_OPTIONS.contains(option)) {
result.add(option);
}
}
skip = false;
}
return result;
}
private static class ContextImpl implements JavacFileManager.Context {
private final StandardJavaFileManager myStdManager;
private final DiagnosticOutputConsumer myOutConsumer;
private final OutputFileConsumer myOutputFileSink;
private final CanceledStatus myCanceledStatus;
public ContextImpl(@NotNull JavaCompiler compiler,
@NotNull DiagnosticOutputConsumer outConsumer,
@NotNull OutputFileConsumer sink,
CanceledStatus canceledStatus) {
myOutConsumer = outConsumer;
myOutputFileSink = sink;
myCanceledStatus = canceledStatus;
StandardJavaFileManager stdManager = null;
final Class<StandardJavaFileManager> optimizedManagerClass = ClasspathBootstrap.getOptimizedFileManagerClass();
if (optimizedManagerClass != null) {
try {
stdManager = optimizedManagerClass.newInstance();
}
catch (Throwable e) {
if (SystemInfo.isWindows) {
System.err.println("Failed to load JPS optimized file manager for javac: " + e.getMessage());
}
}
}
if (stdManager != null) {
myStdManager = stdManager;
}
else {
myStdManager = compiler.getStandardFileManager(outConsumer, Locale.US, null);
}
}
public boolean isCanceled() {
return myCanceledStatus.isCanceled();
}
public StandardJavaFileManager getStandardFileManager() {
return myStdManager;
}
public void reportMessage(final Diagnostic.Kind kind, String message) {
myOutConsumer.report(new PlainMessageDiagnostic(kind, message));
}
public void consumeOutputFile(@NotNull final OutputFileObject cls) {
myOutputFileSink.save(cls);
}
}
}
@@ -14,7 +14,8 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.api.CanceledStatus;
import org.jetbrains.jps.api.SharedThreadPool;
import javax.tools.*;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
import java.io.File;
import java.net.InetSocketAddress;
import java.util.*;
@@ -134,7 +135,7 @@ public class JavacServer {
};
try {
final boolean rc = JavacMain.compile(options, files, classpath, platformCp, sourcePath, outs, diagnostic, outputSink, canceledStatus);
final boolean rc = JavacMain.compile(options, files, classpath, platformCp, sourcePath, outs, diagnostic, outputSink, canceledStatus, false);
return JavacProtoUtil.toMessage(sessionId, JavacProtoUtil.createBuildCompletedResponse(rc));
}
catch (CompilationCanceledException e) {
File diff suppressed because it is too large Load Diff
@@ -1,360 +1,359 @@
package org.jetbrains.jps.javac;
import com.sun.tools.javac.file.BaseFileObject;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.file.RelativePath;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import javax.lang.model.SourceVersion;
import javax.tools.JavaFileObject;
import java.io.*;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetDecoder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* WARNING: Loaded via reflection, do not delete
*
* @noinspection UnusedDeclaration
*/
class OptimizedFileManager17 extends com.sun.tools.javac.file.JavacFileManager {
private boolean myUseZipFileIndex;
private final Map<File, Archive> myArchives;
private final Map<File, Boolean> myIsFile = new ConcurrentHashMap<File, Boolean>();
private final Map<File, SoftReference<File[]>> myDirectoryCache = new HashMap<File, SoftReference<File[]>>();
public static final File[] NULL_FILE_ARRAY = new File[0];
public OptimizedFileManager17() throws Throwable {
super(new Context(), true, null);
final Field archivesField = com.sun.tools.javac.file.JavacFileManager.class.getDeclaredField("archives");
archivesField.setAccessible(true);
myArchives = (Map<File, Archive>) archivesField.get(this);
}
@Override
public Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(Iterable<? extends File> files) {
java.util.List<InputFileObject> result;
if (files instanceof Collection) {
result = new ArrayList<InputFileObject>(((Collection)files).size());
}
else {
result = new ArrayList<InputFileObject>();
}
for (File f: files) {
result.add(new InputFileObject(this, f));
}
return result;
}
@Override
public Iterable<JavaFileObject> list(Location location, String packageName, Set<JavaFileObject.Kind> kinds, boolean recurse) throws IOException {
Iterable<? extends File> locationRoots = getLocation(location);
if (locationRoots == null) {
return List.nil();
}
RelativePath.RelativeDirectory subdirectory = new RelativePath.RelativeDirectory(packageName.replace('.', '/'));
ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();
for (File root : locationRoots) {
Archive archive = myArchives.get(root);
final boolean isFile;
if (archive != null) {
isFile = true;
}
else {
isFile = isFile(root);
}
if (isFile) {
// Not a directory; either a file or non-existant, create the archive
try {
if (archive == null) {
archive = openArchive(root);
}
listArchive(archive, subdirectory, kinds, recurse, results);
}
catch (IOException ex) {
log.error("error.reading.file", root, getMessage(ex));
}
}
else {
final File dir = subdirectory.getFile(root);
if (recurse) {
listDirectoryRecursively(dir, kinds, results, true, !location.isOutputLocation());
}
else {
listDirectory(dir, kinds, results, !location.isOutputLocation());
}
}
}
return results.toList();
}
private static void listArchive(Archive archive, RelativePath.RelativeDirectory subdirectory, Set<JavaFileObject.Kind> fileKinds, boolean recurse, ListBuffer<JavaFileObject> resultList) {
// Get the files directly in the subdir
List<String> files = archive.getFiles(subdirectory);
if (files != null) {
for (; !files.isEmpty(); files = files.tail) {
String file = files.head;
if (isValidFile(file, fileKinds)) {
resultList.append(archive.getFileObject(subdirectory, file));
}
}
}
if (recurse) {
for (RelativePath.RelativeDirectory s: archive.getSubdirectories()) {
if (contains(subdirectory, s)) {
// Because the archive map is a flat list of directories,
// the enclosing loop will pick up all child subdirectories.
// Therefore, there is no need to recurse deeper.
listArchive(archive, s, fileKinds, false, resultList);
}
}
}
}
private void listDirectory(File directory, Set<JavaFileObject.Kind> fileKinds, ListBuffer<JavaFileObject> resultList, boolean canUseCache) {
final File[] files = listChildren(directory, canUseCache);
if (files != null) {
if (sortFiles != null) {
Arrays.sort(files, sortFiles);
}
final boolean acceptUnknownFiles = fileKinds.contains(JavaFileObject.Kind.OTHER);
for (File f: files) {
final String fileName = f.getName();
if (isValidFile(fileName, fileKinds)) {
if (acceptUnknownFiles && !isFile(f)) {
continue;
}
final JavaFileObject fe = new InputFileObject(this, f);
resultList.append(fe);
}
}
}
}
private void listDirectoryRecursively(File file, Set<JavaFileObject.Kind> fileKinds, ListBuffer<JavaFileObject> resultList, boolean isRootCall, boolean canUseCache) {
final File[] children = listChildren(file, canUseCache);
final String fileName = file.getName();
if (children != null) { // is directory
if (isRootCall || SourceVersion.isIdentifier(fileName)) {
if (sortFiles != null) {
Arrays.sort(children, sortFiles);
}
for (File child : children) {
listDirectoryRecursively(child, fileKinds, resultList, false, canUseCache);
}
}
}
else {
if (isValidFile(fileName, fileKinds)) {
JavaFileObject fe = new InputFileObject(this, file);
resultList.append(fe);
}
}
}
private File[] listChildren(File file, boolean canUseCache) {
if (!canUseCache) {
return file.listFiles();
}
final SoftReference<File[]> ref = myDirectoryCache.get(file);
File[] cached = ref != null? ref.get() : null;
if (cached == null) {
cached = file.listFiles();
myDirectoryCache.put(file, new SoftReference<File[]>(cached != null? cached : NULL_FILE_ARRAY));
}
return cached == NULL_FILE_ARRAY ? null : cached;
}
private boolean isFile(File root) {
Boolean cachedIsFile = myIsFile.get(root);
if (cachedIsFile == null) {
cachedIsFile = Boolean.valueOf(root.isFile());
myIsFile.put(root, cachedIsFile);
}
return cachedIsFile.booleanValue();
}
private static boolean contains(RelativePath.RelativeDirectory subdirectory, RelativePath.RelativeDirectory other) {
final String subdirPath = subdirectory.getPath();
final String otherPath = other.getPath();
return otherPath.length() > subdirPath.length() && otherPath.startsWith(subdirPath);
}
private static boolean isValidFile(String name, Set<JavaFileObject.Kind> fileKinds) {
return fileKinds.contains(getKind(name));
}
private class InputFileObject extends BaseFileObject {
private String name;
final File file;
private Reference<File> absFileRef;
public InputFileObject(JavacFileManager fileManager, File f) {
this(fileManager, f.getName(), f);
}
public InputFileObject(JavacFileManager fileManager, String name, File f) {
super(fileManager);
this.name = name;
this.file = f;
}
@Override
public URI toUri() {
return file.toURI().normalize();
}
@Override
public String getName() {
return file.getPath();
}
@Override
public String getShortName() {
return name;
}
@Override
public JavaFileObject.Kind getKind() {
return getKind(name);
}
@Override
public InputStream openInputStream() throws IOException {
return new FileInputStream(file);
}
@Override
public OutputStream openOutputStream() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public Writer openWriter() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public long getLastModified() {
return file.lastModified();
}
@Override
public boolean delete() {
return file.delete();
}
@Override
protected CharsetDecoder getDecoder(boolean ignoreEncodingErrors) {
return fileManager.getDecoder(fileManager.getEncodingName(), ignoreEncodingErrors);
}
@Override
protected String inferBinaryName(Iterable<? extends File> path) {
String fPath = file.getPath();
//System.err.println("RegularFileObject " + file + " " +r.getPath());
for (File dir: path) {
//System.err.println("dir: " + dir);
String dPath = dir.getPath();
if (dPath.length() == 0)
dPath = System.getProperty("user.dir");
if (!dPath.endsWith(File.separator))
dPath += File.separator;
if (fPath.regionMatches(true, 0, dPath, 0, dPath.length())
&& new File(fPath.substring(0, dPath.length())).equals(new File(dPath))) {
String relativeName = fPath.substring(dPath.length());
return removeExtension(relativeName).replace(File.separatorChar, '.');
}
}
return null;
}
@Override
public boolean isNameCompatible(String cn, JavaFileObject.Kind kind) {
cn.getClass();
// null check
if (kind == Kind.OTHER && getKind() != kind) {
return false;
}
String n = cn + kind.extension;
if (name.equals(n)) {
return true;
}
if (name.equalsIgnoreCase(n)) {
return file.getName().equals(n);
}
return false;
}
/**
* Check if two file objects are equal.
* Two RegularFileObjects are equal if the absolute paths of the underlying
* files are equal.
*/
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (!(other instanceof InputFileObject))
return false;
InputFileObject o = (InputFileObject) other;
return getAbsoluteFile().equals(o.getAbsoluteFile());
}
@Override
public int hashCode() {
return getAbsoluteFile().hashCode();
}
private File getAbsoluteFile() {
File absFile = (absFileRef == null ? null : absFileRef.get());
if (absFile == null) {
absFile = file.getAbsoluteFile();
absFileRef = new SoftReference<File>(absFile);
}
return absFile;
}
public CharBuffer getCharContent(boolean ignoreEncodingErrors) throws IOException {
CharBuffer cb = fileManager.getCachedContent(this);
if (cb == null) {
InputStream in = new FileInputStream(file);
try {
ByteBuffer bb = fileManager.makeByteBuffer(in);
JavaFileObject prev = fileManager.log.useSource(this);
try {
cb = fileManager.decode(bb, ignoreEncodingErrors);
} finally {
fileManager.log.useSource(prev);
}
fileManager.recycleByteBuffer(bb);
if (!ignoreEncodingErrors) {
fileManager.cache(this, cb);
}
} finally {
in.close();
}
}
return cb;
}
}
}
package org.jetbrains.jps.javac;
import com.sun.tools.javac.file.BaseFileObject;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.file.RelativePath;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import javax.lang.model.SourceVersion;
import javax.tools.JavaFileObject;
import java.io.*;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetDecoder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* WARNING: Loaded via reflection, do not delete
*
* @noinspection UnusedDeclaration
*/
class OptimizedFileManager17 extends com.sun.tools.javac.file.JavacFileManager {
private boolean myUseZipFileIndex;
private final Map<File, Archive> myArchives;
private final Map<File, Boolean> myIsFile = new ConcurrentHashMap<File, Boolean>();
private final Map<File, File[]> myDirectoryCache = new ConcurrentHashMap<File, File[]>();
public static final File[] NULL_FILE_ARRAY = new File[0];
public OptimizedFileManager17() throws Throwable {
super(new Context(), true, null);
final Field archivesField = com.sun.tools.javac.file.JavacFileManager.class.getDeclaredField("archives");
archivesField.setAccessible(true);
myArchives = (Map<File, Archive>) archivesField.get(this);
}
@Override
public Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(Iterable<? extends File> files) {
java.util.List<InputFileObject> result;
if (files instanceof Collection) {
result = new ArrayList<InputFileObject>(((Collection)files).size());
}
else {
result = new ArrayList<InputFileObject>();
}
for (File f: files) {
result.add(new InputFileObject(this, f));
}
return result;
}
@Override
public Iterable<JavaFileObject> list(Location location, String packageName, Set<JavaFileObject.Kind> kinds, boolean recurse) throws IOException {
Iterable<? extends File> locationRoots = getLocation(location);
if (locationRoots == null) {
return List.nil();
}
RelativePath.RelativeDirectory subdirectory = new RelativePath.RelativeDirectory(packageName.replace('.', '/'));
ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();
for (File root : locationRoots) {
Archive archive = myArchives.get(root);
final boolean isFile;
if (archive != null) {
isFile = true;
}
else {
isFile = isFile(root);
}
if (isFile) {
// Not a directory; either a file or non-existant, create the archive
try {
if (archive == null) {
archive = openArchive(root);
}
listArchive(archive, subdirectory, kinds, recurse, results);
}
catch (IOException ex) {
log.error("error.reading.file", root, getMessage(ex));
}
}
else {
final File dir = subdirectory.getFile(root);
if (recurse) {
listDirectoryRecursively(dir, kinds, results, true, !location.isOutputLocation());
}
else {
listDirectory(dir, kinds, results, !location.isOutputLocation());
}
}
}
return results.toList();
}
private static void listArchive(Archive archive, RelativePath.RelativeDirectory subdirectory, Set<JavaFileObject.Kind> fileKinds, boolean recurse, ListBuffer<JavaFileObject> resultList) {
// Get the files directly in the subdir
List<String> files = archive.getFiles(subdirectory);
if (files != null) {
for (; !files.isEmpty(); files = files.tail) {
String file = files.head;
if (isValidFile(file, fileKinds)) {
resultList.append(archive.getFileObject(subdirectory, file));
}
}
}
if (recurse) {
for (RelativePath.RelativeDirectory s: archive.getSubdirectories()) {
if (contains(subdirectory, s)) {
// Because the archive map is a flat list of directories,
// the enclosing loop will pick up all child subdirectories.
// Therefore, there is no need to recurse deeper.
listArchive(archive, s, fileKinds, false, resultList);
}
}
}
}
private void listDirectory(File directory, Set<JavaFileObject.Kind> fileKinds, ListBuffer<JavaFileObject> resultList, boolean canUseCache) {
final File[] files = listChildren(directory, canUseCache);
if (files != null) {
if (sortFiles != null) {
Arrays.sort(files, sortFiles);
}
final boolean acceptUnknownFiles = fileKinds.contains(JavaFileObject.Kind.OTHER);
for (File f: files) {
final String fileName = f.getName();
if (isValidFile(fileName, fileKinds)) {
if (acceptUnknownFiles && !isFile(f)) {
continue;
}
final JavaFileObject fe = new InputFileObject(this, f);
resultList.append(fe);
}
}
}
}
private void listDirectoryRecursively(File file, Set<JavaFileObject.Kind> fileKinds, ListBuffer<JavaFileObject> resultList, boolean isRootCall, boolean canUseCache) {
final File[] children = listChildren(file, canUseCache);
final String fileName = file.getName();
if (children != null) { // is directory
if (isRootCall || SourceVersion.isIdentifier(fileName)) {
if (sortFiles != null) {
Arrays.sort(children, sortFiles);
}
for (File child : children) {
listDirectoryRecursively(child, fileKinds, resultList, false, canUseCache);
}
}
}
else {
if (isValidFile(fileName, fileKinds)) {
JavaFileObject fe = new InputFileObject(this, file);
resultList.append(fe);
}
}
}
private File[] listChildren(File file, boolean canUseCache) {
if (!canUseCache) {
return file.listFiles();
}
File[] cached = myDirectoryCache.get(file);
if (cached == null) {
cached = file.listFiles();
myDirectoryCache.put(file, cached != null? cached : NULL_FILE_ARRAY);
}
return cached == NULL_FILE_ARRAY ? null : cached;
}
private boolean isFile(File root) {
Boolean cachedIsFile = myIsFile.get(root);
if (cachedIsFile == null) {
cachedIsFile = Boolean.valueOf(root.isFile());
myIsFile.put(root, cachedIsFile);
}
return cachedIsFile.booleanValue();
}
private static boolean contains(RelativePath.RelativeDirectory subdirectory, RelativePath.RelativeDirectory other) {
final String subdirPath = subdirectory.getPath();
final String otherPath = other.getPath();
return otherPath.length() > subdirPath.length() && otherPath.startsWith(subdirPath);
}
private static boolean isValidFile(String name, Set<JavaFileObject.Kind> fileKinds) {
return fileKinds.contains(getKind(name));
}
private class InputFileObject extends BaseFileObject {
private String name;
final File file;
private Reference<File> absFileRef;
public InputFileObject(JavacFileManager fileManager, File f) {
this(fileManager, f.getName(), f);
}
public InputFileObject(JavacFileManager fileManager, String name, File f) {
super(fileManager);
this.name = name;
this.file = f;
}
@Override
public URI toUri() {
return file.toURI().normalize();
}
@Override
public String getName() {
return file.getPath();
}
@Override
public String getShortName() {
return name;
}
@Override
public JavaFileObject.Kind getKind() {
return getKind(name);
}
@Override
public InputStream openInputStream() throws IOException {
return new FileInputStream(file);
}
@Override
public OutputStream openOutputStream() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public Writer openWriter() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public long getLastModified() {
return file.lastModified();
}
@Override
public boolean delete() {
return file.delete();
}
@Override
protected CharsetDecoder getDecoder(boolean ignoreEncodingErrors) {
return fileManager.getDecoder(fileManager.getEncodingName(), ignoreEncodingErrors);
}
@Override
protected String inferBinaryName(Iterable<? extends File> path) {
String fPath = file.getPath();
//System.err.println("RegularFileObject " + file + " " +r.getPath());
for (File dir: path) {
//System.err.println("dir: " + dir);
String dPath = dir.getPath();
if (dPath.length() == 0)
dPath = System.getProperty("user.dir");
if (!dPath.endsWith(File.separator))
dPath += File.separator;
if (fPath.regionMatches(true, 0, dPath, 0, dPath.length())
&& new File(fPath.substring(0, dPath.length())).equals(new File(dPath))) {
String relativeName = fPath.substring(dPath.length());
return removeExtension(relativeName).replace(File.separatorChar, '.');
}
}
return null;
}
@Override
public boolean isNameCompatible(String cn, JavaFileObject.Kind kind) {
cn.getClass();
// null check
if (kind == Kind.OTHER && getKind() != kind) {
return false;
}
String n = cn + kind.extension;
if (name.equals(n)) {
return true;
}
if (name.equalsIgnoreCase(n)) {
return file.getName().equals(n);
}
return false;
}
/**
* Check if two file objects are equal.
* Two RegularFileObjects are equal if the absolute paths of the underlying
* files are equal.
*/
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (!(other instanceof InputFileObject))
return false;
InputFileObject o = (InputFileObject) other;
return getAbsoluteFile().equals(o.getAbsoluteFile());
}
@Override
public int hashCode() {
return getAbsoluteFile().hashCode();
}
private File getAbsoluteFile() {
File absFile = (absFileRef == null ? null : absFileRef.get());
if (absFile == null) {
absFile = file.getAbsoluteFile();
absFileRef = new SoftReference<File>(absFile);
}
return absFile;
}
public CharBuffer getCharContent(boolean ignoreEncodingErrors) throws IOException {
CharBuffer cb = fileManager.getCachedContent(this);
if (cb == null) {
InputStream in = new FileInputStream(file);
try {
ByteBuffer bb = fileManager.makeByteBuffer(in);
JavaFileObject prev = fileManager.log.useSource(this);
try {
cb = fileManager.decode(bb, ignoreEncodingErrors);
} finally {
fileManager.log.useSource(prev);
}
fileManager.recycleByteBuffer(bb);
if (!ignoreEncodingErrors) {
fileManager.cache(this, cb);
}
} finally {
in.close();
}
}
return cb;
}
}
}
@@ -33,12 +33,11 @@ import org.jetbrains.asm4.ClassWriter;
import org.jetbrains.jps.MacroExpander;
import org.jetbrains.jps.javac.JavacServer;
import javax.tools.*;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.*;
/**
* @author Eugene Zhuravlev
@@ -114,6 +113,14 @@ public class ClasspathBootstrap {
catch (Throwable ignored) {
}
for (JavaCompiler javaCompiler : ServiceLoader.load(JavaCompiler.class)) { // Eclipse compiler
final File compilerResource = getResourcePath(javaCompiler.getClass());
final String name = compilerResource.getName();
if (name.startsWith("ecj-") && name.endsWith(".jar")) {
cp.add(compilerResource);
}
}
return new ArrayList<File>(cp);
}
Binary file not shown.
Binary file not shown.
@@ -4,6 +4,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.library.JpsLibrary;
import org.jetbrains.jps.model.library.JpsLibraryReference;
import org.jetbrains.jps.model.library.JpsLibraryType;
import org.jetbrains.jps.model.library.JpsSdkType;
import org.jetbrains.jps.model.module.JpsModule;
import org.jetbrains.jps.model.module.JpsModuleReference;
import org.jetbrains.jps.model.module.JpsModuleType;
@@ -28,6 +29,9 @@ public abstract class JpsElementFactory {
public abstract JpsLibraryReference createLibraryReference(@NotNull String libraryName,
@NotNull JpsElementReference<? extends JpsCompositeElement> parentReference);
@NotNull
public abstract JpsLibraryReference createSdkReference(@NotNull String sdkName, @NotNull JpsSdkType<?> sdkType);
@NotNull
public abstract JpsElementReference<JpsProject> createProjectReference();
@@ -6,6 +6,7 @@ import org.jetbrains.jps.model.library.JpsLibraryCollection;
import org.jetbrains.jps.model.library.JpsLibraryType;
import org.jetbrains.jps.model.module.JpsModule;
import org.jetbrains.jps.model.module.JpsModuleType;
import org.jetbrains.jps.model.module.JpsSdkReferencesTable;
import java.util.List;
@@ -28,4 +29,7 @@ public interface JpsProject extends JpsCompositeElement, JpsReferenceableElement
@NotNull
JpsLibraryCollection getLibraryCollection();
@NotNull
JpsSdkReferencesTable getSdkReferencesTable();
}
@@ -24,4 +24,7 @@ public interface JpsLibrary extends JpsNamedElement, JpsReferenceableElement<Jps
@NotNull
JpsLibraryReference createReference();
@NotNull
JpsLibraryType<?> getType();
}
@@ -5,8 +5,10 @@ import org.jetbrains.jps.model.*;
import org.jetbrains.jps.model.library.JpsLibrary;
import org.jetbrains.jps.model.library.JpsLibraryReference;
import org.jetbrains.jps.model.library.JpsLibraryType;
import org.jetbrains.jps.model.library.JpsSdkType;
import org.jetbrains.jps.model.library.impl.JpsLibraryImpl;
import org.jetbrains.jps.model.library.impl.JpsLibraryReferenceImpl;
import org.jetbrains.jps.model.library.impl.JpsSdkReferenceImpl;
import org.jetbrains.jps.model.module.JpsModule;
import org.jetbrains.jps.model.module.JpsModuleReference;
import org.jetbrains.jps.model.module.JpsModuleType;
@@ -41,6 +43,12 @@ public class JpsElementFactoryImpl extends JpsElementFactory {
return new JpsLibraryReferenceImpl(libraryName, parentReference);
}
@NotNull
@Override
public JpsLibraryReference createSdkReference(@NotNull String sdkName, @NotNull JpsSdkType<?> sdkType) {
return new JpsSdkReferenceImpl(sdkName, sdkType, createGlobalReference());
}
@NotNull
@Override
public JpsElementReference<JpsProject> createProjectReference() {
@@ -37,13 +37,17 @@ public abstract class JpsNamedElementReferenceBase<T extends JpsNamedElement, Se
final List<? extends T> elements = parent.getContainer().getChild(myCollectionKind).getElements();
for (T element : elements) {
if (element.getName().equals(myElementName)) {
if (resolvesTo(element)) {
return element;
}
}
return null;
}
protected boolean resolvesTo(T element) {
return element.getName().equals(myElementName);
}
public JpsElementReference<? extends JpsCompositeElement> getParentReference() {
return myContainer.getChild(PARENT_REFERENCE_KIND);
}
@@ -12,8 +12,10 @@ import org.jetbrains.jps.model.library.impl.JpsLibraryCollectionImpl;
import org.jetbrains.jps.model.library.impl.JpsLibraryKind;
import org.jetbrains.jps.model.module.JpsModule;
import org.jetbrains.jps.model.module.JpsModuleType;
import org.jetbrains.jps.model.module.JpsSdkReferencesTable;
import org.jetbrains.jps.model.module.impl.JpsModuleImpl;
import org.jetbrains.jps.model.module.impl.JpsModuleKind;
import org.jetbrains.jps.model.module.impl.JpsSdkReferencesTableImpl;
import java.util.List;
@@ -29,6 +31,7 @@ public class JpsProjectImpl extends JpsRootElementBase<JpsProjectImpl> implement
super(model, eventDispatcher);
myContainer.setChild(JpsModuleKind.MODULE_COLLECTION_KIND);
myContainer.setChild(EXTERNAL_REFERENCES_COLLECTION_KIND);
myContainer.setChild(JpsSdkReferencesTableImpl.KIND);
myLibraryCollection = new JpsLibraryCollectionImpl(myContainer.setChild(JpsLibraryKind.LIBRARIES_COLLECTION_KIND));
}
@@ -71,6 +74,12 @@ public class JpsProjectImpl extends JpsRootElementBase<JpsProjectImpl> implement
return myLibraryCollection;
}
@Override
@NotNull
public JpsSdkReferencesTable getSdkReferencesTable() {
return myContainer.getChild(JpsSdkReferencesTableImpl.KIND);
}
@NotNull
@Override
public JpsElementReference<JpsProject> createReference() {
@@ -25,6 +25,12 @@ public class JpsLibraryImpl extends JpsNamedCompositeElementBase<JpsLibraryImpl,
super(original);
}
@Override
@NotNull
public JpsLibraryType<?> getType() {
return myContainer.getChild(TYPED_DATA_KIND).getType();
}
@NotNull
@Override
public List<JpsLibraryRoot> getRoots(@NotNull JpsOrderRootType rootType) {
@@ -0,0 +1,50 @@
package org.jetbrains.jps.model.library.impl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.JpsCompositeElement;
import org.jetbrains.jps.model.JpsElementReference;
import org.jetbrains.jps.model.JpsModel;
import org.jetbrains.jps.model.impl.JpsNamedElementReferenceBase;
import org.jetbrains.jps.model.library.JpsLibrary;
import org.jetbrains.jps.model.library.JpsLibraryReference;
import org.jetbrains.jps.model.library.JpsSdkType;
/**
* @author nik
*/
public class JpsSdkReferenceImpl extends JpsNamedElementReferenceBase<JpsLibrary, JpsSdkReferenceImpl> implements JpsLibraryReference {
@NotNull private final JpsSdkType<?> mySdkType;
public JpsSdkReferenceImpl(@NotNull String elementName, @NotNull JpsSdkType<?> sdkType, @NotNull JpsElementReference<? extends JpsCompositeElement> parentReference) {
super(JpsLibraryKind.LIBRARIES_COLLECTION_KIND, elementName, parentReference);
mySdkType = sdkType;
}
public JpsSdkReferenceImpl(JpsSdkReferenceImpl original) {
super(original);
mySdkType = original.mySdkType;
}
@NotNull
@Override
public String getLibraryName() {
return myElementName;
}
@Override
protected boolean resolvesTo(JpsLibrary element) {
return super.resolvesTo(element) && element.getType().equals(mySdkType);
}
@NotNull
@Override
public JpsSdkReferenceImpl createCopy() {
return new JpsSdkReferenceImpl(this);
}
@Override
public JpsLibraryReference asExternal(@NotNull JpsModel model) {
model.registerExternalReference(this);
return this;
}
}
@@ -1,10 +1,8 @@
package org.jetbrains.jps.model.module.impl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.JpsElementCollection;
import org.jetbrains.jps.model.JpsElementKind;
import org.jetbrains.jps.model.JpsElementProperties;
import org.jetbrains.jps.model.JpsUrlList;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.*;
import org.jetbrains.jps.model.impl.*;
import org.jetbrains.jps.model.library.JpsLibrary;
import org.jetbrains.jps.model.library.JpsLibraryCollection;
@@ -34,7 +32,7 @@ public class JpsModuleImpl extends JpsNamedCompositeElementBase<JpsModuleImpl, J
myContainer.setChild(DEPENDENCIES_LIST_KIND, new JpsDependenciesListImpl());
myLibraryCollection = new JpsLibraryCollectionImpl(myContainer.setChild(JpsLibraryKind.LIBRARIES_COLLECTION_KIND));
myContainer.setChild(JpsModuleSourceRootKind.ROOT_COLLECTION_KIND);
myContainer.setChild(JpsSdkReferencesTableImpl.KIND, new JpsSdkReferencesTableImpl());
myContainer.setChild(JpsSdkReferencesTableImpl.KIND);
}
private JpsModuleImpl(JpsModuleImpl original) {
@@ -134,4 +132,10 @@ public class JpsModuleImpl extends JpsNamedCompositeElementBase<JpsModuleImpl, J
public JpsLibraryCollection getLibraryCollection() {
return myLibraryCollection;
}
@Nullable
public JpsProject getProject() {
JpsModel model = getModel();
return model != null ? model.getProject() : null;
}
}
@@ -2,6 +2,7 @@ package org.jetbrains.jps.model.module.impl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.JpsProject;
import org.jetbrains.jps.model.library.JpsLibrary;
import org.jetbrains.jps.model.library.JpsLibraryReference;
import org.jetbrains.jps.model.library.JpsSdkType;
@@ -44,7 +45,16 @@ public class JpsSdkDependencyImpl extends JpsDependencyElementBase<JpsSdkDepende
@Override
@Nullable
public JpsLibraryReference getSdkReference() {
return getDependenciesList().getParent().getSdkReferencesTable().getSdkReference(mySdkType);
JpsModuleImpl module = getDependenciesList().getParent();
JpsLibraryReference sdkReference = module.getSdkReferencesTable().getSdkReference(mySdkType);
if (sdkReference != null) {
return sdkReference;
}
JpsProject project = module.getProject();
if (project != null) {
return project.getSdkReferencesTable().getSdkReference(mySdkType);
}
return null;
}
@Override
@@ -1,9 +1,9 @@
package org.jetbrains.jps.model.module.impl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.JpsElementKind;
import org.jetbrains.jps.model.impl.JpsElementKindBase;
import org.jetbrains.jps.model.JpsElementCreator;
import org.jetbrains.jps.model.impl.JpsCompositeElementBase;
import org.jetbrains.jps.model.impl.JpsElementKindBase;
import org.jetbrains.jps.model.library.JpsLibraryReference;
import org.jetbrains.jps.model.library.JpsSdkType;
import org.jetbrains.jps.model.module.JpsSdkReferencesTable;
@@ -12,7 +12,7 @@ import org.jetbrains.jps.model.module.JpsSdkReferencesTable;
* @author nik
*/
public class JpsSdkReferencesTableImpl extends JpsCompositeElementBase<JpsSdkReferencesTableImpl> implements JpsSdkReferencesTable {
public static final JpsElementKind<JpsSdkReferencesTableImpl> KIND = new JpsElementKindBase<JpsSdkReferencesTableImpl>("sdk references");
public static final JpsSdkReferencesTableKind KIND = new JpsSdkReferencesTableKind();
public JpsSdkReferencesTableImpl() {
super();
@@ -56,4 +56,16 @@ public class JpsSdkReferencesTableImpl extends JpsCompositeElementBase<JpsSdkRef
return obj instanceof JpsSdkReferenceKind && myType.equals(((JpsSdkReferenceKind)obj).myType);
}
}
private static class JpsSdkReferencesTableKind extends JpsElementKindBase<JpsSdkReferencesTable> implements JpsElementCreator<JpsSdkReferencesTable> {
public JpsSdkReferencesTableKind() {
super("sdk references");
}
@NotNull
@Override
public JpsSdkReferencesTable create() {
return new JpsSdkReferencesTableImpl();
}
}
}
@@ -31,7 +31,10 @@ public class JpsLibraryTableLoader {
}
public static JpsLibrary loadLibrary(Element libraryElement) {
String name = libraryElement.getAttributeValue("name");
return loadLibrary(libraryElement, libraryElement.getAttributeValue("name"));
}
public static JpsLibrary loadLibrary(Element libraryElement, String name) {
String typeId = libraryElement.getAttributeValue("type");
JpsLibrary library = JpsElementFactory.getInstance().createLibrary(name, getLibraryType(typeId));
@@ -1,5 +1,6 @@
package org.jetbrains.jps.model.serialization;
import com.intellij.openapi.util.text.StringUtil;
import org.jdom.Element;
import org.jetbrains.jps.model.JpsCompositeElement;
import org.jetbrains.jps.model.JpsElementFactory;
@@ -24,7 +25,7 @@ public class JpsModuleLoader {
module.getContentRootsList().addUrl(url);
for (Element sourceElement : getChildren(contentElement, "sourceFolder")) {
final String sourceUrl = sourceElement.getAttributeValue(URL_ATTRIBUTE);
final String packagePrefix = sourceElement.getAttributeValue("packagePrefix");
final String packagePrefix = StringUtil.notNullize(sourceElement.getAttributeValue("packagePrefix"));
final boolean testSource = Boolean.parseBoolean(sourceElement.getAttributeValue("isTestSource"));
final JavaSourceRootType rootType = testSource ? JavaSourceRootType.SOURCE : JavaSourceRootType.TEST_SOURCE;
module.addSourceRoot(rootType, sourceUrl, new JavaSourceRootProperties(packagePrefix));
@@ -47,8 +48,7 @@ public class JpsModuleLoader {
String sdkTypeId = orderEntry.getAttributeValue("jskType");
final JpsSdkType<?> sdkType = getSdkType(sdkTypeId);
dependenciesList.addSdkDependency(sdkType);
module.getSdkReferencesTable()
.setSdkReference(sdkType, elementFactory.createLibraryReference(sdkName, elementFactory.createGlobalReference()));
module.getSdkReferencesTable().setSdkReference(sdkType, elementFactory.createSdkReference(sdkName, sdkType));
}
else if ("inheritedJdk".equals(type)) {
dependenciesList.addSdkDependency(JpsJavaSdkType.INSTANCE);
@@ -62,7 +62,11 @@ public class JpsModuleLoader {
}
else if ("module-library".equals(type)) {
final Element moduleLibraryElement = orderEntry.getChild("library");
final JpsLibrary library = JpsLibraryTableLoader.loadLibrary(moduleLibraryElement);
String name = moduleLibraryElement.getAttributeValue("name");
if (name == null) {
name = "#" + (moduleLibraryNum++);
}
final JpsLibrary library = JpsLibraryTableLoader.loadLibrary(moduleLibraryElement, name);
module.addModuleLibrary(library);
final JpsLibraryDependency dependency = dependenciesList.addLibraryDependency(library);
@@ -13,6 +13,7 @@ import org.jetbrains.jps.model.JpsGlobal;
import org.jetbrains.jps.model.JpsProject;
import org.jetbrains.jps.model.java.JpsJavaModuleType;
import org.jetbrains.jps.model.library.JpsLibrary;
import org.jetbrains.jps.model.library.JpsSdkType;
import org.jetbrains.jps.model.module.JpsModule;
import org.jetbrains.jps.model.module.JpsModuleType;
@@ -58,6 +59,7 @@ public class JpsProjectLoader {
private void loadFromDirectory(File dir) {
initMacroMap(dir.getParentFile());
loadProjectRoot(loadRootElement(new File(dir, "misc.xml")));
loadModules(loadRootElement(new File(dir, "modules.xml")));
final File[] libraryFiles = new File(dir, "libraries").listFiles();
if (libraryFiles != null) {
@@ -72,10 +74,23 @@ public class JpsProjectLoader {
private void loadFromIpr(File iprFile) {
initMacroMap(iprFile.getParentFile());
final Element root = loadRootElement(iprFile);
loadProjectRoot(root);
loadModules(root);
loadProjectLibraries(findComponent(root, "libraryTable"));
}
private void loadProjectRoot(Element root) {
Element rootManagerElement = findComponent(root, "ProjectRootManager");
if (rootManagerElement != null) {
String sdkName = rootManagerElement.getAttributeValue("project-jdk-name");
String sdkTypeId = rootManagerElement.getAttributeValue("project-jdk-type");
if (sdkName != null && sdkTypeId != null) {
JpsSdkType<?> sdkType = JpsModuleLoader.getSdkType(sdkTypeId);
myProject.getSdkReferencesTable().setSdkReference(sdkType, JpsElementFactory.getInstance().createSdkReference(sdkName, sdkType));
}
}
}
private void initMacroMap(File projectBaseDir) {
myMacroToPathMap = new ExpandMacroToPathMap();
myMacroToPathMap.addMacroExpand("PROJECT_DIR", FileUtil.toSystemIndependentName(projectBaseDir.getAbsolutePath()));
@@ -2,10 +2,12 @@ package org.jetbrains.jps.model.serialization;
import com.intellij.openapi.application.PathManager;
import org.jetbrains.jps.model.JpsModelTestCase;
import org.jetbrains.jps.model.java.JpsJavaSdkType;
import org.jetbrains.jps.model.library.JpsLibrary;
import org.jetbrains.jps.model.module.JpsModule;
import org.jetbrains.jps.model.module.*;
import java.io.IOException;
import java.util.List;
/**
* @author nik
@@ -15,8 +17,17 @@ public class JpsModuleSerializationTest extends JpsModelTestCase {
loadProject("iprProject/iprProject.ipr");
final JpsModule module = assertOneElement(myModel.getProject().getModules());
assertEquals("iprProject", module.getName());
final JpsLibrary library = assertOneElement(myModel.getProject().getLibraryCollection().getLibraries());
assertEquals("junit", library.getName());
List<JpsDependencyElement> dependencies = module.getDependenciesList().getDependencies();
JpsSdkDependency sdkDependency = assertInstanceOf(dependencies.get(0), JpsSdkDependency.class);
assertSame(JpsJavaSdkType.INSTANCE, sdkDependency.getSdkType());
assertEquals("1.6", sdkDependency.getSdkReference().getLibraryName());
assertInstanceOf(dependencies.get(1), JpsModuleSourceDependency.class);
assertInstanceOf(dependencies.get(2), JpsLibraryDependency.class);
assertInstanceOf(dependencies.get(3), JpsLibraryDependency.class);
}
private void loadProject(final String path) {
@@ -7,7 +7,9 @@ class CompilerConfiguration {
List<String> resourcePatterns = []
List<String> resourceIncludePatterns = "properties,xml,gif,png,jpeg,jpg,jtml,dtd,tld,ftl".split(",").collect {"**/?*.$it"}
List<String> resourceExcludePatterns = []
Map<String, String> options = [:]
Map<String, String> javacOptions = [:]
Map<String, String> eclipseOptions = [:]
boolean clearOutputDirectoryOnRebuild = true
boolean addNotNullAssertions = true
AnnotationProcessingProfile defaultAnnotationProcessingProfile = new AnnotationProcessingProfile()
File diff suppressed because it is too large Load Diff
@@ -1,195 +1,204 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution.runners;
import com.intellij.execution.*;
import com.intellij.execution.configurations.ConfigurationPerRunnerSettings;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.configurations.RunProfileState;
import com.intellij.execution.configurations.RunnerSettings;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
public class ExecutionEnvironment {
@Nullable private final Project myProject;
@NotNull private RunProfile myRunProfile;
@NotNull private ExecutionTarget myTarget;
@Nullable private RunnerSettings myRunnerSettings;
@Nullable private ConfigurationPerRunnerSettings myConfigurationSettings;
@Nullable private RunnerAndConfigurationSettings myRunnerAndConfigurationSettings;
@Nullable private final RunContentDescriptor myContentToReuse;
@TestOnly
public ExecutionEnvironment() {
myProject = null;
myContentToReuse = null;
}
public ExecutionEnvironment(@NotNull final ProgramRunner runner,
@NotNull final RunnerAndConfigurationSettings configuration,
@Nullable Project project) {
this(runner, DefaultExecutionTarget.INSTANCE, configuration, project);
}
public ExecutionEnvironment(@NotNull final ProgramRunner runner,
@NotNull final ExecutionTarget target,
@NotNull final RunnerAndConfigurationSettings configuration,
Project project) {
this(configuration.getConfiguration(),
target,
project,
configuration.getRunnerSettings(runner),
configuration.getConfigurationSettings(runner),
null,
configuration);
}
public ExecutionEnvironment(@NotNull RunProfile runProfile,
@Nullable Project project,
@Nullable RunnerSettings runnerSettings,
@Nullable ConfigurationPerRunnerSettings configurationSettings,
@Nullable RunContentDescriptor contentToReuse) {
this(runProfile, project, runnerSettings, configurationSettings, contentToReuse, null);
}
public ExecutionEnvironment(@NotNull RunProfile runProfile,
@Nullable Project project,
@Nullable RunnerSettings runnerSettings,
@Nullable ConfigurationPerRunnerSettings configurationSettings,
@Nullable RunContentDescriptor contentToReuse,
@Nullable RunnerAndConfigurationSettings settings) {
this(runProfile, DefaultExecutionTarget.INSTANCE, project, runnerSettings, configurationSettings, contentToReuse, settings);
}
public ExecutionEnvironment(@NotNull RunProfile runProfile,
@NotNull ExecutionTarget target,
@Nullable Project project,
@Nullable RunnerSettings runnerSettings,
@Nullable ConfigurationPerRunnerSettings configurationSettings,
@Nullable RunContentDescriptor contentToReuse,
@Nullable RunnerAndConfigurationSettings settings) {
myTarget = target;
myRunProfile = runProfile;
myRunnerSettings = runnerSettings;
myConfigurationSettings = configurationSettings;
myProject = project;
myContentToReuse = contentToReuse;
myRunnerAndConfigurationSettings = settings;
}
/**
* @deprecated use {@link #ExecutionEnvironment(ProgramRunner, com.intellij.execution.RunnerAndConfigurationSettings, com.intellij.openapi.project.Project)}
*/
@Deprecated
public ExecutionEnvironment(@NotNull final ProgramRunner runner,
@NotNull final RunnerAndConfigurationSettings configuration,
@NotNull final DataContext context) {
this(configuration.getConfiguration(),
PlatformDataKeys.PROJECT.getData(context),
configuration.getRunnerSettings(runner),
configuration.getConfigurationSettings(runner),
null,
configuration);
}
/**
* @deprecated use {@link #ExecutionEnvironment(com.intellij.execution.configurations.RunProfile, com.intellij.openapi.project.Project, com.intellij.execution.configurations.RunnerSettings, com.intellij.execution.configurations.ConfigurationPerRunnerSettings, com.intellij.execution.ui.RunContentDescriptor)}
*/
@Deprecated
public ExecutionEnvironment(@NotNull final RunProfile profile,
@NotNull final DataContext dataContext) {
this(profile, PlatformDataKeys.PROJECT.getData(dataContext), null, null, null);
}
/**
* @deprecated use {@link #ExecutionEnvironment(com.intellij.execution.configurations.RunProfile, com.intellij.openapi.project.Project, com.intellij.execution.configurations.RunnerSettings, com.intellij.execution.configurations.ConfigurationPerRunnerSettings, com.intellij.execution.ui.RunContentDescriptor)}
*/
@Deprecated
public ExecutionEnvironment(@NotNull final RunProfile runProfile,
@Nullable final RunnerSettings runnerSettings,
@Nullable final ConfigurationPerRunnerSettings configurationSettings,
@NotNull final DataContext dataContext) {
this(runProfile, PlatformDataKeys.PROJECT.getData(dataContext), runnerSettings, configurationSettings, null);
}
@Nullable
public Project getProject() {
return myProject;
}
@NotNull
public ExecutionTarget getExecutionTarget() {
return myTarget;
}
@NotNull
public RunProfile getRunProfile() {
return myRunProfile;
}
@Nullable
public RunnerAndConfigurationSettings getRunnerAndConfigurationSettings() {
return myRunnerAndConfigurationSettings;
}
/**
* @deprecated use {@link #getProject()} and {@link #getContentToReuse()}
*/
@Deprecated
public DataContext getDataContext() {
return new DataContext() {
public Object getData(@NonNls String dataId) {
return PlatformDataKeys.PROJECT.is(dataId) ? myProject : null;
}
};
}
@Nullable
public RunContentDescriptor getContentToReuse() {
return myContentToReuse;
}
@Nullable
public String getRunnerId() {
return myConfigurationSettings == null ? null : myConfigurationSettings.getRunnerId();
}
@Nullable
public RunnerSettings getRunnerSettings() {
return myRunnerSettings;
}
@Nullable
public ConfigurationPerRunnerSettings getConfigurationSettings() {
return myConfigurationSettings;
}
@Nullable
public RunProfileState getState(final Executor executor) throws ExecutionException {
return myRunProfile.getState(executor, this);
}
}
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution.runners;
import com.intellij.execution.*;
import com.intellij.execution.configurations.ConfigurationPerRunnerSettings;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.configurations.RunProfileState;
import com.intellij.execution.configurations.RunnerSettings;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
public class ExecutionEnvironment {
@Nullable private final Project myProject;
@NotNull private RunProfile myRunProfile;
@NotNull private ExecutionTarget myTarget;
@Nullable private RunnerSettings myRunnerSettings;
@Nullable private ConfigurationPerRunnerSettings myConfigurationSettings;
@Nullable private RunnerAndConfigurationSettings myRunnerAndConfigurationSettings;
@Nullable private final RunContentDescriptor myContentToReuse;
@TestOnly
public ExecutionEnvironment() {
myProject = null;
myContentToReuse = null;
}
public ExecutionEnvironment(@NotNull final ProgramRunner runner,
@NotNull final RunnerAndConfigurationSettings configuration,
@Nullable Project project) {
this(runner, DefaultExecutionTarget.INSTANCE, configuration, project);
}
public ExecutionEnvironment(@NotNull final ProgramRunner runner,
@NotNull final ExecutionTarget target,
@NotNull final RunnerAndConfigurationSettings configuration,
Project project) {
this(configuration.getConfiguration(),
target,
project,
configuration.getRunnerSettings(runner),
configuration.getConfigurationSettings(runner),
null,
configuration);
}
public ExecutionEnvironment(@NotNull RunProfile runProfile,
@Nullable Project project,
@Nullable RunnerSettings runnerSettings,
@Nullable ConfigurationPerRunnerSettings configurationSettings,
@Nullable RunContentDescriptor contentToReuse) {
this(runProfile, project, runnerSettings, configurationSettings, contentToReuse, null);
}
public ExecutionEnvironment(@NotNull RunProfile runProfile,
@NotNull ExecutionTarget target,
@Nullable Project project,
@Nullable RunnerSettings runnerSettings,
@Nullable ConfigurationPerRunnerSettings configurationSettings,
@Nullable RunContentDescriptor contentToReuse) {
this(runProfile, target, project, runnerSettings, configurationSettings, contentToReuse, null);
}
public ExecutionEnvironment(@NotNull RunProfile runProfile,
@Nullable Project project,
@Nullable RunnerSettings runnerSettings,
@Nullable ConfigurationPerRunnerSettings configurationSettings,
@Nullable RunContentDescriptor contentToReuse,
@Nullable RunnerAndConfigurationSettings settings) {
this(runProfile, DefaultExecutionTarget.INSTANCE, project, runnerSettings, configurationSettings, contentToReuse, settings);
}
public ExecutionEnvironment(@NotNull RunProfile runProfile,
@NotNull ExecutionTarget target,
@Nullable Project project,
@Nullable RunnerSettings runnerSettings,
@Nullable ConfigurationPerRunnerSettings configurationSettings,
@Nullable RunContentDescriptor contentToReuse,
@Nullable RunnerAndConfigurationSettings settings) {
myTarget = target;
myRunProfile = runProfile;
myRunnerSettings = runnerSettings;
myConfigurationSettings = configurationSettings;
myProject = project;
myContentToReuse = contentToReuse;
myRunnerAndConfigurationSettings = settings;
}
/**
* @deprecated use {@link #ExecutionEnvironment(ProgramRunner, com.intellij.execution.RunnerAndConfigurationSettings, com.intellij.openapi.project.Project)}
*/
@Deprecated
public ExecutionEnvironment(@NotNull final ProgramRunner runner,
@NotNull final RunnerAndConfigurationSettings configuration,
@NotNull final DataContext context) {
this(configuration.getConfiguration(),
PlatformDataKeys.PROJECT.getData(context),
configuration.getRunnerSettings(runner),
configuration.getConfigurationSettings(runner),
null,
configuration);
}
/**
* @deprecated use {@link #ExecutionEnvironment(com.intellij.execution.configurations.RunProfile, com.intellij.openapi.project.Project, com.intellij.execution.configurations.RunnerSettings, com.intellij.execution.configurations.ConfigurationPerRunnerSettings, com.intellij.execution.ui.RunContentDescriptor)}
*/
@Deprecated
public ExecutionEnvironment(@NotNull final RunProfile profile,
@NotNull final DataContext dataContext) {
this(profile, PlatformDataKeys.PROJECT.getData(dataContext), null, null, null);
}
/**
* @deprecated use {@link #ExecutionEnvironment(com.intellij.execution.configurations.RunProfile, com.intellij.openapi.project.Project, com.intellij.execution.configurations.RunnerSettings, com.intellij.execution.configurations.ConfigurationPerRunnerSettings, com.intellij.execution.ui.RunContentDescriptor)}
*/
@Deprecated
public ExecutionEnvironment(@NotNull final RunProfile runProfile,
@Nullable final RunnerSettings runnerSettings,
@Nullable final ConfigurationPerRunnerSettings configurationSettings,
@NotNull final DataContext dataContext) {
this(runProfile, PlatformDataKeys.PROJECT.getData(dataContext), runnerSettings, configurationSettings, null);
}
@Nullable
public Project getProject() {
return myProject;
}
@NotNull
public ExecutionTarget getExecutionTarget() {
return myTarget;
}
@NotNull
public RunProfile getRunProfile() {
return myRunProfile;
}
@Nullable
public RunnerAndConfigurationSettings getRunnerAndConfigurationSettings() {
return myRunnerAndConfigurationSettings;
}
/**
* @deprecated use {@link #getProject()} and {@link #getContentToReuse()}
*/
@Deprecated
public DataContext getDataContext() {
return new DataContext() {
public Object getData(@NonNls String dataId) {
return PlatformDataKeys.PROJECT.is(dataId) ? myProject : null;
}
};
}
@Nullable
public RunContentDescriptor getContentToReuse() {
return myContentToReuse;
}
@Nullable
public String getRunnerId() {
return myConfigurationSettings == null ? null : myConfigurationSettings.getRunnerId();
}
@Nullable
public RunnerSettings getRunnerSettings() {
return myRunnerSettings;
}
@Nullable
public ConfigurationPerRunnerSettings getConfigurationSettings() {
return myConfigurationSettings;
}
@Nullable
public RunProfileState getState(final Executor executor) throws ExecutionException {
return myRunProfile.getState(executor, this);
}
}
@@ -1,160 +1,164 @@
package com.intellij.codeInsight.editorActions;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeStyle.CodeStyleFacade;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.actions.EditorActionUtil;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.util.text.CharArrayUtil;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
/**
* @author yole
*/
public class CopyPasteIndentProcessor implements CopyPastePostProcessor<IndentTransferableData> {
@Override
public IndentTransferableData collectTransferableData(PsiFile file,
Editor editor,
int[] startOffsets,
int[] endOffsets) {
if (!acceptFileType(file.getFileType())) {
return null;
}
if (startOffsets.length != 1) {
return null;
}
Document document = editor.getDocument();
int selStartLine = document.getLineNumber(startOffsets[0]);
int selEndLine = document.getLineNumber(endOffsets[0]);
//if (selStartLine == selEndLine) {
// return null;
//}
// check that selection starts at or before the first non-whitespace character on a line
for (int offset = startOffsets[0] - 1; offset >= document.getLineStartOffset(selStartLine); offset--) {
if (!Character.isWhitespace(document.getCharsSequence().charAt(offset))) {
return null;
}
}
int minIndent = Integer.MAX_VALUE;
int tabSize = CodeStyleFacade.getInstance(file.getProject()).getTabSize(file.getFileType());
for (int line = selStartLine; line <= selEndLine; line++) {
int start = document.getLineStartOffset(line);
int end = document.getLineEndOffset(line);
int indent = getIndent(document.getCharsSequence(), start, end, tabSize);
if (indent >= 0) {
minIndent = Math.min(minIndent, indent);
}
}
int firstNonSpaceChar = CharArrayUtil.shiftForward(document.getCharsSequence(), startOffsets[0], " \t");
int firstLineLeadingSpaces = (firstNonSpaceChar <= document.getLineEndOffset(selStartLine)) ? firstNonSpaceChar - startOffsets[0] : 0;
return new IndentTransferableData(minIndent, firstLineLeadingSpaces);
}
private static boolean acceptFileType(FileType fileType) {
for(PreserveIndentOnPasteBean bean: Extensions.getExtensions(PreserveIndentOnPasteBean.EP_NAME)) {
if (fileType.getName().equals(bean.fileType)) {
return true;
}
}
return false;
}
private static int getIndent(CharSequence chars, int start, int end, int tabSize) {
int result = 0;
boolean nonEmpty = false;
for(int i=start; i<end; i++) {
if (chars.charAt(i) == ' ') {
result++;
}
else if (chars.charAt(i) == '\t') {
result = ((result / tabSize) + 1) * tabSize;
}
else {
nonEmpty = true;
break;
}
}
return nonEmpty ? result : -1;
}
@Override
public IndentTransferableData extractTransferableData(Transferable content) {
IndentTransferableData indentData = null;
try {
final DataFlavor flavor = IndentTransferableData.getDataFlavorStatic();
if (flavor != null) {
final Object transferData = content.getTransferData(flavor);
if (transferData instanceof IndentTransferableData) {
indentData = (IndentTransferableData)transferData;
}
}
}
catch (UnsupportedFlavorException e) {
// do nothing
}
catch (IOException e) {
// do nothing
}
return indentData;
}
@Override
public void processTransferableData(final Project project,
final Editor editor,
final RangeMarker bounds,
final int caretColumn,
final Ref<Boolean> indented,
final IndentTransferableData value) {
if (!CodeInsightSettings.getInstance().INDENT_TO_CARET_ON_PASTE) {
return;
}
final Document document = editor.getDocument();
final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
if (psiFile == null || !acceptFileType(psiFile.getFileType())) {
return;
}
//System.out.println("--- before indent ---\n" + document.getText());
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
String pastedText = document.getText(TextRange.create(bounds));
int startLine = document.getLineNumber(bounds.getStartOffset());
int endLine = document.getLineNumber(bounds.getEndOffset());
if (!pastedText.trim().contains("\n") && startLine == endLine) {
// don't indent single-line text
return;
}
int startLineStart = document.getLineStartOffset(startLine);
// don't indent first line if there's any text before it
final String textBeforeFirstLine = document.getText(new TextRange(startLineStart, bounds.getStartOffset()));
if (textBeforeFirstLine.trim().length() == 0) {
EditorActionUtil.indentLine(project, editor, startLine, -value.getFirstLineLeadingSpaces());
}
if (caretColumn > value.getIndent()) endLine -=1;
for (int i = startLine+1; i <= endLine; i++) {
EditorActionUtil.indentLine(project, editor, i, value.getIndent());
}
indented.set(Boolean.TRUE);
}
});
//System.out.println("--- after indent ---\n" + document.getText());
}
}
package com.intellij.codeInsight.editorActions;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeStyle.CodeStyleFacade;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.actions.EditorActionUtil;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.util.text.CharArrayUtil;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.List;
/**
* @author yole
*/
public class CopyPasteIndentProcessor implements CopyPastePostProcessor<IndentTransferableData> {
@Override
public IndentTransferableData collectTransferableData(PsiFile file,
Editor editor,
int[] startOffsets,
int[] endOffsets) {
if (!acceptFileType(file.getFileType())) {
return null;
}
if (startOffsets.length != 1) {
return null;
}
Document document = editor.getDocument();
int selStartLine = document.getLineNumber(startOffsets[0]);
int selEndLine = document.getLineNumber(endOffsets[0]);
//if (selStartLine == selEndLine) {
// return null;
//}
// check that selection starts at or before the first non-whitespace character on a line
for (int offset = startOffsets[0] - 1; offset >= document.getLineStartOffset(selStartLine); offset--) {
if (!Character.isWhitespace(document.getCharsSequence().charAt(offset))) {
return null;
}
}
int minIndent = Integer.MAX_VALUE;
int tabSize = CodeStyleFacade.getInstance(file.getProject()).getTabSize(file.getFileType());
for (int line = selStartLine; line <= selEndLine; line++) {
int start = document.getLineStartOffset(line);
int end = document.getLineEndOffset(line);
int indent = getIndent(document.getCharsSequence(), start, end, tabSize);
if (indent >= 0) {
minIndent = Math.min(minIndent, indent);
}
}
int firstNonSpaceChar = CharArrayUtil.shiftForward(document.getCharsSequence(), startOffsets[0], " \t");
int firstLineLeadingSpaces = (firstNonSpaceChar <= document.getLineEndOffset(selStartLine)) ? firstNonSpaceChar - startOffsets[0] : 0;
return new IndentTransferableData(minIndent, firstLineLeadingSpaces);
}
private static boolean acceptFileType(FileType fileType) {
for(PreserveIndentOnPasteBean bean: Extensions.getExtensions(PreserveIndentOnPasteBean.EP_NAME)) {
if (fileType.getName().equals(bean.fileType)) {
return true;
}
}
return false;
}
private static int getIndent(CharSequence chars, int start, int end, int tabSize) {
int result = 0;
boolean nonEmpty = false;
for(int i=start; i<end; i++) {
if (chars.charAt(i) == ' ') {
result++;
}
else if (chars.charAt(i) == '\t') {
result = ((result / tabSize) + 1) * tabSize;
}
else {
nonEmpty = true;
break;
}
}
return nonEmpty ? result : -1;
}
@Override
public IndentTransferableData extractTransferableData(Transferable content) {
IndentTransferableData indentData = null;
try {
final DataFlavor flavor = IndentTransferableData.getDataFlavorStatic();
if (flavor != null) {
final Object transferData = content.getTransferData(flavor);
if (transferData instanceof IndentTransferableData) {
indentData = (IndentTransferableData)transferData;
}
}
}
catch (UnsupportedFlavorException e) {
// do nothing
}
catch (IOException e) {
// do nothing
}
return indentData;
}
@Override
public void processTransferableData(final Project project,
final Editor editor,
final RangeMarker bounds,
final int caretColumn,
final Ref<Boolean> indented,
final IndentTransferableData value) {
if (!CodeInsightSettings.getInstance().INDENT_TO_CARET_ON_PASTE) {
return;
}
final Document document = editor.getDocument();
final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
if (psiFile == null || !acceptFileType(psiFile.getFileType())) {
return;
}
//System.out.println("--- before indent ---\n" + document.getText());
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
String pastedText = document.getText(TextRange.create(bounds));
int startLine = document.getLineNumber(bounds.getStartOffset());
int endLine = document.getLineNumber(bounds.getEndOffset());
if (!pastedText.trim().contains("\n") && startLine == endLine) {
// don't indent single-line text
return;
}
int startLineStart = document.getLineStartOffset(startLine);
// don't indent first line if there's any text before it
final String textBeforeFirstLine = document.getText(new TextRange(startLineStart, bounds.getStartOffset()));
if (textBeforeFirstLine.trim().length() == 0) {
EditorActionUtil.indentLine(project, editor, startLine, -value.getFirstLineLeadingSpaces());
}
final List<String> strings = StringUtil.split(pastedText, "\n");
if (caretColumn > value.getIndent() && !strings.isEmpty() &&
StringUtil.isEmptyOrSpaces(strings.get(strings.size()-1))) endLine -=1;
for (int i = startLine+1; i <= endLine; i++) {
EditorActionUtil.indentLine(project, editor, i, value.getIndent());
}
indented.set(Boolean.TRUE);
}
});
//System.out.println("--- after indent ---\n" + document.getText());
}
}
@@ -397,7 +397,13 @@ public abstract class LogConsoleBase extends AdditionalTabComponent implements L
final Document document = editor.getDocument();
final int caretOffset = editor.getCaretModel().getOffset();
if (caretOffset > -1) {
int line = document.getLineNumber(caretOffset);
int line;
try {
line = document.getLineNumber(caretOffset);
}
catch (IllegalStateException e) {
throw new IllegalStateException("document.length=" + document.getTextLength() + ", caret offset = " + caretOffset + "; " + e.getMessage(), e);
}
if (line > -1 && line < document.getLineCount()) {
final int startOffset = document.getLineStartOffset(line);
myLineUnderSelection = document.getText().substring(startOffset, document.getLineEndOffset(line));
@@ -35,7 +35,7 @@ import java.util.Collection;
class AddToNewFavoritesListAction extends AnAction {
public AddToNewFavoritesListAction() {
super(IdeBundle.message("action.add.to.new.favorites.list"),
IdeBundle.message("action.add.to.new.favorites.list"), AllIcons.General.AddFavoritesList);
"Add To New Favorites List", AllIcons.General.AddFavoritesList);
}
public void actionPerformed(AnActionEvent e) {
@@ -82,7 +82,7 @@ public class IndexInfrastructure {
finally {
ourIndexIdToCreationStamp.clear();
os.close();
file.setLastModified(Math.max(System.currentTimeMillis(), prevLastModifiedValue + 1000));
file.setLastModified(Math.max(System.currentTimeMillis(), prevLastModifiedValue + 2000));
}
}
@@ -52,6 +52,8 @@ public class ComponentWithBrowseButton<Comp extends JComponent> extends JPanel i
public ComponentWithBrowseButton(Comp component, @Nullable ActionListener browseActionListener) {
super(new BorderLayout(SystemInfo.isMac? 0 : 2, 0));
myComponent = component;
// required! otherwise JPanel will occasionally gain focus instead of the component
setFocusable(false);
add(myComponent, BorderLayout.CENTER);
myBrowseButton=new FixedSizeButton(myComponent);
@@ -1,215 +1,217 @@
/*
* 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.featureStatistics.actions;
import com.intellij.CommonBundle;
import com.intellij.featureStatistics.*;
import com.intellij.ide.util.TipUIUtil;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.ui.VerticalFlowLayout;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.table.TableView;
import com.intellij.util.text.DateFormatUtil;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.ListTableModel;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
public class ShowFeatureUsageStatisticsDialog extends DialogWrapper {
private static final Logger LOG = Logger.getInstance("#com.intellij.featureStatistics.actions.ShowFeatureUsageStatisticsDialog");
private static final Comparator<FeatureDescriptor> DISPLAY_NAME_COMPARATOR = new Comparator<FeatureDescriptor>() {
public int compare(FeatureDescriptor fd1, FeatureDescriptor fd2) {
return fd1.getDisplayName().compareTo(fd2.getDisplayName());
}
};
private static final Comparator<FeatureDescriptor> GROUP_NAME_COMPARATOR = new Comparator<FeatureDescriptor>() {
public int compare(FeatureDescriptor fd1, FeatureDescriptor fd2) {
return getGroupName(fd1).compareTo(getGroupName(fd2));
}
};
private static final Comparator<FeatureDescriptor> USAGE_COUNT_COMPARATOR = new Comparator<FeatureDescriptor>() {
public int compare(FeatureDescriptor fd1, FeatureDescriptor fd2) {
return fd1.getUsageCount() - fd2.getUsageCount();
}
};
private static final Comparator<FeatureDescriptor> LAST_USED_COMPARATOR = new Comparator<FeatureDescriptor>() {
public int compare(FeatureDescriptor fd1, FeatureDescriptor fd2) {
return new Date(fd2.getLastTimeUsed()).compareTo(new Date(fd1.getLastTimeUsed()));
}
};
private static final ColumnInfo<FeatureDescriptor, String> DISPLAY_NAME = new ColumnInfo<FeatureDescriptor, String>(FeatureStatisticsBundle.message("feature.statistics.column.feature")) {
public String valueOf(FeatureDescriptor featureDescriptor) {
return featureDescriptor.getDisplayName();
}
public Comparator<FeatureDescriptor> getComparator() {
return DISPLAY_NAME_COMPARATOR;
}
};
private static final ColumnInfo<FeatureDescriptor, String> GROUP_NAME = new ColumnInfo<FeatureDescriptor, String>(FeatureStatisticsBundle.message("feature.statistics.column.group")) {
public String valueOf(FeatureDescriptor featureDescriptor) {
return getGroupName(featureDescriptor);
}
public Comparator<FeatureDescriptor> getComparator() {
return GROUP_NAME_COMPARATOR;
}
};
private static final ColumnInfo<FeatureDescriptor, String> USED_TOTAL = new ColumnInfo<FeatureDescriptor, String>(FeatureStatisticsBundle.message("feature.statistics.column.usage.count")) {
public String valueOf(FeatureDescriptor featureDescriptor) {
int count = featureDescriptor.getUsageCount();
return FeatureStatisticsBundle.message("feature.statistics.usage.count", count);
}
public Comparator<FeatureDescriptor> getComparator() {
return USAGE_COUNT_COMPARATOR;
}
};
private static final ColumnInfo<FeatureDescriptor, String> LAST_USED = new ColumnInfo<FeatureDescriptor, String>(FeatureStatisticsBundle.message("feature.statistics.column.last.used")) {
public String valueOf(FeatureDescriptor featureDescriptor) {
long tm = featureDescriptor.getLastTimeUsed();
if (tm <= 0) return FeatureStatisticsBundle.message("feature.statistics.not.applicable");
return DateFormatUtil.formatBetweenDates(tm, System.currentTimeMillis());
}
public Comparator<FeatureDescriptor> getComparator() {
return LAST_USED_COMPARATOR;
}
};
private static final ColumnInfo[] COLUMNS = new ColumnInfo[]{DISPLAY_NAME, GROUP_NAME, USED_TOTAL, LAST_USED};
public ShowFeatureUsageStatisticsDialog(Project project) {
super(project, true);
setTitle(FeatureStatisticsBundle.message("feature.statistics.dialog.title"));
setCancelButtonText(CommonBundle.getCloseButtonText());
setModal(false);
init();
}
protected String getDimensionServiceKey() {
return "#com.intellij.featureStatistics.actions.ShowFeatureUsageStatisticsDialog";
}
protected Action[] createActions() {
return new Action[] {getCancelAction(), getHelpAction()};
}
protected void doHelpAction() {
HelpManager.getInstance().invokeHelp("editing.productivityGuide");
}
protected JComponent createCenterPanel() {
Splitter splitter = new Splitter(true);
splitter.setShowDividerControls(true);
ProductivityFeaturesRegistry registry = ProductivityFeaturesRegistry.getInstance();
ArrayList<FeatureDescriptor> features = new ArrayList<FeatureDescriptor>();
for (String id : registry.getFeatureIds()) {
features.add(registry.getFeatureDescriptor(id));
}
final TableView table = new TableView<FeatureDescriptor>(new ListTableModel<FeatureDescriptor>(COLUMNS, features, 0));
JPanel controlsPanel = new JPanel(new VerticalFlowLayout());
Application app = ApplicationManager.getApplication();
long uptime = System.currentTimeMillis() - app.getStartTime();
long idleTime = app.getIdleTime();
final String uptimeS = FeatureStatisticsBundle.message("feature.statistics.application.uptime",
ApplicationNamesInfo.getInstance().getFullProductName(),
DateFormatUtil.formatDuration(uptime));
final String idleTimeS = FeatureStatisticsBundle.message("feature.statistics.application.idle.time",
DateFormatUtil.formatDuration(idleTime));
String labelText = uptimeS + ", " + idleTimeS;
CompletionStatistics stats = ((FeatureUsageTrackerImpl)FeatureUsageTracker.getInstance()).getCompletionStatistics();
if (stats.dayCount > 0 && stats.sparedCharacters > 0) {
String total = formatCharacterCount(stats.sparedCharacters, true);
String perDay = formatCharacterCount(stats.sparedCharacters / stats.dayCount, false);
labelText += "<br>Code completion has saved you from typing at least " + total + " since " + DateFormatUtil.formatDate(stats.startDate) +
" (\u2245" + perDay + " per working day)";
}
controlsPanel.add(new JLabel("<html><body>" + labelText + "</body></html>"), BorderLayout.NORTH);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(controlsPanel, BorderLayout.NORTH);
topPanel.add(ScrollPaneFactory.createScrollPane(table), BorderLayout.CENTER);
splitter.setFirstComponent(topPanel);
final JEditorPane browser = new JEditorPane(UIUtil.HTML_MIME, "");
browser.setEditable(false);
splitter.setSecondComponent(ScrollPaneFactory.createScrollPane(browser));
table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
Collection selection = table.getSelection();
try {
if (selection.isEmpty()) {
browser.read(new StringReader(""), null);
}
else {
FeatureDescriptor feature = (FeatureDescriptor)selection.iterator().next();
TipUIUtil.openTipInBrowser(feature.getTipFileName(), browser, feature.getProvider());
}
}
catch (IOException ex) {
LOG.info(ex);
}
}
});
return splitter;
}
private static String formatCharacterCount(int count, boolean full) {
String result = count > 1024 * 1024 ? (count / 1024 / 1024) + "M" :
count > 1024 ? (count / 1024) + "K" :
String.valueOf(count);
if (full) {
return result + " characters";
}
return result;
}
private static String getGroupName(FeatureDescriptor featureDescriptor) {
final ProductivityFeaturesRegistry registry = ProductivityFeaturesRegistry.getInstance();
final GroupDescriptor groupDescriptor = registry.getGroupDescriptor(featureDescriptor.getGroupId());
return groupDescriptor != null ? groupDescriptor.getDisplayName() : "";
}
}
/*
* 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.featureStatistics.actions;
import com.intellij.CommonBundle;
import com.intellij.featureStatistics.*;
import com.intellij.ide.util.TipUIUtil;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.ui.VerticalFlowLayout;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.table.TableView;
import com.intellij.util.text.DateFormatUtil;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.ListTableModel;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.io.IOException;
import java.io.StringReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
public class ShowFeatureUsageStatisticsDialog extends DialogWrapper {
private static final Logger LOG = Logger.getInstance("#com.intellij.featureStatistics.actions.ShowFeatureUsageStatisticsDialog");
private static final Comparator<FeatureDescriptor> DISPLAY_NAME_COMPARATOR = new Comparator<FeatureDescriptor>() {
public int compare(FeatureDescriptor fd1, FeatureDescriptor fd2) {
return fd1.getDisplayName().compareTo(fd2.getDisplayName());
}
};
private static final Comparator<FeatureDescriptor> GROUP_NAME_COMPARATOR = new Comparator<FeatureDescriptor>() {
public int compare(FeatureDescriptor fd1, FeatureDescriptor fd2) {
return getGroupName(fd1).compareTo(getGroupName(fd2));
}
};
private static final Comparator<FeatureDescriptor> USAGE_COUNT_COMPARATOR = new Comparator<FeatureDescriptor>() {
public int compare(FeatureDescriptor fd1, FeatureDescriptor fd2) {
return fd1.getUsageCount() - fd2.getUsageCount();
}
};
private static final Comparator<FeatureDescriptor> LAST_USED_COMPARATOR = new Comparator<FeatureDescriptor>() {
public int compare(FeatureDescriptor fd1, FeatureDescriptor fd2) {
return new Date(fd2.getLastTimeUsed()).compareTo(new Date(fd1.getLastTimeUsed()));
}
};
private static final ColumnInfo<FeatureDescriptor, String> DISPLAY_NAME = new ColumnInfo<FeatureDescriptor, String>(FeatureStatisticsBundle.message("feature.statistics.column.feature")) {
public String valueOf(FeatureDescriptor featureDescriptor) {
return featureDescriptor.getDisplayName();
}
public Comparator<FeatureDescriptor> getComparator() {
return DISPLAY_NAME_COMPARATOR;
}
};
private static final ColumnInfo<FeatureDescriptor, String> GROUP_NAME = new ColumnInfo<FeatureDescriptor, String>(FeatureStatisticsBundle.message("feature.statistics.column.group")) {
public String valueOf(FeatureDescriptor featureDescriptor) {
return getGroupName(featureDescriptor);
}
public Comparator<FeatureDescriptor> getComparator() {
return GROUP_NAME_COMPARATOR;
}
};
private static final ColumnInfo<FeatureDescriptor, String> USED_TOTAL = new ColumnInfo<FeatureDescriptor, String>(FeatureStatisticsBundle.message("feature.statistics.column.usage.count")) {
public String valueOf(FeatureDescriptor featureDescriptor) {
int count = featureDescriptor.getUsageCount();
return FeatureStatisticsBundle.message("feature.statistics.usage.count", count);
}
public Comparator<FeatureDescriptor> getComparator() {
return USAGE_COUNT_COMPARATOR;
}
};
private static final ColumnInfo<FeatureDescriptor, String> LAST_USED = new ColumnInfo<FeatureDescriptor, String>(FeatureStatisticsBundle.message("feature.statistics.column.last.used")) {
public String valueOf(FeatureDescriptor featureDescriptor) {
long tm = featureDescriptor.getLastTimeUsed();
if (tm <= 0) return FeatureStatisticsBundle.message("feature.statistics.not.applicable");
return DateFormatUtil.formatBetweenDates(tm, System.currentTimeMillis());
}
public Comparator<FeatureDescriptor> getComparator() {
return LAST_USED_COMPARATOR;
}
};
private static final ColumnInfo[] COLUMNS = new ColumnInfo[]{DISPLAY_NAME, GROUP_NAME, USED_TOTAL, LAST_USED};
public ShowFeatureUsageStatisticsDialog(Project project) {
super(project, true);
setTitle(FeatureStatisticsBundle.message("feature.statistics.dialog.title"));
setCancelButtonText(CommonBundle.getCloseButtonText());
setModal(false);
init();
}
protected String getDimensionServiceKey() {
return "#com.intellij.featureStatistics.actions.ShowFeatureUsageStatisticsDialog";
}
protected Action[] createActions() {
return new Action[] {getCancelAction(), getHelpAction()};
}
protected void doHelpAction() {
HelpManager.getInstance().invokeHelp("editing.productivityGuide");
}
protected JComponent createCenterPanel() {
Splitter splitter = new Splitter(true);
splitter.setShowDividerControls(true);
ProductivityFeaturesRegistry registry = ProductivityFeaturesRegistry.getInstance();
ArrayList<FeatureDescriptor> features = new ArrayList<FeatureDescriptor>();
for (String id : registry.getFeatureIds()) {
features.add(registry.getFeatureDescriptor(id));
}
final TableView table = new TableView<FeatureDescriptor>(new ListTableModel<FeatureDescriptor>(COLUMNS, features, 0));
JPanel controlsPanel = new JPanel(new VerticalFlowLayout());
Application app = ApplicationManager.getApplication();
long uptime = System.currentTimeMillis() - app.getStartTime();
long idleTime = app.getIdleTime();
final String uptimeS = FeatureStatisticsBundle.message("feature.statistics.application.uptime",
ApplicationNamesInfo.getInstance().getFullProductName(),
DateFormatUtil.formatDuration(uptime));
final String idleTimeS = FeatureStatisticsBundle.message("feature.statistics.application.idle.time",
DateFormatUtil.formatDuration(idleTime));
String labelText = uptimeS + ", " + idleTimeS;
CompletionStatistics stats = ((FeatureUsageTrackerImpl)FeatureUsageTracker.getInstance()).getCompletionStatistics();
if (stats.dayCount > 0 && stats.sparedCharacters > 0) {
String total = formatCharacterCount(stats.sparedCharacters, true);
String perDay = formatCharacterCount(stats.sparedCharacters / stats.dayCount, false);
labelText += "<br>Code completion has saved you from typing at least " + total + " since " + DateFormatUtil.formatDate(stats.startDate) +
" (\u2245" + perDay + " per working day)";
}
controlsPanel.add(new JLabel("<html><body>" + labelText + "</body></html>"), BorderLayout.NORTH);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(controlsPanel, BorderLayout.NORTH);
topPanel.add(ScrollPaneFactory.createScrollPane(table), BorderLayout.CENTER);
splitter.setFirstComponent(topPanel);
final JEditorPane browser = new JEditorPane(UIUtil.HTML_MIME, "");
browser.setEditable(false);
splitter.setSecondComponent(ScrollPaneFactory.createScrollPane(browser));
table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
Collection selection = table.getSelection();
try {
if (selection.isEmpty()) {
browser.read(new StringReader(""), null);
}
else {
FeatureDescriptor feature = (FeatureDescriptor)selection.iterator().next();
TipUIUtil.openTipInBrowser(feature.getTipFileName(), browser, feature.getProvider());
}
}
catch (IOException ex) {
LOG.info(ex);
}
}
});
return splitter;
}
private static String formatCharacterCount(int count, boolean full) {
DecimalFormat oneDigit = new DecimalFormat("0.0");
String result = count > 1024 * 1024 ? oneDigit.format((double)count / 1024 / 1024) + "M" :
count > 1024 ? oneDigit.format((double)count / 1024) + "K" :
String.valueOf(count);
if (full) {
return result + " characters";
}
return result;
}
private static String getGroupName(FeatureDescriptor featureDescriptor) {
final ProductivityFeaturesRegistry registry = ProductivityFeaturesRegistry.getInstance();
final GroupDescriptor groupDescriptor = registry.getGroupDescriptor(featureDescriptor.getGroupId());
return groupDescriptor != null ? groupDescriptor.getDisplayName() : "";
}
}
@@ -89,7 +89,7 @@ public class NotificationsManagerImpl extends NotificationsManager implements No
@Override
public <T extends Notification> T[] getNotificationsOfType(Class<T> klass, @Nullable final Project project) {
final List<T> result = new ArrayList<T>();
if (project == null || !project.isDefault()) {
if (project == null || !project.isDefault() && !project.isDisposed()) {
for (Notification notification : EventLog.getLogModel(project).getNotifications()) {
if (klass.isInstance(notification)) {
//noinspection unchecked
File diff suppressed because it is too large Load Diff
@@ -158,7 +158,7 @@ run.configuration.arguments.help.panel.copy.action.name=Copy
terminating.process.progress.title=Terminating ''{0}''
waiting.for.vm.detach.progress.text=Waiting for process detach
restart.error.message.title=Restart Error
rerun.configuration.action.name=Rerun {0}
rerun.configuration.action.name=Rerun ''{0}''
rerun.confirmation.message=Are you sure you want to stop ''{0}''
rerun.confirmation.title=Stop Confirmation
rerun.confirmation.checkbox=Confirm rerun with process termination
File diff suppressed because it is too large Load Diff
@@ -40,6 +40,7 @@ import java.io.*;
import java.lang.reflect.Method;
import java.nio.channels.FileChannel;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.Pattern;
@SuppressWarnings({"UtilityClassWithoutPrivateConstructor", "MethodOverridesStaticMethodOfSuperclass"})
@@ -289,15 +290,17 @@ public class FileUtil extends FileUtilRt {
return result;
}
public static void asyncDelete(@NotNull File file) {
@NotNull
public static Future<Void> asyncDelete(@NotNull File file) {
final File tempFile = renameToTempFileOrDelete(file);
if (tempFile == null) {
return;
return new CompletedFuture<Void>();
}
startDeletionThread(tempFile);
return startDeletionThread(tempFile);
}
public static void asyncDelete(@NotNull Collection<File> files) {
@NotNull
public static Future<Void> asyncDelete(@NotNull Collection<File> files) {
List<File> tempFiles = new ArrayList<File>();
for (File file : files) {
final File tempFile = renameToTempFileOrDelete(file);
@@ -306,12 +309,13 @@ public class FileUtil extends FileUtilRt {
}
}
if (!tempFiles.isEmpty()) {
startDeletionThread(tempFiles.toArray(new File[tempFiles.size()]));
return startDeletionThread(tempFiles.toArray(new File[tempFiles.size()]));
}
return new CompletedFuture<Void>();
}
private static void startDeletionThread(@NotNull final File... tempFiles) {
final Runnable deleteFilesTask = new Runnable() {
private static Future<Void> startDeletionThread(@NotNull final File... tempFiles) {
final RunnableFuture<Void> deleteFilesTask = new FutureTask<Void>(new Runnable() {
public void run() {
final Thread currentThread = Thread.currentThread();
final int priority = currentThread.getPriority();
@@ -325,7 +329,7 @@ public class FileUtil extends FileUtilRt {
currentThread.setPriority(priority);
}
}
};
}, null);
try {
// Attempt to execute on pooled thread
@@ -340,6 +344,7 @@ public class FileUtil extends FileUtilRt {
Thread t = new Thread(deleteFilesTask, "File deletion thread");
t.start();
}
return deleteFilesTask;
}
private static File renameToTempFileOrDelete(@NotNull File file) {
@@ -1279,4 +1284,22 @@ public class FileUtil extends FileUtilRt {
JAVA_IO_FILESYSTEM = fs;
JAVA_IO_FILESYSTEM_GET_BOOLEAN_ATTRIBUTES_METHOD = getBooleanAttributes;
}
private static final class CompletedFuture<T> implements Future<T> {
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
public boolean isCancelled() {
return false;
}
public boolean isDone() {
return true;
}
public T get() throws InterruptedException, ExecutionException {
return null;
}
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return null;
}
}
}
@@ -158,9 +158,7 @@ public class XDebuggerUtilImpl extends XDebuggerUtil {
if (editor == null) return null;
final Document document = editor.getDocument();
final int offset = editor.getCaretModel().getOffset();
int line = document.getLineNumber(offset);
final int line = editor.getCaretModel().getLogicalPosition().line;
VirtualFile file = FileDocumentManager.getInstance().getFile(document);
return XSourcePositionImpl.create(file, line);
}
@@ -1,99 +1,99 @@
/*
* 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.testAssistant;
import com.intellij.codeHighlighting.TextEditorHighlightingPass;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.impl.DocumentMarkupModel;
import com.intellij.openapi.editor.markup.*;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class TestDataHighlightingPass extends TextEditorHighlightingPass {
private static final Key<Object> KEY = Key.create("TestDataHighlighterKey");
private static final Object VALUE = new Object();
private static final Icon ICON = AllIcons.RunConfigurations.UnitTest;
private static final GutterIconRenderer ICON_RENDERER = new MyGutterIconRenderer();
private static final TextAttributes CARET_ATTRIBUTES = new TextAttributes(Color.BLUE, null, null, null, Font.BOLD);
private static final String CARET = "<caret>";
protected TestDataHighlightingPass(@NotNull final Project project, @Nullable final Document document) {
super(project, document);
}
@Override
public void doCollectInformation(@NotNull ProgressIndicator progress) {
}
@Override
public void doApplyInformationToEditor() {
removeHighlighters();
final MarkupModel model = DocumentMarkupModel.forDocument(myDocument, myProject, true);
final String text = myDocument.getText();
if (text != null) {
int ind = -1;
while ((ind = text.indexOf(CARET, ind + 1)) >= 0) {
final RangeHighlighter highlighter = model.addRangeHighlighter(ind,
ind + CARET.length(),
HighlighterLayer.ADDITIONAL_SYNTAX,
CARET_ATTRIBUTES,
HighlighterTargetArea.EXACT_RANGE);
highlighter.setGutterIconRenderer(ICON_RENDERER);
highlighter.putUserData(KEY, VALUE);
}
}
}
private void removeHighlighters() {
final MarkupModel model = DocumentMarkupModel.forDocument(myDocument, myProject, true);
for (RangeHighlighter highlighter : model.getAllHighlighters()) {
if (highlighter.getUserData(KEY) == VALUE) {
highlighter.dispose();
}
}
}
private static class MyGutterIconRenderer extends GutterIconRenderer {
@NotNull
@Override
public Icon getIcon() {
return ICON;
}
@Override
public boolean equals(Object obj) {
return obj instanceof MyGutterIconRenderer;
}
@Override
public int hashCode() {
return getIcon().hashCode();
}
}
}
/*
* 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.testAssistant;
import com.intellij.codeHighlighting.TextEditorHighlightingPass;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.impl.DocumentMarkupModel;
import com.intellij.openapi.editor.markup.*;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class TestDataHighlightingPass extends TextEditorHighlightingPass {
private static final Key<Object> KEY = Key.create("TestDataHighlighterKey");
private static final Object VALUE = new Object();
private static final Icon ICON = AllIcons.RunConfigurations.Junit;
private static final GutterIconRenderer ICON_RENDERER = new MyGutterIconRenderer();
private static final TextAttributes CARET_ATTRIBUTES = new TextAttributes(Color.BLUE, null, null, null, Font.BOLD);
private static final String CARET = "<caret>";
protected TestDataHighlightingPass(@NotNull final Project project, @Nullable final Document document) {
super(project, document);
}
@Override
public void doCollectInformation(@NotNull ProgressIndicator progress) {
}
@Override
public void doApplyInformationToEditor() {
removeHighlighters();
final MarkupModel model = DocumentMarkupModel.forDocument(myDocument, myProject, true);
final String text = myDocument.getText();
if (text != null) {
int ind = -1;
while ((ind = text.indexOf(CARET, ind + 1)) >= 0) {
final RangeHighlighter highlighter = model.addRangeHighlighter(ind,
ind + CARET.length(),
HighlighterLayer.ADDITIONAL_SYNTAX,
CARET_ATTRIBUTES,
HighlighterTargetArea.EXACT_RANGE);
highlighter.setGutterIconRenderer(ICON_RENDERER);
highlighter.putUserData(KEY, VALUE);
}
}
}
private void removeHighlighters() {
final MarkupModel model = DocumentMarkupModel.forDocument(myDocument, myProject, true);
for (RangeHighlighter highlighter : model.getAllHighlighters()) {
if (highlighter.getUserData(KEY) == VALUE) {
highlighter.dispose();
}
}
}
private static class MyGutterIconRenderer extends GutterIconRenderer {
@NotNull
@Override
public Icon getIcon() {
return ICON;
}
@Override
public boolean equals(Object obj) {
return obj instanceof MyGutterIconRenderer;
}
@Override
public int hashCode() {
return getIcon().hashCode();
}
}
}
@@ -15,6 +15,7 @@
*/
package com.siyeh.ig;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
@@ -173,6 +174,12 @@ public abstract class BaseInspectionVisitor extends JavaElementVisitor {
protected final void registerError(@NotNull PsiElement location,
Object... infos) {
registerError(location, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, infos);
}
protected final void registerError(@NotNull PsiElement location,
final ProblemHighlightType highlightType,
Object... infos) {
if (location.getTextLength() == 0 && !(location instanceof PsiFile)) {
return;
}
@@ -181,7 +188,7 @@ public abstract class BaseInspectionVisitor extends JavaElementVisitor {
fix.setOnTheFly(onTheFly);
}
final String description = inspection.buildErrorString(infos);
holder.registerProblem(location, description, fixes);
holder.registerProblem(location, description, highlightType, fixes);
}
protected final void registerErrorAtOffset(@NotNull PsiElement location,
@@ -16,6 +16,7 @@
package com.siyeh.ig.style;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
@@ -122,7 +123,7 @@ public class RedundantFieldInitializationInspection extends BaseInspection {
!text.equals(PsiKeyword.NULL)) {
return;
}
registerError(initializer);
registerError(initializer, ProblemHighlightType.LIKE_UNUSED_SYMBOL);
}
}
}
@@ -16,6 +16,7 @@
package com.siyeh.ig.style;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
@@ -159,7 +160,7 @@ public class UnnecessarilyQualifiedInnerClassAccessInspection
if (!isReferenceToTarget(shortName, aClass, reference)) {
return;
}
registerError(qualifier, aClass);
registerError(qualifier, ProblemHighlightType.LIKE_UNUSED_SYMBOL, aClass);
}
@Override
@@ -182,7 +182,7 @@ public class UnnecessarilyQualifiedStaticUsageInspection
PsiClass.class);
final PsiClass qualifyingClass = (PsiClass)resolvedQualifier;
if (containingClass == null ||
!containingClass.equals(qualifyingClass)) {
!PsiTreeUtil.isAncestor(qualifyingClass, containingClass, false)) {
return false;
}
final Project project = referenceElement.getProject();
@@ -16,6 +16,7 @@
package com.siyeh.ig.style;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.infos.CandidateInfo;
@@ -117,7 +118,7 @@ public class UnnecessarilyQualifiedStaticallyImportedElementInspection
if (!isReferenceCorrectWithoutQualifier(reference, member)) {
return;
}
registerError(qualifier, member);
registerError(qualifier, ProblemHighlightType.LIKE_UNUSED_SYMBOL, member);
}
private static boolean isReferenceCorrectWithoutQualifier(
@@ -16,6 +16,7 @@
package com.siyeh.ig.style;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
@@ -91,7 +92,7 @@ public class UnnecessaryQualifierForThisInspection
if (!containingClass.equals(referent)) {
return;
}
registerError(qualifier);
registerError(qualifier, ProblemHighlightType.LIKE_UNUSED_SYMBOL);
}
}
}
@@ -16,6 +16,7 @@
package com.siyeh.ig.style;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
@@ -89,7 +90,7 @@ public class UnnecessarySuperConstructorInspection
if (args.length != 0) {
return;
}
registerError(call);
registerError(call, ProblemHighlightType.LIKE_UNUSED_SYMBOL);
}
}
}
@@ -16,6 +16,7 @@
package com.siyeh.ig.style;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
@@ -103,7 +104,7 @@ public class UnnecessarySuperQualifierInspection extends BaseInspection {
return;
}
}
registerError(expression);
registerError(expression, ProblemHighlightType.LIKE_UNUSED_SYMBOL);
}
private static boolean hasUnnecessarySuperQualifier(
@@ -65,4 +65,19 @@ class X {
l.add("b");
l.add("c");
}
}
class InnerClassTest {
public static int foo = 0;
public static void bar() {
System.out.println();
}
public static class Inner {
public void test1() {
InnerClassTest.bar(); // (1)
System.out.println(InnerClassTest.foo); // (2)
}
}
}
@@ -36,6 +36,20 @@
<line>64</line>
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Unnecessarily qualified static access</problem_class>
<description>Unnecessarily qualified static access &lt;code&gt;X.l&lt;/code&gt; #loc</description>
</problem>
<problem>
<file>UnnecessarilyQualifiedStaticUsageInspection.java</file>
<line>79</line>
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Unnecessarily qualified static access</problem_class>
<description>Unnecessarily qualified static method call &lt;code&gt;InnerClassTest.bar()&lt;/code&gt; #loc</description>
</problem>
<problem>
<file>UnnecessarilyQualifiedStaticUsageInspection.java</file>
<line>80</line>
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Unnecessarily qualified static access</problem_class>
<description>Unnecessarily qualified static access &lt;code&gt;InnerClassTest.foo&lt;/code&gt; #loc</description>
</problem>
</problems>
@@ -16,10 +16,10 @@
package org.jetbrains.plugins.groovy.codeInspection.spellchecker;
import com.intellij.codeInspection.SuppressIntentionAction;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.spellchecker.inspections.PlainTextSplitter;
import com.intellij.spellchecker.tokenizer.EscapeSequenceTokenizer;
import com.intellij.spellchecker.tokenizer.SuppressibleSpellcheckingStrategy;
import com.intellij.spellchecker.tokenizer.TokenConsumer;
import com.intellij.spellchecker.tokenizer.Tokenizer;
@@ -27,31 +27,43 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.codeInspection.GroovySuppressableInspectionTool;
import org.jetbrains.plugins.groovy.lang.lexer.TokenSets;
import org.jetbrains.plugins.groovy.lang.psi.GrNamedElement;
import org.jetbrains.plugins.groovy.lang.resolve.GroovyStringLiteralManipulator;
import org.jetbrains.plugins.groovy.lang.psi.util.GrStringUtil;
/**
* @author peter
*/
public class GroovySpellcheckingStrategy extends SuppressibleSpellcheckingStrategy {
private final GrDocCommentTokenizer myDocCommentTokenizer = new GrDocCommentTokenizer();
private Tokenizer<PsiElement> myStringTokenizer = new Tokenizer<PsiElement>() {
@Override
public void tokenize(@NotNull PsiElement literal, TokenConsumer consumer) {
String text = GrStringUtil.removeQuotes(literal.getText());
if (!text.contains("\\")) {
consumer.consumeToken(literal, PlainTextSplitter.getInstance());
}
else {
StringBuilder unescapedText = new StringBuilder();
int[] offsets = new int[text.length() + 1];
GrStringUtil.parseStringCharacters(text, unescapedText, offsets);
EscapeSequenceTokenizer.processTextWithOffsets(literal, consumer, unescapedText, offsets, GrStringUtil.getStartQuote(literal.getText()).length());
}
}
};
@NotNull
@Override
public Tokenizer getTokenizer(PsiElement element) {
if (TokenSets.STRING_LITERAL_SET.contains(element.getNode().getElementType())) {
return myStringTokenizer;
}
if (element instanceof GrNamedElement) {
final PsiElement name = ((GrNamedElement)element).getNameIdentifierGroovy();
if (TokenSets.STRING_LITERAL_SET.contains(name.getNode().getElementType())) {
return new Tokenizer<GrNamedElement>() {
@Override
public void tokenize(@NotNull GrNamedElement element, TokenConsumer consumer) {
String text = name.getText();
TextRange range = GroovyStringLiteralManipulator.getLiteralRange(text);
consumer.consumeToken(name, text, false, 0, range, PlainTextSplitter.getInstance());
}
};
return EMPTY_TOKENIZER;
}
}
if (element instanceof PsiDocComment) return myDocCommentTokenizer;
//if (element instanceof GrLiteralImpl && ((GrLiteralImpl)element).isStringLiteral()) return myStringTokenizer;
return super.getTokenizer(element);
}
@@ -155,7 +155,7 @@ replace.with.wrapper=Replace with {0}
replace.primitive.type.with.wrapper=Replace primitive type with wrapper
split.into.declaration.and.assignment=Split into declaration and assignment
split.into.separate.declaration=Split into separate declaration
gr.split.declaration.family.name=Split Variable Declaration
gr.split.declaration.intention.family.name=Split Variable Declaration
remove.parameter.0=Remove parameter ''{0}''
remove.unused.parameter=Remove unused parameter
remove.exception=Remove exception
@@ -45,5 +45,15 @@ class SpockTest {
'''
checkTypos()
}
public void testStringEscapes() {
myFixture.configureByText 'a.groovy', '''
def foo = "\\ntest \\n<TYPO descr="Typo: In word 'dddd'">dddd</TYPO>"
def foo1 = '\\ntest \\n<TYPO descr="Typo: In word 'dddd'">dddd</TYPO>'
def bar = """\\ntest \\n<TYPO descr="Typo: In word 'dddd'">dddd</TYPO>"""
def bar1 = \'''\\ntest \\n<TYPO descr="Typo: In word 'dddd'">dddd</TYPO>\'''
'''
checkTypos()
}
}
@@ -1,69 +1,69 @@
/*
* 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.spellchecker;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.psi.JavaTokenType;
import com.intellij.psi.PsiLiteralExpression;
import com.intellij.psi.PsiModifierListOwner;
import com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.spellchecker.inspections.PlainTextSplitter;
import com.intellij.spellchecker.tokenizer.EscapeSequenceTokenizer;
import com.intellij.spellchecker.tokenizer.TokenConsumer;
import com.intellij.spellchecker.tokenizer.Tokenizer;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
/**
* Created by IntelliJ IDEA.
*
* @author shkate@jetbrains.com
*/
public class LiteralExpressionTokenizer extends Tokenizer<PsiLiteralExpression> {
@Override
public void tokenize(@NotNull PsiLiteralExpression element, TokenConsumer consumer) {
PsiLiteralExpressionImpl literalExpression = (PsiLiteralExpressionImpl) element;
if (literalExpression.getLiteralElementType() != JavaTokenType.STRING_LITERAL) {
return; // not a string literal
}
final PsiModifierListOwner listOwner = PsiTreeUtil.getParentOfType(element, PsiModifierListOwner.class);
if (listOwner != null && AnnotationUtil.isAnnotated(listOwner, Collections.singleton(AnnotationUtil.NON_NLS))) {
return;
}
String text = literalExpression.getInnerText();
if (text == null) {
return;
}
if (!text.contains("\\")) {
consumer.consumeToken(element, PlainTextSplitter.getInstance());
}
else {
processTextWithEscapeSequences(element, text, consumer);
}
}
public static void processTextWithEscapeSequences(PsiLiteralExpression element, String text, TokenConsumer consumer) {
StringBuilder unescapedText = new StringBuilder();
int[] offsets = new int[text.length()+1];
PsiLiteralExpressionImpl.parseStringCharacters(text, unescapedText, offsets);
EscapeSequenceTokenizer.processTextWithOffsets(element, consumer, unescapedText, offsets);
}
}
/*
* 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.spellchecker;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.psi.JavaTokenType;
import com.intellij.psi.PsiLiteralExpression;
import com.intellij.psi.PsiModifierListOwner;
import com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.spellchecker.inspections.PlainTextSplitter;
import com.intellij.spellchecker.tokenizer.EscapeSequenceTokenizer;
import com.intellij.spellchecker.tokenizer.TokenConsumer;
import com.intellij.spellchecker.tokenizer.Tokenizer;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
/**
* Created by IntelliJ IDEA.
*
* @author shkate@jetbrains.com
*/
public class LiteralExpressionTokenizer extends Tokenizer<PsiLiteralExpression> {
@Override
public void tokenize(@NotNull PsiLiteralExpression element, TokenConsumer consumer) {
PsiLiteralExpressionImpl literalExpression = (PsiLiteralExpressionImpl) element;
if (literalExpression.getLiteralElementType() != JavaTokenType.STRING_LITERAL) {
return; // not a string literal
}
final PsiModifierListOwner listOwner = PsiTreeUtil.getParentOfType(element, PsiModifierListOwner.class);
if (listOwner != null && AnnotationUtil.isAnnotated(listOwner, Collections.singleton(AnnotationUtil.NON_NLS))) {
return;
}
String text = literalExpression.getInnerText();
if (text == null) {
return;
}
if (!text.contains("\\")) {
consumer.consumeToken(element, PlainTextSplitter.getInstance());
}
else {
processTextWithEscapeSequences(element, text, consumer);
}
}
public static void processTextWithEscapeSequences(PsiLiteralExpression element, String text, TokenConsumer consumer) {
StringBuilder unescapedText = new StringBuilder();
int[] offsets = new int[text.length()+1];
PsiLiteralExpressionImpl.parseStringCharacters(text, unescapedText, offsets);
EscapeSequenceTokenizer.processTextWithOffsets(element, consumer, unescapedText, offsets, 1);
}
}
@@ -1,77 +1,77 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution.junit;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.configuration.ConfigurationFactoryEx;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.execution.configurations.ModuleBasedConfiguration;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.project.Project;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class JUnitConfigurationType implements ConfigurationType {
public static final Icon ICON = AllIcons.RunConfigurations.UnitTest;
private final ConfigurationFactory myFactory;
/**reflection*/
public JUnitConfigurationType() {
myFactory = new ConfigurationFactoryEx(this) {
public RunConfiguration createTemplateConfiguration(Project project) {
return new JUnitConfiguration("", project, this);
}
@Override
public void onNewConfigurationCreated(@NotNull RunConfiguration configuration) {
((ModuleBasedConfiguration)configuration).onNewConfigurationCreated();
}
};
}
public String getDisplayName() {
return ExecutionBundle.message("junit.configuration.display.name");
}
public String getConfigurationTypeDescription() {
return ExecutionBundle.message("junit.configuration.description");
}
public Icon getIcon() {
return ICON;
}
public ConfigurationFactory[] getConfigurationFactories() {
return new ConfigurationFactory[]{myFactory};
}
@NotNull
public String getId() {
return "JUnit";
}
@Nullable
public static JUnitConfigurationType getInstance() {
return ContainerUtil.findInstance(Extensions.getExtensions(CONFIGURATION_TYPE_EP), JUnitConfigurationType.class);
}
}
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution.junit;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.configuration.ConfigurationFactoryEx;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.execution.configurations.ModuleBasedConfiguration;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.project.Project;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class JUnitConfigurationType implements ConfigurationType {
public static final Icon ICON = AllIcons.RunConfigurations.Junit;
private final ConfigurationFactory myFactory;
/**reflection*/
public JUnitConfigurationType() {
myFactory = new ConfigurationFactoryEx(this) {
public RunConfiguration createTemplateConfiguration(Project project) {
return new JUnitConfiguration("", project, this);
}
@Override
public void onNewConfigurationCreated(@NotNull RunConfiguration configuration) {
((ModuleBasedConfiguration)configuration).onNewConfigurationCreated();
}
};
}
public String getDisplayName() {
return ExecutionBundle.message("junit.configuration.display.name");
}
public String getConfigurationTypeDescription() {
return ExecutionBundle.message("junit.configuration.description");
}
public Icon getIcon() {
return ICON;
}
public ConfigurationFactory[] getConfigurationFactories() {
return new ConfigurationFactory[]{myFactory};
}
@NotNull
public String getId() {
return "JUnit";
}
@Nullable
public static JUnitConfigurationType getInstance() {
return ContainerUtil.findInstance(Extensions.getExtensions(CONFIGURATION_TYPE_EP), JUnitConfigurationType.class);
}
}
@@ -1,56 +1,56 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.spellchecker.tokenizer;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.spellchecker.inspections.PlainTextSplitter;
/**
* @author yole
*/
public class EscapeSequenceTokenizer {
public static void processTextWithOffsets(PsiElement element, TokenConsumer consumer, StringBuilder unescapedText,
int[] offsets) {
StringBuilder currentToken = new StringBuilder();
int currentTokenStart = 0;
for (int i = 0; i < unescapedText.length(); i++) {
if (offsets[i+1]-offsets[i] == 1) {
if (currentToken.length() == 0) {
currentTokenStart = offsets[i];
}
currentToken.append(unescapedText.charAt(i));
}
else {
if (currentToken.length() > 0) {
processCurrentToken(element, currentToken, currentTokenStart, consumer);
currentToken.setLength(0);
}
}
}
if (currentToken.length() > 0) {
processCurrentToken(element, currentToken, currentTokenStart, consumer);
}
}
private static void processCurrentToken(PsiElement element,
StringBuilder currentToken,
int currentTokenStart, TokenConsumer consumer) {
final String token = currentToken.toString();
// +1 for the starting quote of the string literal
consumer.consumeToken(element, token, false, currentTokenStart+1, TextRange.allOf(token), PlainTextSplitter.getInstance());
}
}
/*
* 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.spellchecker.tokenizer;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.spellchecker.inspections.PlainTextSplitter;
/**
* @author yole
*/
public class EscapeSequenceTokenizer {
public static void processTextWithOffsets(PsiElement element, TokenConsumer consumer, StringBuilder unescapedText,
int[] offsets, int startOffset) {
StringBuilder currentToken = new StringBuilder();
int currentTokenStart = startOffset;
for (int i = 0; i < unescapedText.length(); i++) {
if (offsets[i+1]-offsets[i] == 1) {
if (currentToken.length() == 0) {
currentTokenStart = offsets[i] + startOffset;
}
currentToken.append(unescapedText.charAt(i));
}
else {
if (currentToken.length() > 0) {
processCurrentToken(element, currentToken, currentTokenStart, consumer);
currentToken.setLength(0);
}
}
}
if (currentToken.length() > 0) {
processCurrentToken(element, currentToken, currentTokenStart, consumer);
}
}
private static void processCurrentToken(PsiElement element,
StringBuilder currentToken,
int currentTokenStart, TokenConsumer consumer) {
final String token = currentToken.toString();
// +1 for the starting quote of the string literal
consumer.consumeToken(element, token, false, currentTokenStart, TextRange.allOf(token), PlainTextSplitter.getInstance());
}
}
File diff suppressed because it is too large Load Diff