Merge commit 'origin/master'

This commit is contained in:
sweinreuter
2012-04-18 10:40:14 +02:00
92 changed files with 9692 additions and 450 deletions
+6 -2
View File
@@ -86,13 +86,17 @@ BITS=$?
if [ $OPEN_JDK -eq 0 ]; then
echo "WARNING: You are launching the IDE using OpenJDK Java runtime."
echo
echo " THIS IS STRICTLY UNSUPPORTED DUE TO KNOWN PERFORMANCE AND GRAPHICS PROBLEMS!"
echo " ITS KNOWN TO HAVE PERFORMANCE AND GRAPHICS ISSUES!"
echo " SWITCH TO THE ORACLE(SUN) JDK BEFORE REPORTING PROBLEMS!"
echo
echo "NOTE: If you have both Oracle (Sun) JDK and OpenJDK installed"
echo " please validate either @@product_uc@@_JDK, JDK_HOME, or JAVA_HOME environment variable points to valid Oracle (Sun) JDK installation."
echo " See http://ow.ly/6TuKQ for more info on switching default JDK."
echo
echo "Press Enter to continue."
# ---------------------------------------------------------------------
# COMMENT LINE BELOW TO REMOVE PAUSE AFTER OPEN JDK WARNING
# ---------------------------------------------------------------------
read IGNORE
fi
if [ $BITS -eq 0 ]; then
@@ -141,7 +145,7 @@ if [ "$IS_EAP" = "true" ]; then
OS_NAME=`echo $OS_TYPE | "$TR" '[:upper:]' '[:lower:]'`
AGENT_LIB="yjpagent-$OS_NAME$BITS"
if [ -r "$IDE_BIN_HOME/lib$AGENT_LIB.so" ]; then
AGENT="-agentlib:$AGENT_LIB=disablej2ee,disablecounts,disablealloc,sessionname=@@system_selector@@"
AGENT="-agentlib:$AGENT_LIB=disablej2ee,disablealloc,sessionname=@@system_selector@@"
fi
fi
+1 -1
View File
@@ -206,7 +206,7 @@ libraryLicense(name: "Maven3", libraryNames: ["Maven3", "maven-dependency-tree-1
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.jar", version: "3.7.1", license: "BSD", url: "http://www.miglayout.com/", licenseUrl: "http://www.miglayout.com/mavensite/license.html")
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")
+3 -3
View File
@@ -60,10 +60,10 @@ binding.setVariable("vmOptions", { "$common_vmoptions ${isEap() ? '-XX:+HeapDump
binding.setVariable("vmOptions32", { "$mem32 ${vmOptions()}".trim() })
binding.setVariable("vmOptions64", { "$mem64 ${vmOptions()}".trim() })
binding.setVariable("vmOptions32yjp", { String systemSelector ->
"${vmOptions32()} -agentlib:yjpagent=disablej2ee,disablecounts,disablealloc,sessionname=$systemSelector".trim()
"${vmOptions32()} -agentlib:yjpagent=disablej2ee,disablealloc,sessionname=$systemSelector".trim()
})
binding.setVariable("vmOptions64yjp", { String systemSelector ->
"${vmOptions64()} -agentlib:yjpagent64=disablej2ee,disablecounts,disablealloc,sessionname=$systemSelector".trim()
"${vmOptions64()} -agentlib:yjpagent64=disablej2ee,disablealloc,sessionname=$systemSelector".trim()
})
binding.setVariable("isDefined", {String key ->
@@ -252,7 +252,7 @@ binding.setVariable("layoutMacApp", { String path, String ch, Map args ->
String vmOptions = "${vmOptions()} -Xverify:none"
if (isEap() && !args.mac_no_yjp) {
vmOptions += " -agentlib:yjpagent=disablej2ee,disablecounts,disablealloc,sessionname=${args.system_selector}"
vmOptions += " -agentlib:yjpagent=disablej2ee,disablealloc,sessionname=${args.system_selector}"
}
String version = isEap() ? "EAP $args.buildNumber" : "${p("component.version.major")}.${p("component.version.minor")}"
@@ -71,11 +71,20 @@ public abstract class SelectImportedProjectsStep<T> extends ProjectImportWizardS
return panel;
}
protected boolean isElementEnabled(T element) {
return true;
}
public void updateStep() {
fileChooser.clear();
for (T element : getContext().getList()) {
fileChooser.addElement(element, getContext().isMarked(element));
boolean isEnabled = isElementEnabled(element);
fileChooser.addElement(element, isEnabled && getContext().isMarked(element));
if (!isEnabled) {
fileChooser.disableElement(element);
}
}
fileChooser.setBorder(IdeBorderFactory.createTitledBorder(
IdeBundle.message("project.import.select.title", getContext().getName()), false));
openModuleSettingsCheckBox.setSelected(getBuilder().isOpenProjectSettingsAfter());
@@ -973,6 +973,13 @@ public class GenericsHighlightUtil {
return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, ref, JavaErrorMessages.message("generics.cannot.instanceof.type.parameters"));
}
if (resolved instanceof PsiClass) {
final PsiClass containingClass = ((PsiClass)resolved).getContainingClass();
if (containingClass != null && ref.getQualifier() == null && containingClass.getTypeParameters().length > 0) {
return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, typeElement, JavaErrorMessages.message("illegal.generic.type.for.instanceof"));
}
}
final PsiType[] parameters = ref.getTypeParameters();
for (PsiType parameterType : parameters) {
if (parameterType != null &&
@@ -1506,6 +1506,10 @@ public class JavaDocInfoGenerator {
}
}
if (type instanceof PsiCapturedWildcardType) {
type = ((PsiCapturedWildcardType)type).getWildcard();
}
if (type instanceof PsiWildcardType){
PsiWildcardType wt = ((PsiWildcardType)type);
@@ -47,7 +47,9 @@ public class DummyEntryPointsTool extends FilteringInspectionTool {
public void runInspection(@NotNull AnalysisScope scope, @NotNull final InspectionManager manager) {}
public void exportResults(@NotNull Element parentNode) {}
@Override
public void exportResults(@NotNull Element parentNode, RefEntity refEntity) {
}
@NotNull
public JobDescriptor[] getJobDescriptors(GlobalInspectionContext globalInspectionContext) {
@@ -631,45 +631,43 @@ public class UnusedDeclarationInspection extends FilteringInspectionTool {
return myComposer;
}
public void exportResults(@NotNull final Element parentNode) {
@Override
public void exportResults(@NotNull final Element parentNode, RefEntity refEntity) {
if (!(refEntity instanceof RefJavaElement)) return;
final WeakUnreferencedFilter filter = new WeakUnreferencedFilter(this);
getRefManager().iterate(new RefJavaVisitor() {
@Override public void visitElement(RefEntity refEntity) {
if (!(refEntity instanceof RefJavaElement)) return;
if (!getIgnoredRefElements().contains(refEntity) && filter.accepts((RefJavaElement)refEntity)) {
if (refEntity instanceof RefImplicitConstructor) refEntity = ((RefImplicitConstructor)refEntity).getOwnerClass();
Element element = refEntity.getRefManager().export(refEntity, parentNode, -1);
@NonNls Element problemClassElement = new Element(InspectionsBundle.message("inspection.export.results.problem.element.tag"));
if (!getIgnoredRefElements().contains(refEntity) && filter.accepts((RefJavaElement)refEntity)) {
if (refEntity instanceof RefImplicitConstructor) refEntity = ((RefImplicitConstructor)refEntity).getOwnerClass();
Element element = refEntity.getRefManager().export(refEntity, parentNode, -1);
@NonNls Element problemClassElement = new Element(InspectionsBundle.message("inspection.export.results.problem.element.tag"));
if (refEntity instanceof RefElement) {
final RefElement refElement = (RefElement)refEntity;
final HighlightSeverity severity = getCurrentSeverity(refElement);
final String attributeKey = getTextAttributeKey(refElement.getElement().getProject(), severity, ProblemHighlightType.LIKE_UNUSED_SYMBOL);
problemClassElement.setAttribute("severity", severity.myName);
problemClassElement.setAttribute("attribute_key", attributeKey);
}
problemClassElement.addContent(InspectionsBundle.message("inspection.export.results.dead.code"));
element.addContent(problemClassElement);
@NonNls Element hintsElement = new Element("hints");
for (String hint : HINTS) {
@NonNls Element hintElement = new Element("hint");
hintElement.setAttribute("value", hint);
hintsElement.addContent(hintElement);
}
element.addContent(hintsElement);
Element descriptionElement = new Element(InspectionsBundle.message("inspection.export.results.description.tag"));
StringBuffer buf = new StringBuffer();
DeadHTMLComposer.appendProblemSynopsis((RefElement)refEntity, buf);
descriptionElement.addContent(buf.toString());
element.addContent(descriptionElement);
}
if (refEntity instanceof RefElement) {
final RefElement refElement = (RefElement)refEntity;
final HighlightSeverity severity = getCurrentSeverity(refElement);
final String attributeKey =
getTextAttributeKey(refElement.getRefManager().getProject(), severity, ProblemHighlightType.LIKE_UNUSED_SYMBOL);
problemClassElement.setAttribute("severity", severity.myName);
problemClassElement.setAttribute("attribute_key", attributeKey);
}
});
problemClassElement.addContent(InspectionsBundle.message("inspection.export.results.dead.code"));
element.addContent(problemClassElement);
@NonNls Element hintsElement = new Element("hints");
for (String hint : HINTS) {
@NonNls Element hintElement = new Element("hint");
hintElement.setAttribute("value", hint);
hintsElement.addContent(hintElement);
}
element.addContent(hintsElement);
Element descriptionElement = new Element(InspectionsBundle.message("inspection.export.results.description.tag"));
StringBuffer buf = new StringBuffer();
DeadHTMLComposer.appendProblemSynopsis((RefElement)refEntity, buf);
descriptionElement.addContent(buf.toString());
element.addContent(descriptionElement);
}
}
public QuickFixAction[] getQuickFixes(final RefEntity[] refElements) {
@@ -75,7 +75,7 @@ public class RefJavaUtilImpl extends RefJavaUtil{
if (refConstructor == null) { // No explicit constructor referenced. Should use default one.
PsiType newType = newExpr.getType();
if (newType instanceof PsiClassType) {
processClassReference(PsiUtil.resolveClassInType(newType), refFrom, psiFrom);
processClassReference(PsiUtil.resolveClassInType(newType), refFrom, psiFrom, true);
}
}
}
@@ -124,22 +124,38 @@ public class RefJavaUtilImpl extends RefJavaUtil{
final PsiTypeElement operand = expression.getOperand();
final PsiType type = operand.getType();
if (type instanceof PsiClassType) {
processClassReference(((PsiClassType)type).resolve(), refFrom, psiFrom);
processClassReference(((PsiClassType)type).resolve(), refFrom, psiFrom, false);
}
}
private void processClassReference(final PsiClass psiClass, final RefJavaElementImpl refFrom, final PsiModifierListOwner psiFrom) {
private void processClassReference(final PsiClass psiClass,
final RefJavaElementImpl refFrom,
final PsiModifierListOwner psiFrom,
boolean defaultConstructorOnly) {
if (psiClass != null) {
RefClassImpl refClass = (RefClassImpl)refFrom.getRefManager().getReference(psiClass);
if (refClass != null) {
RefMethodImpl refDefaultConstructor = (RefMethodImpl)refClass.getDefaultConstructor();
boolean hasConstructorsMarked = false;
if (refDefaultConstructor != null && !(refDefaultConstructor instanceof RefImplicitConstructor)) {
refDefaultConstructor.addInReference(refFrom);
refFrom.addOutReference(refDefaultConstructor);
if (defaultConstructorOnly) {
RefMethodImpl refDefaultConstructor = (RefMethodImpl)refClass.getDefaultConstructor();
if (refDefaultConstructor != null && !(refDefaultConstructor instanceof RefImplicitConstructor)) {
refDefaultConstructor.addInReference(refFrom);
refFrom.addOutReference(refDefaultConstructor);
hasConstructorsMarked = true;
}
}
else {
for (RefMethod cons : refClass.getConstructors()) {
if (cons instanceof RefImplicitConstructor) continue;
((RefMethodImpl)cons).addInReference(refFrom);
refFrom.addOutReference(cons);
hasConstructorsMarked = true;
}
}
if (!hasConstructorsMarked) {
refFrom.addReference(refClass, psiClass, psiFrom, false, true, null);
}
}
@@ -385,4 +401,4 @@ public class RefJavaUtilImpl extends RefJavaUtil{
}
}
}
}
}
@@ -0,0 +1,27 @@
class A<T> {
public void foo(Object object) {
if (object instanceof <error descr="Illegal generic type for instanceof">B</error>) {}
if (object instanceof A.B) {}
if (object instanceof A<?>.B) {}
if (object instanceof A<?>) {}
if (object instanceof <error descr="Illegal generic type for instanceof">A<String></error>) {}
if (object instanceof A) {}
if (object instanceof A[]) {}
if (object instanceof <error descr="Illegal generic type for instanceof">B[]</error>) {}
if (object instanceof A.B[]) {}
}
private class B {
}
}
class A1 {
public void foo(Object object) {
if (object instanceof B1) {}
if (object instanceof A1.B1) {}
if (object instanceof B1[]) {}
}
private class B1 {
}
}
@@ -1,3 +1,4 @@
import java.lang.Override;
import java.util.*;
class GenericsTest<T> {
@@ -91,4 +92,30 @@ class GenericsTest2<T> {
}
};
}
}
class Example {
private static <T> void assertThat(T actual, Matcher<? super T> matcher) {
assert actual != null;
assert matcher != null;
}
private static <E> Matcher<? super Collection<? extends E>> hasSize(int size) {
assert size >=0;
return new Matcher<Collection<? extends E>>() {
@Override
public void foo(Collection<? extends E> es) {
System.out.println(es);
}
};
}
public static void main(String[] args) {
List<Boolean> list = <warning descr="Unchecked assignment: 'java.util.ArrayList' to 'java.util.List<java.lang.Boolean>'">new ArrayList()</warning>;
System.out.println(list);
assertThat(new ArrayList<Boolean>(), hasSize(0));
}
private interface Matcher<T> {
void foo(T t);
}
}
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<problems/>
@@ -0,0 +1,12 @@
import java.lang.Class;
import java.lang.String;
public class Test {
public static void main(String[] args) {
Test.class.getDeclaredConstructor(String.class).newInstance("Foo");
}
public Test(String param) {
System.out.println("This is used!");
}
}
@@ -132,6 +132,7 @@ public class GenericsHighlightingTest extends LightDaemonAnalyzerTestCase {
public void testIDEA74899() throws Exception {doTest(false);}
public void testIDEA63291() throws Exception {doTest(false);}
public void testIDEA72912() throws Exception {doTest(false);}
public void testIllegalGenericTypeInInstanceof() throws Exception {doTest(false);}
public void testJavaUtilCollections_NoVerify() throws Exception {
PsiClass collectionsClass = getJavaFacade().findClass("java.util.Collections", GlobalSearchScope.moduleWithLibrariesScope(getModule()));
@@ -184,4 +184,8 @@ public class UnusedDeclarationTest extends InspectionTestCase {
public void testAbstractClassWithSerializableSubclasses() throws Exception {
doTest();
}
public void testclassLiteralRef() throws Exception {
doTest();
}
}
@@ -0,0 +1,135 @@
package org.jetbrains.jpsservice;
option java_package = "org.jetbrains.jps.api";
option optimize_for = LITE_RUNTIME;
message Message {
message UUID {
required sint64 most_sig_bits = 1;
required sint64 least_sig_bits = 2;
}
message KeyValuePair {
required string key = 1;
required string value = 2;
}
enum Type {
CONTROLLER_MESSAGE = 1;
BUILDER_MESSAGE = 2;
FAILURE = 3;
}
message Failure {
optional int32 error_code = 1;
optional string description = 2;
optional string stacktrace = 3;
}
message ControllerMessage {
enum Type {
BUILD_PARAMETERS = 1;
CANCEL_BUILD_COMMAND = 2;
}
message GlobalSettings {
message GlobalLibrary {
required string name = 1;
optional string homePath = 2;
optional string type_name = 3;
optional string additional_data_xml = 4;
repeated string path = 5;
optional string version = 6;
}
repeated KeyValuePair path_variable = 1;
repeated GlobalLibrary global_library = 2;
optional string global_encoding = 3;
optional string ignored_files_patterns = 4;
}
message ParametersMessage {
enum Type {
REBUILD = 1;
MAKE = 2;
CLEAN = 3;
FORCED_COMPILATION = 4;
}
required Type build_type = 1;
optional GlobalSettings global_settings = 2;
optional string project_id = 3;
repeated string module_name = 4;
repeated string file_path = 5;
repeated string artifact_name = 6;
repeated KeyValuePair builder_parameter = 7;
}
required Type type = 1;
optional ParametersMessage params_message = 2;
}
message BuilderMessage {
enum Type {
PARAM_REQUEST = 1;
BUILD_EVENT = 2;
COMPILE_MESSAGE = 3;
}
message BuildEvent {
enum Type {
BUILD_COMPLETED = 1;
FILES_GENERATED = 2;
}
enum Status {
CANCELED = 1;
ERRORS = 2;
SUCCESS = 3;
UP_TO_DATE = 4;
}
message GeneratedFile {
required string output_root = 1;
required string relative_path = 2;
}
required Type event_type = 1;
optional string description = 2;
optional Status completion_status = 3;
repeated GeneratedFile generated_files = 4;
}
message CompileMessage {
enum Kind {
ERROR = 1;
WARNING = 2;
INFO = 3;
PROGRESS = 4;
}
required Kind kind = 1;
optional string text = 2;
optional string source_file_path = 3;
optional uint64 problem_begin_offset = 4;
optional uint64 problem_end_offset = 5;
optional uint64 problem_location_offset = 6;
optional uint64 line = 7;
optional uint64 column = 8;
optional float done = 9;
}
required Type type = 1;
optional BuildEvent build_event = 2;
optional CompileMessage compile_message = 3;
}
required UUID session_id = 1;
required Type type = 2;
optional ControllerMessage controller_message = 3;
optional BuilderMessage builder_message = 4;
optional Failure failure = 5;
}
+2 -1
View File
@@ -1,2 +1,3 @@
call protoc -I=. --java_out=../src javac_remote_proto.proto
call protoc -I=. --java_out=../src jps_remote_proto.proto
call protoc -I=. --java_out=../src jps_remote_proto.proto
call protoc -I=. --java_out=../src cmdline_remote_proto.proto
+2 -1
View File
@@ -1,2 +1,3 @@
protoc -I=. --java_out=../src javac_remote_proto.proto
protoc -I=. --java_out=../src jps_remote_proto.proto
protoc -I=. --java_out=../src jps_remote_proto.proto
protoc -I=. --java_out=../src cmdline_remote_proto.proto
@@ -0,0 +1,121 @@
package org.jetbrains.jps.api;
import com.intellij.openapi.util.Pair;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.incremental.messages.BuildMessage;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Collection;
import java.util.UUID;
/**
* @author Eugene Zhuravlev
* Date: 4/17/12
*/
public class CmdlineProtoUtil {
public static CmdlineRemoteProto.Message.Failure createFailure(String description, Throwable cause) {
final CmdlineRemoteProto.Message.Failure.Builder builder = CmdlineRemoteProto.Message.Failure.newBuilder();
builder.setDescription(description);
if (cause != null) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
cause.printStackTrace(new PrintStream(baos));
builder.setStacktrace(new String(baos.toByteArray()));
}
return builder.build();
}
public static CmdlineRemoteProto.Message.BuilderMessage createCompileProgressMessageResponse(String text, float done) {
return createCompileMessageResponse(BuildMessage.Kind.PROGRESS, text, null, -1L, -1L, -1L, -1, -1, done);
}
public static CmdlineRemoteProto.Message.BuilderMessage createCompileMessageResponse(final BuildMessage.Kind kind,
String text,
String path,
long beginOffset, long endOffset, long offset, long line,
long column, float done) {
final CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Builder builder = CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.newBuilder();
switch (kind) {
case ERROR:
builder.setKind(CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind.ERROR);
break;
case WARNING:
builder.setKind(CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind.WARNING);
break;
case INFO:
builder.setKind(CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind.INFO);
break;
default:
builder.setKind(CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind.PROGRESS);
}
if (text != null) {
builder.setText(text);
}
if (path != null) {
builder.setSourceFilePath(path);
}
if (beginOffset >= 0L) {
builder.setProblemBeginOffset(beginOffset);
}
if (endOffset >= 0L) {
builder.setProblemEndOffset(endOffset);
}
if (offset >= 0L) {
builder.setProblemLocationOffset(offset);
}
if (line > 0L) {
builder.setLine(line);
}
if (column > 0L) {
builder.setColumn(column);
}
if (done >= 0.0f) {
builder.setDone(done);
}
return CmdlineRemoteProto.Message.BuilderMessage.newBuilder().setType(CmdlineRemoteProto.Message.BuilderMessage.Type.COMPILE_MESSAGE).setCompileMessage(builder.build()).build();
}
public static CmdlineRemoteProto.Message.BuilderMessage createBuildCompletedEvent(@Nullable String description, final CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status status) {
return createBuildEvent(CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Type.BUILD_COMPLETED, description, status, null);
}
public static CmdlineRemoteProto.Message.BuilderMessage createFileGeneratedEvent(final Collection<Pair<String, String>> paths) {
return createBuildEvent(CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Type.FILES_GENERATED, null, null, paths);
}
public static CmdlineRemoteProto.Message.BuilderMessage createBuildEvent(final CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Type type, @Nullable String description, final CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status status, Collection<Pair<String, String>> generatedPaths) {
final CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Builder builder = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.newBuilder().setEventType(type);
if (description != null) {
builder.setDescription(description);
}
if (status != null) {
builder.setCompletionStatus(status);
}
if (generatedPaths != null) {
for (Pair<String, String> pair : generatedPaths) {
final CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.GeneratedFile.Builder fileBuilder = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.GeneratedFile.newBuilder();
final CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.GeneratedFile generatedFile = fileBuilder.setOutputRoot(pair.first).setRelativePath(pair.second).build();
builder.addGeneratedFiles(generatedFile);
}
}
return CmdlineRemoteProto.Message.BuilderMessage.newBuilder().setType(CmdlineRemoteProto.Message.BuilderMessage.Type.BUILD_EVENT).setBuildEvent(builder.build()).build();
}
public static CmdlineRemoteProto.Message.BuilderMessage createParamRequest() {
return CmdlineRemoteProto.Message.BuilderMessage.newBuilder().setType(CmdlineRemoteProto.Message.BuilderMessage.Type.PARAM_REQUEST).build();
}
public static CmdlineRemoteProto.Message toMessage(UUID sessionId, CmdlineRemoteProto.Message.BuilderMessage builderMessage) {
return CmdlineRemoteProto.Message.newBuilder().setSessionId(toProtoUUID(sessionId)).setType(CmdlineRemoteProto.Message.Type.BUILDER_MESSAGE).setBuilderMessage(builderMessage).build();
}
public static CmdlineRemoteProto.Message toMessage(UUID sessionId, CmdlineRemoteProto.Message.Failure failure) {
return CmdlineRemoteProto.Message.newBuilder().setSessionId(toProtoUUID(sessionId)).setType(CmdlineRemoteProto.Message.Type.FAILURE).setFailure(failure).build();
}
private static CmdlineRemoteProto.Message.UUID toProtoUUID(UUID sessionId) {
final CmdlineRemoteProto.Message.UUID.Builder uuidBuilder = CmdlineRemoteProto.Message.UUID.newBuilder();
return uuidBuilder.setMostSigBits(sessionId.getMostSignificantBits()).setLeastSigBits(sessionId.getLeastSignificantBits()).build();
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,144 @@
package org.jetbrains.jps.cmdline;
import com.intellij.openapi.diagnostic.Logger;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.protobuf.ProtobufDecoder;
import org.jboss.netty.handler.codec.protobuf.ProtobufEncoder;
import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import org.jetbrains.jps.api.CmdlineProtoUtil;
import org.jetbrains.jps.api.CmdlineRemoteProto;
import org.jetbrains.jps.api.SharedThreadPool;
import java.io.File;
import java.net.InetSocketAddress;
import java.util.UUID;
/**
* @author Eugene Zhuravlev
* Date: 4/16/12
*/
public class BuildMain {
private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.cmdline.BuildMain");
public static void main(String[] args){
final String host = args[0];
final int port = Integer.parseInt(args[1]);
final UUID sessionId = UUID.fromString(args[2]);
final File systemDir = new File(args[3]);
systemDir.mkdirs();
final ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(SharedThreadPool.INSTANCE, SharedThreadPool.INSTANCE, 1));
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(
new ProtobufVarint32FrameDecoder(),
new ProtobufDecoder(CmdlineRemoteProto.Message.getDefaultInstance()),
new ProtobufVarint32LengthFieldPrepender(),
new ProtobufEncoder(),
new MyMessageHandler(sessionId)
);
}
});
bootstrap.setOption("tcpNoDelay", true);
bootstrap.setOption("keepAlive", true);
final ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
future.awaitUninterruptibly();
final boolean success = future.isSuccess();
if (success) {
Channels.write(future.getChannel(), CmdlineProtoUtil.toMessage(sessionId, CmdlineProtoUtil.createParamRequest()));
}
else {
final Throwable reason = future.getCause();
if (reason != null) {
System.err.println("Error connecting to " + host + ":" + port + "; " + reason.getMessage());
reason.printStackTrace(System.err);
}
System.exit(-1);
}
}
private static class MyMessageHandler extends SimpleChannelHandler {
private final UUID mySessionId;
private volatile BuildSession mySession;
private MyMessageHandler(UUID sessionId) {
mySessionId = sessionId;
}
@Override
public void messageReceived(final ChannelHandlerContext ctx, MessageEvent e) throws Exception {
CmdlineRemoteProto.Message message = (CmdlineRemoteProto.Message)e.getMessage();
final CmdlineRemoteProto.Message.Type type = message.getType();
if (type == CmdlineRemoteProto.Message.Type.CONTROLLER_MESSAGE) {
final CmdlineRemoteProto.Message.ControllerMessage controllerMessage = message.getControllerMessage();
switch (controllerMessage.getType()) {
case BUILD_PARAMETERS:
if (mySession == null) {
final BuildSession session = new BuildSession(mySessionId, ctx.getChannel(), controllerMessage.getParamsMessage());
mySession = session;
SharedThreadPool.INSTANCE.submit(session);
}
else {
LOG.info("Cannot start another build session because one is already running");
}
return;
case CANCEL_BUILD_COMMAND:
final BuildSession session = mySession;
if (session != null) {
session.cancel();
}
else {
LOG.info("Cannot cancel build: no build session is running");
closeChannel(ctx.getChannel());
}
return;
}
}
Channels.write(ctx.getChannel(), CmdlineProtoUtil.toMessage(mySessionId, CmdlineProtoUtil.createFailure("Unsupported message type: " + type.name(), null)));
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
try {
super.channelClosed(ctx, e);
}
finally {
SharedThreadPool.INSTANCE.submit(new Runnable() {
@Override
public void run() {
System.exit(0);
}
});
}
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
try {
super.channelDisconnected(ctx, e);
}
finally {
closeChannel(ctx.getChannel());
}
}
}
private static void closeChannel(final Channel channel) {
SharedThreadPool.INSTANCE.submit(new Runnable() {
@Override
public void run() {
channel.close().awaitUninterruptibly();
}
});
}
}
@@ -0,0 +1,406 @@
package org.jetbrains.jps.cmdline;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import groovy.util.Node;
import groovy.util.XmlParser;
import org.codehaus.groovy.runtime.MethodClosure;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.Channels;
import org.jetbrains.jps.Library;
import org.jetbrains.jps.Module;
import org.jetbrains.jps.Project;
import org.jetbrains.jps.Sdk;
import org.jetbrains.jps.api.*;
import org.jetbrains.jps.artifacts.Artifact;
import org.jetbrains.jps.idea.IdeaProjectLoader;
import org.jetbrains.jps.idea.SystemOutErrorReporter;
import org.jetbrains.jps.incremental.*;
import org.jetbrains.jps.incremental.messages.*;
import org.jetbrains.jps.incremental.storage.BuildDataManager;
import org.jetbrains.jps.incremental.storage.ProjectTimestamps;
import org.jetbrains.jps.incremental.storage.TimestampStorage;
import org.jetbrains.jps.server.ProjectDescriptor;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.util.*;
/**
* @author Eugene Zhuravlev
* Date: 4/17/12
*/
final class BuildSession implements Runnable, CanceledStatus {
private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.cmdline.BuildSession");
public static final String IDEA_PROJECT_DIRNAME = ".idea";
private final UUID mySessionId;
private final Channel myChannel;
private volatile boolean myCanceled = false;
// globals
private final Map<String, String> myPathVars;
private final List<GlobalLibrary> myGlobalLibraries;
private final String myGlobalEncoding;
private final String myIgnorePatterns;
// build params
private final BuildType myBuildType;
private final Set<String> myModules;
private final List<String> myArtifacts;
private final List<String> myFilePaths;
private final Map<String, String> myBuilderParams;
private String myProjectPath;
// todo pass FSState in order not to scan FS from scratch
BuildSession(UUID sessionId, Channel channel, CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage params) {
mySessionId = sessionId;
myChannel = channel;
// globals
myPathVars = new HashMap<String, String>();
final CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings globals = params.getGlobalSettings();
for (CmdlineRemoteProto.Message.KeyValuePair variable : globals.getPathVariableList()) {
myPathVars.put(variable.getKey(), variable.getValue());
}
myGlobalLibraries = new ArrayList<GlobalLibrary>();
for (CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings.GlobalLibrary library : globals.getGlobalLibraryList()) {
myGlobalLibraries.add(
library.hasHomePath() ?
new SdkLibrary(library.getName(), library.getTypeName(), library.hasVersion() ? library.getVersion() : null, library.getHomePath(), library.getPathList(), library.hasAdditionalDataXml() ? library.getAdditionalDataXml() : null) :
new GlobalLibrary(library.getName(), library.getPathList())
);
}
myGlobalEncoding = globals.hasGlobalEncoding()? globals.getGlobalEncoding() : null;
myIgnorePatterns = globals.hasIgnoredFilesPatterns()? globals.getIgnoredFilesPatterns() : null;
// session params
myProjectPath = FileUtil.toCanonicalPath(params.getProjectId());
myBuildType = convertCompileType(params.getBuildType());
myModules = new HashSet<String>(params.getModuleNameList());
myArtifacts = params.getArtifactNameList();
myFilePaths = params.getFilePathList();
myBuilderParams = new HashMap<String, String>();
for (CmdlineRemoteProto.Message.KeyValuePair pair : params.getBuilderParameterList()) {
myBuilderParams.put(pair.getKey(), pair.getValue());
}
}
public void run() {
Throwable error = null;
final Ref<Boolean> hasErrors = new Ref<Boolean>(false);
final Ref<Boolean> markedFilesUptodate = new Ref<Boolean>(false);
try {
runBuild(myProjectPath, myBuildType, myModules, myArtifacts, myBuilderParams, myFilePaths, new MessageHandler() {
public void processMessage(BuildMessage buildMessage) {
final CmdlineRemoteProto.Message.BuilderMessage response;
if (buildMessage instanceof FileGeneratedEvent) {
final Collection<Pair<String, String>> paths = ((FileGeneratedEvent)buildMessage).getPaths();
response = !paths.isEmpty() ? CmdlineProtoUtil.createFileGeneratedEvent(paths) : null;
}
else if (buildMessage instanceof UptoDateFilesSavedEvent) {
markedFilesUptodate.set(true);
response = null;
}
else if (buildMessage instanceof CompilerMessage) {
markedFilesUptodate.set(true);
final CompilerMessage compilerMessage = (CompilerMessage)buildMessage;
final String text = compilerMessage.getCompilerName() + ": " + compilerMessage.getMessageText();
final BuildMessage.Kind kind = compilerMessage.getKind();
if (kind == BuildMessage.Kind.ERROR) {
hasErrors.set(true);
}
response = CmdlineProtoUtil.createCompileMessageResponse(
kind, text, compilerMessage.getSourcePath(),
compilerMessage.getProblemBeginOffset(), compilerMessage.getProblemEndOffset(),
compilerMessage.getProblemLocationOffset(), compilerMessage.getLine(), compilerMessage.getColumn(),
-1.0f);
}
else {
float done = -1.0f;
if (buildMessage instanceof ProgressMessage) {
done = ((ProgressMessage)buildMessage).getDone();
}
response = CmdlineProtoUtil.createCompileProgressMessageResponse(buildMessage.getMessageText(), done);
}
if (response != null) {
Channels.write(myChannel, CmdlineProtoUtil.toMessage(mySessionId, response));
}
}
}, this);
}
catch (Throwable e) {
LOG.info(e);
error = e;
}
finally {
finishBuild(error, hasErrors.get(), markedFilesUptodate.get());
}
}
private void runBuild(String projectPath, BuildType buildType, Set<String> modules, Collection<String> artifacts, Map<String, String> builderParams, Collection<String> paths, final MessageHandler msgHandler, CanceledStatus cs) throws Throwable{
ProjectDescriptor pd;
final Project project = loadProject(projectPath);
final FSState fsState = new FSState(false);
ProjectTimestamps timestamps = null;
BuildDataManager dataManager = null;
final File dataStorageRoot = Utils.getDataStorageRoot(project);
try {
timestamps = new ProjectTimestamps(dataStorageRoot);
dataManager = new BuildDataManager(dataStorageRoot, true);
}
catch (Exception e) {
// second try
e.printStackTrace(System.err);
if (timestamps != null) {
timestamps.close();
}
if (dataManager != null) {
dataManager.close();
}
buildType = BuildType.PROJECT_REBUILD; // force project rebuild
FileUtil.delete(dataStorageRoot);
timestamps = new ProjectTimestamps(dataStorageRoot);
dataManager = new BuildDataManager(dataStorageRoot, true);
// second attempt succeded
msgHandler.processMessage(new CompilerMessage("compile-server", BuildMessage.Kind.INFO, "Project rebuild forced: " + e.getMessage()));
}
pd = new ProjectDescriptor(project, fsState, timestamps, dataManager, BuildLoggingManager.DEFAULT);
try {
final CompileScope compileScope = createCompilationScope(buildType, pd, modules, artifacts, paths);
final IncProjectBuilder builder = new IncProjectBuilder(pd, BuilderRegistry.getInstance(), builderParams, cs);
if (msgHandler != null) {
builder.addMessageHandler(msgHandler);
}
switch (buildType) {
case PROJECT_REBUILD:
builder.build(compileScope, false, true);
break;
case FORCED_COMPILATION:
builder.build(compileScope, false, false);
break;
case MAKE:
builder.build(compileScope, true, false);
break;
case CLEAN:
//todo[nik]
// new ProjectBuilder(new GantBinding(), project).clean();
break;
}
}
finally {
pd.release();
}
}
private void finishBuild(Throwable error, boolean hadBuildErrors, boolean markedUptodateFiles) {
CmdlineRemoteProto.Message lastMessage = null;
try {
if (error != null) {
Throwable cause = error.getCause();
if (cause == null) {
cause = error;
}
final ByteArrayOutputStream out = new ByteArrayOutputStream();
cause.printStackTrace(new PrintStream(out));
final StringBuilder messageText = new StringBuilder();
messageText.append("Internal error: (").append(cause.getClass().getName()).append(") ").append(cause.getMessage());
final String trace = out.toString();
if (!trace.isEmpty()) {
messageText.append("\n").append(trace);
}
lastMessage = CmdlineProtoUtil.toMessage(mySessionId, CmdlineProtoUtil.createFailure(messageText.toString(), cause));
}
else {
CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.SUCCESS;
if (myCanceled) {
status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.CANCELED;
}
else if (hadBuildErrors) {
status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.ERRORS;
}
else if (!markedUptodateFiles){
status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.UP_TO_DATE;
}
lastMessage = CmdlineProtoUtil.toMessage(mySessionId, CmdlineProtoUtil.createBuildCompletedEvent("build completed", status));
}
}
catch (Throwable e) {
lastMessage = CmdlineProtoUtil.toMessage(mySessionId, CmdlineProtoUtil.createFailure(e.getMessage(), e));
}
finally {
Channels.write(myChannel, lastMessage).addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
SharedThreadPool.INSTANCE.submit(new Runnable() {
@Override
public void run() {
final ChannelFuture closeFuture = myChannel.close();
closeFuture.awaitUninterruptibly();
}
});
}
});
}
}
public void cancel() {
myCanceled = true;
}
@Override
public boolean isCanceled() {
return myCanceled;
}
private Project loadProject(String projectPath) {
final long start = System.currentTimeMillis();
try {
final Project project = new Project();
// setup JDKs and global libraries
final MethodClosure fakeClosure = new MethodClosure(new Object(), "hashCode");
for (GlobalLibrary library : myGlobalLibraries) {
if (library instanceof SdkLibrary) {
final SdkLibrary sdk = (SdkLibrary)library;
Node additionalData = null;
final String additionalXml = sdk.getAdditionalDataXml();
if (additionalXml != null) {
try {
additionalData = new XmlParser(false, false).parseText(additionalXml);
}
catch (Exception e) {
LOG.info(e);
}
}
final Sdk jdk = project.createSdk(sdk.getTypeName(), sdk.getName(), sdk.getVersion(), sdk.getHomePath(), additionalData);
if (jdk != null) {
jdk.setClasspath(sdk.getPaths());
}
else {
LOG.info("Failed to load SDK " + sdk.getName() + ", type: " + sdk.getTypeName());
}
}
else {
final Library lib = project.createGlobalLibrary(library.getName(), fakeClosure);
if (lib != null) {
lib.setClasspath(library.getPaths());
}
else {
LOG.info("Failed to load global library " + library.getName());
}
}
}
final File projectFile = new File(projectPath);
//String root = dirBased ? projectPath : projectFile.getParent();
final String loadPath = isDirectoryBased(projectFile) ? new File(projectFile, IDEA_PROJECT_DIRNAME).getPath() : projectPath;
IdeaProjectLoader.loadFromPath(project, loadPath, myPathVars, null, new SystemOutErrorReporter(false));
final String globalEncoding = myGlobalEncoding;
if (globalEncoding != null && project.getProjectCharset() == null) {
project.setProjectCharset(globalEncoding);
}
project.getIgnoredFilePatterns().loadFromString(myIgnorePatterns);
return project;
}
finally {
final long loadTime = System.currentTimeMillis() - start;
LOG.info("Project " + projectPath + " loaded in " + loadTime + " ms");
}
}
private static boolean isDirectoryBased(File projectFile) {
return !(projectFile.isFile() && projectFile.getName().endsWith(".ipr"));
}
private static CompileScope createCompilationScope(BuildType buildType, ProjectDescriptor pd, Set<String> modules, Collection<String> artifactNames, Collection<String> paths) throws Exception {
Set<Artifact> artifacts = new HashSet<Artifact>();
if (artifactNames.isEmpty() && buildType == BuildType.PROJECT_REBUILD) {
artifacts.addAll(pd.project.getArtifacts().values());
}
else {
final Map<String, Artifact> artifactMap = pd.project.getArtifacts();
for (String name : artifactNames) {
final Artifact artifact = artifactMap.get(name);
if (artifact != null && !StringUtil.isEmpty(artifact.getOutputPath())) {
artifacts.add(artifact);
}
}
}
final CompileScope compileScope;
if (buildType == BuildType.PROJECT_REBUILD || (modules.isEmpty() && paths.isEmpty())) {
compileScope = new AllProjectScope(pd.project, artifacts, buildType != BuildType.MAKE);
}
else {
final Set<Module> forcedModules;
if (!modules.isEmpty()) {
forcedModules = new HashSet<Module>();
for (Module m : pd.project.getModules().values()) {
if (modules.contains(m.getName())) {
forcedModules.add(m);
}
}
}
else {
forcedModules = Collections.emptySet();
}
final TimestampStorage tsStorage = pd.timestamps.getStorage();
final Map<Module, Set<File>> filesToCompile;
if (!paths.isEmpty()) {
filesToCompile = new HashMap<Module, Set<File>>();
for (String path : paths) {
final File file = new File(path);
final RootDescriptor rd = pd.rootsIndex.getModuleAndRoot(file);
if (rd != null) {
Set<File> files = filesToCompile.get(rd.module);
if (files == null) {
files = new HashSet<File>();
filesToCompile.put(rd.module, files);
}
files.add(file);
if (buildType == BuildType.FORCED_COMPILATION) {
pd.fsState.markDirty(file, rd, tsStorage);
}
}
}
}
else {
filesToCompile = Collections.emptyMap();
}
if (filesToCompile.isEmpty()) {
compileScope = new ModulesScope(pd.project, forcedModules, artifacts, buildType != BuildType.MAKE);
}
else {
compileScope = new ModulesAndFilesScope(pd.project, forcedModules, filesToCompile, artifacts, buildType != BuildType.MAKE);
}
}
return compileScope;
}
private static BuildType convertCompileType(CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.Type compileType) {
switch (compileType) {
case CLEAN: return BuildType.CLEAN;
case MAKE: return BuildType.MAKE;
case REBUILD: return BuildType.PROJECT_REBUILD;
case FORCED_COMPILATION: return BuildType.FORCED_COMPILATION;
}
return BuildType.MAKE; // use make by default
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* 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.
@@ -133,28 +133,34 @@ public class DaemonTooltipRendererProvider implements ErrorStripTooltipRendererP
@Override
protected boolean dressDescription(@NotNull final Editor editor) {
final String[] problems = UIUtil.getHtmlBody(myText).split(BORDER_LINE);
final List<String> problems = StringUtil.split(UIUtil.getHtmlBody(myText), BORDER_LINE);
String text = "";
for (String problem : problems) {
final String ref = getLinkRef(problem);
if (ref != null) {
String description = TooltipLinkHandlerEP.getDescription(ref, editor);
if (description != null) {
final Pattern pattern = Pattern.compile(".*Use.*(the (panel|checkbox|checkboxes|field|button|controls).*below).*", Pattern.DOTALL);
final Matcher matcher = pattern.matcher(description);
int startFindIdx = 0;
while (matcher.find(startFindIdx)) {
final int end = matcher.end(1);
startFindIdx = end;
description = description.substring(0, matcher.start(1)) + " inspection settings " + description.substring(end);
description = UIUtil.getHtmlBody(description);
final int descriptionEnd = description.indexOf("<!-- tooltip end -->");
if (descriptionEnd < 0) {
final Pattern pattern = Pattern.compile(".*Use.*(the (panel|checkbox|checkboxes|field|button|controls).*below).*", Pattern.DOTALL);
final Matcher matcher = pattern.matcher(description);
int startFindIdx = 0;
while (matcher.find(startFindIdx)) {
final int end = matcher.end(1);
startFindIdx = end;
description = description.substring(0, matcher.start(1)) + " inspection settings " + description.substring(end);
}
} else {
description = description.substring(0, descriptionEnd);
}
text += UIUtil.getHtmlBody(problem).replace(DaemonBundle.message("inspection.extended.description"),
DaemonBundle.message("inspection.collapse.description")) +
BORDER_LINE + UIUtil.getHtmlBody(description) + BORDER_LINE;
BORDER_LINE + description + BORDER_LINE;
}
}
}
if (text.length() > 0) { //otherwise do not change anything
if (!text.isEmpty()) { //otherwise do not change anything
myText = "<html><body>" + StringUtil.trimEnd(text, BORDER_LINE) + "</body></html>";
return true;
}
@@ -17,11 +17,14 @@ package com.intellij.codeInsight.lookup.impl;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.ui.HeavyweightHint;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
/**
* @author Konstantin Bulenkov
@@ -36,6 +39,17 @@ public class CompletionExtender extends HeavyweightHint {
myElement = element;
myLookup = lookup;
myIndex = myLookup.getList().getSelectedIndex();
myLookup.getComponent().addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
recalculateLocation();
}
@Override
public void componentMoved(ComponentEvent e) {
recalculateLocation();
}
});
}
public LookupElement getLookupElement() {
@@ -74,6 +88,18 @@ public class CompletionExtender extends HeavyweightHint {
return false;
}
void recalculateLocation() {
if (!isVisible()) return;
final JList list = myLookup.getList();
final Point p = list.getLocationOnScreen();
p.y += list.indexToLocation(list.getSelectedIndex()).y;
final JComponent rootPane = UIUtil.getRootPane(myLookup.getEditor().getContentComponent());
if (rootPane != null) {
SwingUtilities.convertPointFromScreen(p, rootPane);
setLocation(new RelativePoint(rootPane, p));
}
}
@Override
public void hide() {
super.hide();
@@ -20,6 +20,7 @@ import com.intellij.codeInspection.GlobalInspectionContext;
import com.intellij.codeInspection.InspectionEP;
import com.intellij.codeInspection.InspectionManager;
import com.intellij.codeInspection.reference.RefEntity;
import com.intellij.codeInspection.reference.RefVisitor;
import com.intellij.codeInspection.ui.InspectionNode;
import com.intellij.codeInspection.ui.InspectionTreeNode;
import org.jdom.Element;
@@ -111,7 +112,7 @@ public class CommonInspectionToolWrapper extends InspectionToolWrapper<Inspectio
}
@Override
public void exportResults(@NotNull Element parentNode) {
getTool().exportResults(parentNode);
public void exportResults(@NotNull Element parentNode, RefEntity refEntity) {
getTool().exportResults(parentNode, refEntity);
}
}
@@ -20,7 +20,6 @@ import com.intellij.codeInspection.*;
import com.intellij.codeInspection.reference.RefElement;
import com.intellij.codeInspection.reference.RefEntity;
import com.intellij.codeInspection.reference.RefModule;
import com.intellij.codeInspection.reference.RefVisitor;
import com.intellij.codeInspection.ui.ProblemDescriptionNode;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.components.PathMacroManager;
@@ -105,7 +104,7 @@ public abstract class DescriptorProviderInspection extends InspectionTool implem
final File file = new File(fileName);
final CharArrayWriter writer = new CharArrayWriter();
if (!file.exists()) {
writer.append("<").append(InspectionsBundle.message("inspection.problems")).append(" is_local_tool=\"")
writer.append("<").append(InspectionsBundle.message("inspection.problems")).append(" " + GlobalInspectionContextImpl.LOCAL_TOOL_ATTRIBUTE + "=\"")
.append(Boolean.toString(this instanceof LocalInspectionToolWrapper)).append("\">\n");
}
for (Object o : list) {
@@ -263,19 +262,16 @@ public abstract class DescriptorProviderInspection extends InspectionTool implem
return myComposer;
}
public void exportResults(@NotNull final Element parentNode) {
getRefManager().iterate(new RefVisitor() {
@Override public void visitElement(final RefEntity refEntity) {
synchronized (lock) {
if (getProblemElements().containsKey(refEntity)) {
CommonProblemDescriptor[] descriptions = getDescriptions(refEntity);
if (descriptions != null) {
exportResults(descriptions, refEntity, parentNode);
}
}
@Override
public void exportResults(final @NotNull Element parentNode, RefEntity refEntity) {
synchronized (lock) {
if (getProblemElements().containsKey(refEntity)) {
CommonProblemDescriptor[] descriptions = getDescriptions(refEntity);
if (descriptions != null) {
exportResults(descriptions, refEntity, parentNode);
}
}
});
}
}
private void exportResults(@NotNull final CommonProblemDescriptor[] descriptions, final RefEntity refEntity, final Element parentNode) {
@@ -294,7 +290,7 @@ public abstract class DescriptorProviderInspection extends InspectionTool implem
ProblemHighlightType problemHighlightType = description instanceof ProblemDescriptor
? ((ProblemDescriptor)description).getHighlightType()
: ProblemHighlightType.GENERIC_ERROR_OR_WARNING;
final String attributeKey = getTextAttributeKey(refElement.getElement().getProject(), severity, problemHighlightType);
final String attributeKey = getTextAttributeKey(refElement.getRefManager().getProject(), severity, problemHighlightType);
problemClassElement.setAttribute("severity", severity.myName);
problemClassElement.setAttribute("attribute_key", attributeKey);
}
@@ -105,6 +105,7 @@ public class GlobalInspectionContextImpl extends UserDataHolderBase implements G
private final Map<String, Tools> myTools = new THashMap<String, Tools>();
private AnalysisUIOptions myUIOptions;
@NonNls static final String LOCAL_TOOL_ATTRIBUTE = "is_local_tool";
public GlobalInspectionContextImpl(Project project, NotNullLazyValue<ContentManager> contentManager) {
myProject = project;
@@ -296,44 +297,68 @@ public class GlobalInspectionContextImpl extends UserDataHolderBase implements G
public void run() {
performInspectionsWithProgress(scope, manager);
@NonNls final String ext = ".xml";
final Map<Element, Tools> globalTools = new HashMap<Element, Tools>();
for (Map.Entry<String,Tools> stringSetEntry : myTools.entrySet()) {
final Element root = new Element(InspectionsBundle.message("inspection.problems"));
final Document doc = new Document(root);
final Tools sameTools = stringSetEntry.getValue();
boolean hasProblems = false;
boolean isLocalTool = false;
String toolName = stringSetEntry.getKey();
if (sameTools != null) {
for (ScopeToolState toolDescr : sameTools.getTools()) {
final InspectionTool tool = (InspectionTool)toolDescr.getTool();
if (tool instanceof LocalInspectionToolWrapper) {
hasProblems = new File(outputPath, toolName + ext).exists();
isLocalTool = true;
}
else {
tool.updateContent();
if (tool.hasReportedProblems()) {
hasProblems = true;
tool.exportResults(root);
final Element root = new Element(InspectionsBundle.message("inspection.problems"));
globalTools.put(root, sameTools);
LOG.assertTrue(!hasProblems, toolName);
break;
}
}
}
}
if (!hasProblems) continue;
@NonNls final String isLocalToolAttribute = "is_local_tool";
root.setAttribute(isLocalToolAttribute, String.valueOf(isLocalTool));
try {
new File(outputPath).mkdirs();
final File file = new File(outputPath, toolName + ext);
inspectionsResults.add(file);
if (isLocalTool) {
FileUtil.writeToFile(file, ("</" + InspectionsBundle.message("inspection.problems") + ">").getBytes("UTF-8"), true);
}
else {
PathMacroManager.getInstance(getProject()).collapsePaths(doc.getRootElement());
JDOMUtil.writeDocument(doc, file, "\n");
FileUtil.writeToFile(file, ("</" + InspectionsBundle.message("inspection.problems") + ">").getBytes("UTF-8"), true);
}
catch (IOException e) {
LOG.error(e);
}
}
getRefManager().iterate(new RefVisitor() {
@Override
public void visitElement(final RefEntity refEntity) {
for (Element element : globalTools.keySet()) {
final Tools tools = globalTools.get(element);
for (ScopeToolState state : tools.getTools()) {
try {
((InspectionTool)state.getTool()).exportResults(element, refEntity);
}
catch (Exception e) {
LOG.error("Problem when exporting: " + refEntity.getExternalName(), e);
}
}
}
}
});
for (Element element : globalTools.keySet()) {
final String toolName = globalTools.get(element).getShortName();
element.setAttribute(LOCAL_TOOL_ATTRIBUTE, Boolean.toString(false));
final Document doc = new Document(element);
PathMacroManager.getInstance(getProject()).collapsePaths(doc.getRootElement());
try {
new File(outputPath).mkdirs();
final File file = new File(outputPath, toolName + ext);
inspectionsResults.add(file);
JDOMUtil.writeDocument(doc, file, "\n");
}
catch (IOException e) {
LOG.error(e);
}
@@ -29,10 +29,7 @@ import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
import com.intellij.codeInsight.daemon.impl.SeverityRegistrar;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInspection.*;
import com.intellij.codeInspection.reference.RefElement;
import com.intellij.codeInspection.reference.RefEntity;
import com.intellij.codeInspection.reference.RefManager;
import com.intellij.codeInspection.reference.RefModule;
import com.intellij.codeInspection.reference.*;
import com.intellij.codeInspection.ui.InspectionNode;
import com.intellij.codeInspection.ui.InspectionTreeNode;
import com.intellij.lang.annotation.HighlightSeverity;
@@ -69,7 +66,16 @@ public abstract class InspectionTool extends InspectionProfileEntry {
public abstract void runInspection(@NotNull AnalysisScope scope, @NotNull InspectionManager manager);
public abstract void exportResults(@NotNull Element parentNode);
public void exportResults(@NotNull final Element parentNode) {
getRefManager().iterate(new RefVisitor(){
@Override
public void visitElement(RefEntity elem) {
exportResults(parentNode, elem);
}
});
}
public abstract void exportResults(@NotNull Element parentNode, RefEntity refEntity);
public abstract boolean isGraphNeeded();
@Nullable
@@ -162,7 +168,7 @@ public abstract class InspectionTool extends InspectionProfileEntry {
}
protected HighlightSeverity getCurrentSeverity(RefElement element) {
final PsiElement psiElement = element.getElement();
final PsiElement psiElement = element.getPointer().getContainingFile();
if (psiElement != null) {
if (myContext != null) {
final Tools tools = myContext.getTools().get(getShortName());
@@ -78,6 +78,7 @@ com.siyeh.ig.classlayout.EmptyClassInspection
com.siyeh.ig.classlayout.InnerClassOnInterfaceInspection
com.siyeh.ig.classlayout.ListenerMayUseAdapterInspection
com.siyeh.ig.classlayout.MissingOverrideAnnotationInspection
com.siyeh.ig.classlayout.UtilityClassInspection
com.siyeh.ig.classlayout.UtilityClassWithoutPrivateConstructorInspection
com.siyeh.ig.classmetrics.AnonymousClassComplexityInspection
com.siyeh.ig.classmetrics.AnonymousClassMethodCountInspection
@@ -439,7 +439,17 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable,
if (!(settings.getConfiguration() instanceof UnknownRunConfiguration)) {
final List<BeforeRunTask> tasks = getBeforeRunTasks(settings.getConfiguration());
final Element methodsElement = new Element(METHOD);
Map<Key<BeforeRunTask>,BeforeRunTask> templateTasks = null;
if (!settings.isTemplate()) {
List<BeforeRunTask> beforeRunTasks = getBeforeRunTasks(getConfigurationTemplate(settings.getFactory()).getConfiguration());
templateTasks = new HashMap<Key<BeforeRunTask>, BeforeRunTask>();
for (BeforeRunTask task : beforeRunTasks) {
templateTasks.put(task.getProviderId(), task);
}
}
for (BeforeRunTask task : tasks) {
if (templateTasks != null && task.equals(templateTasks.get(task.getProviderId())))
continue; // not neccesary saving if the task is the same as template
final Element child = new Element(OPTION);
child.setAttribute(NAME_ATTR, task.getProviderId().toString());
task.writeExternal(child);
@@ -793,7 +803,11 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable,
@NotNull
@Override
public <T extends BeforeRunTask> List<T> getBeforeRunTasks(RunConfiguration settings, Key<T> taskProviderID) {
List<BeforeRunTask> tasks = getBeforeRunTasks(settings);
List<BeforeRunTask> tasks = myConfigurationToBeforeTasksMap.get(settings);
if (tasks == null) {
tasks = getBeforeRunTasks(settings);
myConfigurationToBeforeTasksMap.put(settings, tasks);
}
List<T> result = new ArrayList<T>();
for (BeforeRunTask task : tasks) {
if (task.getProviderId() == taskProviderID)
@@ -859,7 +873,20 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable,
}
public final void setBeforeRunTasks(final RunConfiguration runConfiguration, List<BeforeRunTask> tasks) {
myConfigurationToBeforeTasksMap.put(runConfiguration, tasks);
List<BeforeRunTask> templates = getBeforeRunTasks(runConfiguration);//here may be some disabled templates
Set<Key<BeforeRunTask>> idsToSet = new HashSet<Key<BeforeRunTask>>();
List<BeforeRunTask> result = new ArrayList<BeforeRunTask>(tasks);
for (BeforeRunTask task : tasks) {
idsToSet.add(task.getProviderId());
}
int i = 0;
for (BeforeRunTask template : templates) {
if (!idsToSet.contains(template.getProviderId())) {
result.add(i, template);
i++;
}
}
myConfigurationToBeforeTasksMap.put(runConfiguration, result);
fireBeforeRunTasksUpdated();
}
@@ -39,13 +39,13 @@ public class CloneElementAction extends CopyElementAction {
}
protected void updateForToolWindow(String id, DataContext dataContext,Presentation presentation) {
if (!ToolWindowId.COMMANDER.equals(id)) {
presentation.setVisible(false);
return;
}
// work only with single selection
PsiElement[] elements = LangDataKeys.PSI_ELEMENT_ARRAY.getData(dataContext);
presentation.setEnabled(elements != null && elements.length == 1 && CopyHandler.canClone(elements));
presentation.setVisible(true);
if (!ToolWindowId.COMMANDER.equals(id)) {
presentation.setVisible(false);
}
}
}
@@ -34,6 +34,13 @@ public class InspectionsConfigTreeComparator implements Comparator<InspectionCon
if (userObject1 instanceof String && userObject2 instanceof String) {
s1 = (String)userObject1;
s2 = (String)userObject2;
} else {
if (userObject1 instanceof String) return -1;
if (userObject2 instanceof String) return 1;
}
if (s1 != null) {
return getDisplayTextToSort(s1).compareToIgnoreCase(getDisplayTextToSort(s2));
}
final Descriptor descriptor1 = o1.getDesriptor();
@@ -62,7 +62,7 @@ public class CopyHandler {
if (elements.length > 0) {
final CopyHandlerDelegate[] copyHandlers = Extensions.getExtensions(CopyHandlerDelegate.EP_NAME);
for (CopyHandlerDelegate delegate : copyHandlers) {
if (delegate.canCopy(elements)) {
if (delegate instanceof CopyHandlerDelegateBase ? ((CopyHandlerDelegateBase)delegate).canCopy(elements, true) : delegate.canCopy(elements)) {
if (delegate instanceof CopyHandlerDelegateBase && ((CopyHandlerDelegateBase)delegate).forbidToClone(elements, true)){
return false;
}
@@ -34,6 +34,7 @@ import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import org.jetbrains.annotations.NonNls;
import java.io.File;
import java.util.ArrayList;
public class Tool implements SchemeElement {
@@ -300,7 +301,15 @@ public class Tool implements SchemeElement {
commandLine.setWorkDirectory(MacroManager.getInstance().expandMacrosInString(workingDir, false, dataContext));
exePath = MacroManager.getInstance().expandMacrosInString(exePath, false, dataContext);
if (exePath == null) return null;
commandLine.setExePath(exePath);
File exeFile = new File(exePath);
if (exeFile.isDirectory() && exeFile.getName().endsWith(".app")) {
commandLine.setExePath("open");
commandLine.getParametersList().prependAll("-a", exePath);
}
else {
commandLine.setExePath(exePath);
}
}
catch (Macro.ExecutionCancelledException e) {
return null;
@@ -21,9 +21,10 @@ import com.intellij.ide.macro.MacroManager;
import com.intellij.ide.macro.MacrosDialog;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.fileChooser.FileChooserFactory;
import com.intellij.openapi.fileChooser.PathChooserDialog;
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
@@ -34,6 +35,7 @@ import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.util.Consumer;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
@@ -42,6 +44,7 @@ import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.List;
public class ToolEditorDialog extends DialogWrapper {
private final JTextField myNameField = new JTextField();
@@ -179,7 +182,7 @@ public class ToolEditorDialog extends DialogWrapper {
}
private JPanel createCommandPane() {
JPanel pane = new JPanel(new GridBagLayout());
final JPanel pane = new JPanel(new GridBagLayout());
pane.setBorder(IdeBorderFactory.createTitledBorder(ToolsBundle.message("tools.tool.group"), true));
GridBagConstraints constr;
@@ -196,18 +199,24 @@ public class ToolEditorDialog extends DialogWrapper {
browseCommandButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor();
VirtualFile file = FileChooser.chooseFile(descriptor, myProject, null);
if (file != null) {
myTfCommand.setText(file.getPresentableUrl());
String workingDirectory = myTfCommandWorkingDirectory.getText();
if (workingDirectory == null || workingDirectory.length() == 0){
VirtualFile parent = file.getParent();
if (parent != null && parent.isDirectory()) {
myTfCommandWorkingDirectory.setText(parent.getPresentableUrl());
FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFileOrExecutableAppDescriptor();
PathChooserDialog chooser = FileChooserFactory.getInstance().createPathChooser(descriptor, myProject, pane);
chooser.choose(null, new Consumer<List<VirtualFile>>() {
@Override
public void consume(List<VirtualFile> files) {
VirtualFile file = files.size() > 0 ? files.get(0) : null;
if (file != null) {
myTfCommand.setText(file.getPresentableUrl());
String workingDirectory = myTfCommandWorkingDirectory.getText();
if (workingDirectory == null || workingDirectory.length() == 0){
VirtualFile parent = file.getParent();
if (parent != null && parent.isDirectory()) {
myTfCommandWorkingDirectory.setText(parent.getPresentableUrl());
}
}
}
}
}
});
}
}
);
@@ -276,10 +285,17 @@ public class ToolEditorDialog extends DialogWrapper {
new ActionListener() {
public void actionPerformed(ActionEvent e) {
FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
VirtualFile file = FileChooser.chooseFile(descriptor, myProject, null);
if (file != null) {
myTfCommandWorkingDirectory.setText(file.getPresentableUrl());
}
PathChooserDialog chooser = FileChooserFactory.getInstance().createPathChooser(descriptor, myProject, pane);
chooser.choose(null, new Consumer<List<VirtualFile>>() {
@Override
public void consume(List<VirtualFile> files) {
VirtualFile file = files.size() > 0 ? files.get(0) : null;
if (file != null) {
myTfCommandWorkingDirectory.setText(file.getPresentableUrl());
}
}
});
}
}
);
@@ -463,4 +479,4 @@ public class ToolEditorDialog extends DialogWrapper {
if (s.length() == 0) return null;
return s.replace('/', File.separatorChar);
}
}
}
@@ -206,7 +206,7 @@ public class FileChooserDescriptor implements Cloneable {
@Nullable
public final VirtualFile getFileToSelect(VirtualFile file) {
if (file.isDirectory() && myChooseFolders) {
if (file.isDirectory() && (myChooseFolders || isFileSelectable(file))) {
return file;
}
boolean isJar = file.getFileType() == FileTypes.ARCHIVE;
@@ -16,6 +16,7 @@
package com.intellij.openapi.fileChooser;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.UIBundle;
@@ -39,6 +40,21 @@ public class FileChooserDescriptorFactory {
return new FileChooserDescriptor(true, false, false, false, false, false);
}
public static FileChooserDescriptor createSingleFileOrExecutableAppDescriptor() {
return new FileChooserDescriptor(true, false, false, false, false, false) {
@Override
public boolean isFileSelectable(VirtualFile file) {
if (super.isFileSelectable(file)) return true;
if (SystemInfo.isMac && file.isDirectory() && "app".equals(file.getExtension())) {
return true;
}
return false;
}
};
}
public static FileChooserDescriptor createSingleLocalFileDescriptor() {
return new FileChooserDescriptor(true, true, true, true, false, false);
}
@@ -41,6 +41,7 @@ import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.impl.WindowManagerImpl;
import com.intellij.ui.Splash;
import com.intellij.util.SystemProperties;
import com.intellij.util.messages.MessageBus;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
@@ -48,32 +49,36 @@ import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
@SuppressWarnings({"CallToPrintStackTrace"})
public class IdeaApplication {
@NonNls public static final String IDEA_IS_INTERNAL_PROPERTY = "idea.is.internal";
private static final Logger LOG = Logger.getInstance("#com.intellij.idea.IdeaApplication");
private static IdeaApplication ourInstance;
protected final String[] myArgs;
private boolean myPerformProjectLoad = true;
private static IdeaApplication ourInstance;
private ApplicationStarter myStarter;
@NonNls public static final String IDEA_IS_INTERNAL_PROPERTY = "idea.is.internal";
public IdeaApplication(String[] args) {
LOG.assertTrue(ourInstance == null);
//noinspection AssignmentToStaticFieldFromInstanceMethod
ourInstance = this;
myArgs = args;
boolean isInternal = Boolean.valueOf(System.getProperty(IDEA_IS_INTERNAL_PROPERTY)).booleanValue();
if (Main.isCommandLine(args)) {
boolean headless = Main.isHeadless(args);
new CommandLineApplication(isInternal, false, headless);
if (!headless) patchSystem();
new CommandLineApplication(isInternal, false, headless);
}
else {
System.setProperty("sun.awt.noerasebackground","true");
patchSystem();
Splash splash = null;
if (myArgs.length == 0) {
@@ -90,16 +95,82 @@ public class IdeaApplication {
}
private static void patchSystem() {
System.setProperty("sun.awt.noerasebackground","true");
Toolkit.getDefaultToolkit().getSystemEventQueue().push(IdeEventQueue.getInstance());
if (Patches.SUN_BUG_ID_6209673) {
RepaintManager.setCurrentManager(new IdeRepaintManager());
}
patchWM();
IconLoader.activate();
}
private static void patchWM() {
if (SystemProperties.getBooleanProperty("idea.skip.wm.patching", false)) return;
if (!"sun.awt.X11.XToolkit".equals(Toolkit.getDefaultToolkit().getClass().getName())) return;
try {
final Class<?> xwmClass = Class.forName("sun.awt.X11.XWM");
final Method getWM = xwmClass.getDeclaredMethod("getWM");
getWM.setAccessible(true);
final Object xwm = getWM.invoke(null);
if (xwm == null) return;
final Method getNetProtocol = xwmClass.getDeclaredMethod("getNETProtocol");
getNetProtocol.setAccessible(true);
final Object netProtocol = getNetProtocol.invoke(xwm);
if (netProtocol == null) return;
final Method getWMName = netProtocol.getClass().getDeclaredMethod("getWMName");
getWMName.setAccessible(true);
final String wmName = (String)getWMName.invoke(netProtocol);
if (wmName == null) return;
LOG.info("WM detected: " + wmName);
if ("Mutter".equals(wmName)) {
try {
xwmClass.getDeclaredField("MUTTER_WM");
}
catch (NoSuchFieldException e) {
setWM(xwm, "METACITY_WM"); // Mutter support absent - mimic Metacity
}
}
else if ("awesome".equals(wmName)) {
try {
xwmClass.getDeclaredField("OTHER_NONREPARENTING_WM");
if (System.getenv("_JAVA_AWT_WM_NONREPARENTING") == null) {
setWM(xwm, "OTHER_NONREPARENTING_WM"); // patch present but not activated
}
}
catch (NoSuchFieldException e) {
setWM(xwm, "LG3D_WM"); // patch absent - mimic LG3D
}
}
}
catch (Throwable e) {
LOG.warn(e);
}
}
private static void setWM(final Object xwm, final String wmConstant) throws NoSuchFieldException, IllegalAccessException {
final Field wm = xwm.getClass().getDeclaredField(wmConstant);
wm.setAccessible(true);
final Object id = wm.get(null);
if (id != null) {
final Field awtWmgr = xwm.getClass().getDeclaredField("awt_wmgr");
awtWmgr.setAccessible(true);
awtWmgr.set(null, id);
final Field wmID = xwm.getClass().getDeclaredField("WMID");
wmID.setAccessible(true);
wmID.set(xwm, id);
}
}
protected ApplicationStarter getStarter() {
if (myArgs.length > 0) {
final Application app = ApplicationManager.getApplication();
PluginManager.getPlugins();
ExtensionPoint<ApplicationStarter> point = Extensions.getRootArea().getExtensionPoint(ExtensionPoints.APPLICATION_STARTER);
@@ -224,6 +295,7 @@ public class IdeaApplication {
}
}
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
public void run() {
PluginManager.reportPluginError();
@@ -91,7 +91,7 @@ public class MarkupModelImpl extends UserDataHolderBase implements MarkupModelEx
return addRangeHighlighterAndChangeAttributes(offset, offset, layer, textAttributes, HighlighterTargetArea.LINES_IN_RANGE, true, null);
}
static int getFirstNonspaceCharOffset(@NotNull Document doc, int lineNumber) {
private static int getFirstNonspaceCharOffset(@NotNull Document doc, int lineNumber) {
int lineStart = doc.getLineStartOffset(lineNumber);
int lineEnd = doc.getLineEndOffset(lineNumber);
CharSequence text = doc.getCharsSequence();
@@ -430,12 +430,17 @@ public class EditorWindow {
else if (myTabbedPane != null) {
final boolean focusEditor = ToolWindowManager.getInstance(getManager().getProject()).isEditorComponentActive();
final VirtualFile currentFile = getSelectedFile();
if (currentFile != null) {
// do not close associated language console on tab placement change
currentFile.putUserData(FileEditorManagerImpl.CLOSING_TO_REOPEN, Boolean.TRUE);
}
final VirtualFile[] files = getFiles();
for (VirtualFile file : files) {
closeFile(file, false);
}
disposeTabs();
if (currentFile != null) {
currentFile.putUserData(FileEditorManagerImpl.CLOSING_TO_REOPEN, null);
getManager().openFileImpl2(this, currentFile, focusEditor && myOwner.getCurrentWindow() == this);
}
else {
@@ -134,23 +134,23 @@ public class VirtualFilePointerManagerImpl extends VirtualFilePointerManager imp
}
private static boolean startsWith(final String url, final String pointerUrl) {
String urlSuffix = stripSuffix(url);
String pointerPrefix = stripToJarPrefix(pointerUrl);
if (urlSuffix.length() > 0) {
return Comparing.equal(stripToJarPrefix(url), pointerPrefix, SystemInfo.isFileSystemCaseSensitive) &&
StringUtil.startsWith(urlSuffix, stripSuffix(pointerUrl));
String urlSuffix = substringAfterJarSeparator(url);
String pointerPrefix = substringBeforeJarSeparator(pointerUrl);
if (!urlSuffix.isEmpty()) {
return Comparing.equal(substringBeforeJarSeparator(url), pointerPrefix, SystemInfo.isFileSystemCaseSensitive) &&
StringUtil.startsWith(urlSuffix, substringAfterJarSeparator(pointerUrl));
}
return FileUtil.startsWith(pointerPrefix, stripToJarPrefix(url));
return FileUtil.startsWith(pointerPrefix, substringBeforeJarSeparator(url));
}
private static String stripToJarPrefix(String url) {
private static String substringBeforeJarSeparator(String url) {
int separatorIndex = url.indexOf(JarFileSystem.JAR_SEPARATOR);
if (separatorIndex < 0) return url;
return url.substring(0, separatorIndex);
}
private static String stripSuffix(String url) {
private static String substringAfterJarSeparator(String url) {
int separatorIndex = url.indexOf(JarFileSystem.JAR_SEPARATOR);
if (separatorIndex < 0) return "";
return url.substring(separatorIndex + JarFileSystem.JAR_SEPARATOR.length());
@@ -28,6 +28,7 @@ import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.newvfs.*;
import com.intellij.openapi.vfs.newvfs.events.VFileEvent;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ConcurrentHashSet;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.text.CaseInsensitiveStringHashingStrategy;
@@ -76,11 +77,10 @@ public class JarFileSystemImpl extends JarFileSystem implements ApplicationCompo
String[] jarPaths;
synchronized (LOCK) {
if (jarPathsCache == null) {
Set<String> jarPathsSet = myHandlers.keySet();
jarPathsCache = jarPathsSet.toArray(new String[jarPathsSet.size()]);
}
jarPaths = jarPathsCache;
if (jarPaths == null) {
jarPathsCache = jarPaths = ArrayUtil.toStringArray(myHandlers.keySet());
}
}
for (String jarPath : jarPaths) {
@@ -15,16 +15,19 @@
*/
package com.intellij.openapi.wm.impl;
import com.intellij.ide.impl.ProjectUtil;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.wm.WindowManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
/**
* @ author Bas Leijdekkers
* This class is programmatically instantiated and registered when opening and closing projects
@@ -115,7 +118,15 @@ public class ProjectWindowAction extends ToggleAction implements DumbAware {
if (project == null) {
return;
}
ProjectUtil.focusProjectWindow(project, true);
final JFrame projectFrame = WindowManager.getInstance().getFrame(project);
final int frameState = projectFrame.getExtendedState();
if ((frameState & Frame.ICONIFIED) == Frame.ICONIFIED) {
// restore the frame if it is minimized
projectFrame.setExtendedState(frameState ^ Frame.ICONIFIED);
}
projectFrame.toFront();
projectFrame.requestFocus();
//ProjectUtil.focusProjectWindow(project, true);
}
@Override
@@ -1970,4 +1970,5 @@ ambiguous.field.access.hides.parameter.problem.descriptor=Field <code>#ref</code
ambiguous.field.access.hides.field.problem.descriptor=Field <code>#ref</code> from super class ''{0}'' accessed, while field access from surrounding class might be expected #loc
ambiguous.field.access.quickfix=Qualify field access with 'super.'
string.builder.replaceable.by.string.quickfix=Replace 'StringBuilder' with 'String'
string.buffer.replaceable.by.string.quickfix=Replace 'StringBuffer' with 'String'
string.buffer.replaceable.by.string.quickfix=Replace 'StringBuffer' with 'String'
add.0.to.ignore.if.annotated.by.list.quickfix=Add ''{0}'' to ''Ignore if annotated by'' list
@@ -1,5 +1,5 @@
/*
* Copyright 2003-2011 Dave Griffith, Bas Leijdekkers
* Copyright 2003-2012 Dave Griffith, Bas Leijdekkers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,14 +17,13 @@ package com.siyeh.ig.abstraction;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.codeInspection.util.SpecialAnnotationsUtil;
import com.intellij.psi.CommonClassNames;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiModifier;
import com.intellij.psi.*;
import com.intellij.util.ui.CheckBox;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.fixes.AddToIgnoreIfAnnotatedByListQuickFix;
import com.siyeh.ig.psiutils.LibraryUtil;
import com.siyeh.ig.psiutils.TestUtils;
import com.siyeh.ig.ui.ExternalizableStringSet;
@@ -57,14 +56,17 @@ public class PublicMethodNotExposedInInterfaceInspection
"public.method.not.in.interface.problem.descriptor");
}
@NotNull
@Override
protected InspectionGadgetsFix[] buildFixes(Object... infos) {
return AddToIgnoreIfAnnotatedByListQuickFix.build((PsiModifierListOwner)infos[0], ignorableAnnotations);
}
@Override
public JComponent createOptionsPanel() {
final JPanel panel = new JPanel(new GridBagLayout());
final JPanel annotationsListControl =
SpecialAnnotationsUtil.createSpecialAnnotationsListControl(
ignorableAnnotations,
InspectionGadgetsBundle.message(
"ignore.if.annotated.by"));
final JPanel annotationsListControl = SpecialAnnotationsUtil.createSpecialAnnotationsListControl(
ignorableAnnotations, InspectionGadgetsBundle.message("ignore.if.annotated.by"));
final GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
@@ -74,8 +76,7 @@ public class PublicMethodNotExposedInInterfaceInspection
constraints.fill = GridBagConstraints.BOTH;
panel.add(annotationsListControl, constraints);
final CheckBox checkBox = new CheckBox(InspectionGadgetsBundle.message(
"public.method.not.in.interface.option"),
this, "onlyWarnIfContainingClassImplementsAnInterface");
"public.method.not.in.interface.option"), this, "onlyWarnIfContainingClassImplementsAnInterface");
constraints.gridy = 1;
constraints.weighty = 0.0;
constraints.anchor = GridBagConstraints.WEST;
@@ -141,7 +142,7 @@ public class PublicMethodNotExposedInInterfaceInspection
if (TestUtils.isJUnitTestMethod(method)) {
return;
}
registerMethodError(method);
registerMethodError(method, method);
}
private boolean exposedInInterface(PsiMethod method) {
@@ -23,6 +23,8 @@ import com.intellij.util.ui.CheckBox;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.fixes.AddToIgnoreIfAnnotatedByListQuickFix;
import com.siyeh.ig.ui.ExternalizableStringSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
@@ -87,6 +89,16 @@ public class EmptyClassInspection extends BaseInspection {
return panel;
}
@NotNull
@Override
protected InspectionGadgetsFix[] buildFixes(Object... infos) {
final Object info = infos[0];
if (!(info instanceof PsiModifierListOwner)) {
return InspectionGadgetsFix.EMPTY_ARRAY;
}
return AddToIgnoreIfAnnotatedByListQuickFix.build((PsiModifierListOwner)info, ignorableAnnotations);
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new EmptyClassVisitor();
@@ -1,5 +1,5 @@
/*
* Copyright 2003-2007 Dave Griffith, Bas Leijdekkers
* Copyright 2003-2012 Dave Griffith, Bas Leijdekkers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,31 +15,57 @@
*/
package com.siyeh.ig.classlayout;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.codeInspection.util.SpecialAnnotationsUtil;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiModifierListOwner;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.fixes.AddToIgnoreIfAnnotatedByListQuickFix;
import com.siyeh.ig.psiutils.UtilityClassUtil;
import com.siyeh.ig.ui.ExternalizableStringSet;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
public class UtilityClassInspection extends BaseInspection {
@SuppressWarnings({"PublicField"})
public final ExternalizableStringSet ignorableAnnotations = new ExternalizableStringSet();
@Override
@NotNull
public String getDisplayName() {
return InspectionGadgetsBundle.message("utility.class.display.name");
}
@Override
@NotNull
protected String buildErrorString(Object... infos) {
return InspectionGadgetsBundle.message(
"utility.class.problem.descriptor");
}
@NotNull
@Override
protected InspectionGadgetsFix[] buildFixes(Object... infos) {
return AddToIgnoreIfAnnotatedByListQuickFix.build((PsiModifierListOwner) infos[0], ignorableAnnotations);
}
@Override
public JComponent createOptionsPanel() {
return SpecialAnnotationsUtil.createSpecialAnnotationsListControl(
ignorableAnnotations, InspectionGadgetsBundle.message("ignore.if.annotated.by"));
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new UtilityClassVisitor();
}
private static class UtilityClassVisitor extends BaseInspectionVisitor {
private class UtilityClassVisitor extends BaseInspectionVisitor {
@Override
public void visitClass(@NotNull PsiClass aClass) {
@@ -47,7 +73,10 @@ public class UtilityClassInspection extends BaseInspection {
if (!UtilityClassUtil.isUtilityClass(aClass)) {
return;
}
registerClassError(aClass);
if (AnnotationUtil.isAnnotated(aClass, ignorableAnnotations)) {
return;
}
registerClassError(aClass, aClass);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2003-2010 Dave Griffith, Bas Leijdekkers
* Copyright 2003-2012 Dave Griffith, Bas Leijdekkers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,8 +15,9 @@
*/
package com.siyeh.ig.classlayout;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel;
import com.intellij.codeInspection.util.SpecialAnnotationsUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.*;
@@ -27,25 +28,32 @@ import com.intellij.psi.search.searches.ClassInheritorsSearch;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Query;
import com.intellij.util.ui.CheckBox;
import com.siyeh.HardcodedMethodConstants;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.fixes.AddToIgnoreIfAnnotatedByListQuickFix;
import com.siyeh.ig.psiutils.UtilityClassUtil;
import com.siyeh.ig.ui.ExternalizableStringSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class UtilityClassWithoutPrivateConstructorInspection
extends BaseInspection {
/**
* @noinspection PublicField for externalization
*/
@SuppressWarnings({"PublicField"})
public boolean ignoreClassesWithOnlyMain = false;
@SuppressWarnings({"PublicField"})
public final ExternalizableStringSet ignorableAnnotations = new ExternalizableStringSet();
@Override
@NotNull
public String getDisplayName() {
@@ -63,30 +71,34 @@ public class UtilityClassWithoutPrivateConstructorInspection
@Override
@Nullable
public JComponent createOptionsPanel() {
return new SingleCheckboxOptionsPanel(InspectionGadgetsBundle.message(
"utility.class.without.private.constructor.option"), this,
"ignoreClassesWithOnlyMain");
final JPanel panel = new JPanel(new BorderLayout());
final JPanel annotationsPanel = SpecialAnnotationsUtil.createSpecialAnnotationsListControl(
ignorableAnnotations, InspectionGadgetsBundle.message("ignore.if.annotated.by"));
panel.add(annotationsPanel, BorderLayout.CENTER);
final CheckBox checkBox = new CheckBox(InspectionGadgetsBundle.message("utility.class.without.private.constructor.option"),
this, "ignoreClassesWithOnlyMain");
panel.add(checkBox, BorderLayout.SOUTH);
return panel;
}
@NotNull
@Override
protected InspectionGadgetsFix buildFix(Object... infos) {
protected InspectionGadgetsFix[] buildFixes(Object... infos) {
final List<InspectionGadgetsFix> fixes = new ArrayList();
final PsiClass aClass = (PsiClass)infos[0];
final PsiMethod constructor = getNullArgConstructor(aClass);
if (constructor == null) {
return new CreateEmptyPrivateConstructor();
fixes.add(new CreateEmptyPrivateConstructor());
}
else {
final Query<PsiReference> query =
ReferencesSearch.search(constructor,
constructor.getUseScope());
final Query<PsiReference> query = ReferencesSearch.search(constructor, constructor.getUseScope());
final PsiReference reference = query.findFirst();
if (reference == null) {
return new MakeConstructorPrivateFix();
}
else {
return null;
fixes.add(new MakeConstructorPrivateFix());
}
}
AddToIgnoreIfAnnotatedByListQuickFix.build(aClass, ignorableAnnotations, fixes);
return fixes.toArray(new InspectionGadgetsFix[fixes.size()]);
}
private static class CreateEmptyPrivateConstructor
@@ -131,14 +143,12 @@ public class UtilityClassWithoutPrivateConstructorInspection
final PsiModifierList modifierList = constructor.getModifierList();
modifierList.setModifierProperty(PsiModifier.PRIVATE, true);
aClass.add(constructor);
final CodeStyleManager styleManager =
CodeStyleManager.getInstance(project);
final CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
styleManager.reformat(constructor);
}
}
private static class MakeConstructorPrivateFix
extends InspectionGadgetsFix {
private static class MakeConstructorPrivateFix extends InspectionGadgetsFix {
@NotNull
public String getName() {
@@ -154,13 +164,11 @@ public class UtilityClassWithoutPrivateConstructorInspection
if (aClass == null) {
return;
}
final PsiMethod[] constructurs = aClass.getConstructors();
for (final PsiMethod constructor : constructurs) {
final PsiParameterList parameterList =
constructor.getParameterList();
final PsiMethod[] constructors = aClass.getConstructors();
for (final PsiMethod constructor : constructors) {
final PsiParameterList parameterList = constructor.getParameterList();
if (parameterList.getParametersCount() == 0) {
final PsiModifierList modifiers =
constructor.getModifierList();
final PsiModifierList modifiers = constructor.getModifierList();
modifiers.setModifierProperty(PsiModifier.PUBLIC, false);
modifiers.setModifierProperty(PsiModifier.PROTECTED, false);
modifiers.setModifierProperty(PsiModifier.PRIVATE, true);
@@ -174,8 +182,7 @@ public class UtilityClassWithoutPrivateConstructorInspection
return new UtilityClassWithoutPrivateConstructorVisitor();
}
private class UtilityClassWithoutPrivateConstructorVisitor
extends BaseInspectionVisitor {
private class UtilityClassWithoutPrivateConstructorVisitor extends BaseInspectionVisitor {
@Override
public void visitClass(@NotNull PsiClass aClass) {
@@ -192,10 +199,11 @@ public class UtilityClassWithoutPrivateConstructorInspection
if (hasPrivateConstructor(aClass)) {
return;
}
final SearchScope scope =
GlobalSearchScope.projectScope(aClass.getProject());
final Query<PsiClass> query =
ClassInheritorsSearch.search(aClass, scope, true, true);
if (AnnotationUtil.isAnnotated(aClass, ignorableAnnotations)) {
return;
}
final SearchScope scope = GlobalSearchScope.projectScope(aClass.getProject());
final Query<PsiClass> query = ClassInheritorsSearch.search(aClass, scope, true, true);
final PsiClass subclass = query.findFirst();
if (subclass != null) {
return;
@@ -229,8 +237,7 @@ public class UtilityClassWithoutPrivateConstructorInspection
if (!PsiType.VOID.equals(returnType)) {
return false;
}
final PsiParameterList parameterList =
method.getParameterList();
final PsiParameterList parameterList = method.getParameterList();
if (parameterList.getParametersCount() != 1) {
return false;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2003-2011 Dave Griffith, Bas Leijdekkers
* Copyright 2003-2012 Dave Griffith, Bas Leijdekkers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,6 +23,7 @@ import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.fixes.AddToIgnoreIfAnnotatedByListQuickFix;
import com.siyeh.ig.fixes.EncapsulateVariableFix;
import com.siyeh.ig.psiutils.ClassUtils;
import com.siyeh.ig.ui.ExternalizableStringSet;
@@ -31,6 +32,8 @@ import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class PublicFieldInspection extends BaseInspection {
@@ -66,10 +69,14 @@ public class PublicFieldInspection extends BaseInspection {
return panel;
}
@NotNull
@Override
protected InspectionGadgetsFix buildFix(Object... infos) {
protected InspectionGadgetsFix[] buildFixes(Object... infos) {
final List<InspectionGadgetsFix> fixes = new ArrayList();
final PsiField field = (PsiField)infos[0];
return new EncapsulateVariableFix(field.getName());
fixes.add(new EncapsulateVariableFix(field.getName()));
AddToIgnoreIfAnnotatedByListQuickFix.build(field, ignorableAnnotations, fixes);
return fixes.toArray(new InspectionGadgetsFix[fixes.size()]);
}
@Override
@@ -0,0 +1,76 @@
/*
* 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.siyeh.ig.fixes;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInspection.util.SpecialAnnotationsUtil;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.PsiModifierList;
import com.intellij.psi.PsiModifierListOwner;
import com.intellij.util.Processor;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.DelegatingFix;
import com.siyeh.ig.InspectionGadgetsFix;
import org.jetbrains.annotations.NonNls;
import java.util.ArrayList;
import java.util.List;
/**
* @author Bas Leijdekkers
*/
public class AddToIgnoreIfAnnotatedByListQuickFix {
private AddToIgnoreIfAnnotatedByListQuickFix() {}
public static InspectionGadgetsFix[] build(PsiModifierListOwner modifierListOwner, List<String> configurationList) {
final List<InspectionGadgetsFix> fixes = build(modifierListOwner, configurationList, new ArrayList());
return fixes.isEmpty() ? InspectionGadgetsFix.EMPTY_ARRAY : fixes.toArray(new InspectionGadgetsFix[fixes.size()]);
}
public static List<InspectionGadgetsFix> build(final PsiModifierListOwner modifierListOwner,
final List<String> configurationList,
final List<InspectionGadgetsFix> fixes) {
processAnnotationTexts(modifierListOwner, new Processor<String>() {
@Override
public boolean process(String annotationText) {
fixes.add(new DelegatingFix(SpecialAnnotationsUtil.createAddToSpecialAnnotationsListQuickFix(
InspectionGadgetsBundle.message("add.0.to.ignore.if.annotated.by.list.quickfix", annotationText),
QuickFixBundle.message("fix.add.special.annotation.family"),
configurationList, annotationText, modifierListOwner)));
return true;
}
});
return fixes;
}
private static void processAnnotationTexts(final PsiModifierListOwner owner, final Processor<String> processor) {
final PsiModifierList modifierList = owner.getModifierList();
if (modifierList == null) {
return;
}
final PsiAnnotation[] annotations = modifierList.getAnnotations();
for (PsiAnnotation annotation : annotations) {
@NonNls final String text = annotation.getText();
if (text.startsWith("java.") || text.startsWith("javax.") || text.startsWith("org.jetbrains.")) {
continue;
}
if (!processor.process(text)) {
break;
}
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2003-2011 Dave Griffith, Bas Leijdekkers
* Copyright 2003-2012 Dave Griffith, Bas Leijdekkers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,6 +26,8 @@ import com.intellij.util.ui.CheckBox;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.fixes.AddToIgnoreIfAnnotatedByListQuickFix;
import com.siyeh.ig.psiutils.ClassUtils;
import com.siyeh.ig.psiutils.UninitializedReadCollector;
import org.jdom.Element;
@@ -39,8 +41,7 @@ import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.List;
public class InstanceVariableUninitializedUseInspection
extends BaseInspection {
public class InstanceVariableUninitializedUseInspection extends BaseInspection {
/**
* @noinspection PublicField
@@ -94,10 +95,8 @@ public class InstanceVariableUninitializedUseInspection
public JComponent createOptionsPanel() {
final JComponent panel = new JPanel(new GridBagLayout());
final JPanel annotationsPanel =
SpecialAnnotationsUtil.createSpecialAnnotationsListControl(
annotationNames, InspectionGadgetsBundle.message(
"ignore.if.annotated.by"));
final JPanel annotationsPanel = SpecialAnnotationsUtil.createSpecialAnnotationsListControl(
annotationNames, InspectionGadgetsBundle.message("ignore.if.annotated.by"));
final CheckBox checkBox = new CheckBox(InspectionGadgetsBundle.message(
"primitive.fields.ignore.option"), this, "m_ignorePrimitives");
@@ -117,13 +116,19 @@ public class InstanceVariableUninitializedUseInspection
return panel;
}
@NotNull
@Override
protected InspectionGadgetsFix[] buildFixes(Object... infos) {
final PsiField field = (PsiField)infos[0];
return AddToIgnoreIfAnnotatedByListQuickFix.build(field, annotationNames);
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new InstanceVariableInitializationVisitor();
}
private class InstanceVariableInitializationVisitor
extends BaseInspectionVisitor {
private class InstanceVariableInitializationVisitor extends BaseInspectionVisitor {
@Override
public void visitField(@NotNull PsiField field) {
@@ -133,8 +138,7 @@ public class InstanceVariableUninitializedUseInspection
if (field.getInitializer() != null) {
return;
}
final PsiAnnotation annotation =
AnnotationUtil.findAnnotation(field, annotationNames);
final PsiAnnotation annotation = AnnotationUtil.findAnnotation(field, annotationNames);
if (annotation != null) {
return;
}
@@ -154,26 +158,21 @@ public class InstanceVariableUninitializedUseInspection
return;
}
}
final UninitializedReadCollector uninitializedReadsCollector =
new UninitializedReadCollector();
if (!isInitializedInInitializer(field,
uninitializedReadsCollector)) {
final UninitializedReadCollector uninitializedReadsCollector = new UninitializedReadCollector();
if (!isInitializedInInitializer(field, uninitializedReadsCollector)) {
final PsiMethod[] constructors = aClass.getConstructors();
for (final PsiMethod constructor : constructors) {
final PsiCodeBlock body = constructor.getBody();
uninitializedReadsCollector.blockAssignsVariable(body,
field);
uninitializedReadsCollector.blockAssignsVariable(body, field);
}
}
final PsiExpression[] badReads =
uninitializedReadsCollector.getUninitializedReads();
final PsiExpression[] badReads = uninitializedReadsCollector.getUninitializedReads();
for (PsiExpression expression : badReads) {
registerError(expression);
registerError(expression, field);
}
}
private boolean isInitializedInInitializer(
@NotNull PsiField field,
private boolean isInitializedInInitializer(@NotNull PsiField field,
UninitializedReadCollector uninitializedReadsCollector) {
final PsiClass aClass = field.getContainingClass();
if (aClass == null) {
@@ -183,8 +182,7 @@ public class InstanceVariableUninitializedUseInspection
for (final PsiClassInitializer initializer : initializers) {
if (!initializer.hasModifierProperty(PsiModifier.STATIC)) {
final PsiCodeBlock body = initializer.getBody();
if (uninitializedReadsCollector.blockAssignsVariable(body,
field)) {
if (uninitializedReadsCollector.blockAssignsVariable(body, field)) {
return true;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2006-2011 Dave Griffith, Bas Leijdekkers
* Copyright 2006-2012 Dave Griffith, Bas Leijdekkers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,14 +23,15 @@ import com.intellij.psi.PsiField;
import com.intellij.psi.PsiModifier;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.fixes.AddToIgnoreIfAnnotatedByListQuickFix;
import com.siyeh.ig.psiutils.SerializationUtils;
import com.siyeh.ig.ui.ExternalizableStringSet;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
public class NonSerializableFieldInSerializableClassInspection
extends SerializableInspection {
public class NonSerializableFieldInSerializableClassInspection extends SerializableInspection {
@SuppressWarnings({"PublicField"})
public final ExternalizableStringSet ignorableAnnotations = new ExternalizableStringSet();
@@ -55,6 +56,13 @@ public class NonSerializableFieldInSerializableClassInspection
ignorableAnnotations, InspectionGadgetsBundle.message("ignore.if.annotated.by"))};
}
@NotNull
@Override
protected InspectionGadgetsFix[] buildFixes(Object... infos) {
final PsiField field = (PsiField)infos[0];
return AddToIgnoreIfAnnotatedByListQuickFix.build(field, ignorableAnnotations);
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new NonSerializableFieldInSerializableClassVisitor();
@@ -90,7 +98,7 @@ public class NonSerializableFieldInSerializableClassInspection
if (AnnotationUtil.isAnnotated(field, ignorableAnnotations)) {
return;
}
registerFieldError(field);
registerFieldError(field, field);
}
}
}
@@ -3,6 +3,7 @@
This inspection reports empty classes and Java files without any defined classes. A class is empty if it
doesn't have any fields, methods, constructors or initializers. Empty classes are often left over
after large changes or refactorings.
<!-- tooltip end -->
<p>
Use the list below to specify special annotations. Classes annotated with one of
these annotations will be ignored by this inspection.
@@ -2,10 +2,14 @@
<body>
This inspection reports reads of instance variables which are not yet initialized.
<p>
Use the checkbox below to indicate whether you want uninitialized primitive fields to be reported.
<p>
Note: This inspection uses a very conservative dataflow algorithm, and may report instance variables
as uninitialized incorrectly. Variables reported as initialized will always be initialized.
<!-- tooltip end -->
<p>
Use the list below to specify special annotations. Fields annotated with one of
these annotations will be ignored by this inspection.
<p>
Use the checkbox below to indicate whether you want uninitialized primitive fields to be reported.
<p>
<small>Powered by InspectionGadgets</small>
</body>
@@ -10,12 +10,16 @@ method. For purposes of this inspection, fields with
<b>java.util.Map</b> types are assumed to be
<b>Serializable</b>, unless the types
they are declared to contain are non-<b>Serializable</b>.
<!-- tooltip end -->
<p>
Use the table below to specify what specific classes and inheritors should be excluded
Use the first list below to specify what specific classes and inheritors should be excluded
from being checked by this inspection. This is meant for those classes which, although they inherit
Serializable from a superclass, are not intended for serialization. Such classes would lead this
inspection to report unnecessarily.
<p>
Use the second list below to specify special annotations. Fields annotated with one of
these annotations will be ignored by this inspection.
<p>
<small>Powered by InspectionGadgets</small>
</body>
</html>
@@ -2,6 +2,7 @@
<body>
This inspection reports <b>public</b> instance variables.
Constants (i.e. variables marked <b>static</b> and <b>final</b>) are not reported.
<!-- tooltip end -->
<p>
Use the list below to specify special annotations. Fields annotated with one of these annotations will be ignored by this inspection.
<p>
@@ -3,6 +3,7 @@
This inspection reports <b>public</b> methods in classes
which are not exposed as in interface. Exposing all <b>public</b> methods via interface is important for
maintaining loose coupling, and may be necessary for certain component-based programming styles.
<!-- tooltip end -->
<p>
Use the list below to specify special annotations. Methods annotated with one of
these annotations will be ignored by this inspection.
@@ -3,6 +3,10 @@
This inspection reports utility classes.
Utility classes have all fields and methods declared <b>static</b>, and their
presence may indicate a lack of object-oriented design.
<!-- tooltip end -->
<p>
Use the list below to specify special annotations. Classes annotated with one of
these annotations will be ignored by this inspection.
<p>
<small>Powered by InspectionGadgets</small>
</body>
@@ -3,6 +3,12 @@
This inspection reports utility classes which do not have <b>private</b> constructors.
Utility classes have all fields and methods declared <b>static</b>. Giving such classes a <b>private</b>
constructor prevents them from being inadvertently instantiated.
<!-- tooltip end -->
<p>
Use the list below to specify special annotations. Classes annotated with one of
these annotations will be ignored by this inspection.
<p>
Use the checkbox below to ignore classes which only have a main method and no other methods.
<p>
<small>Powered by InspectionGadgets</small>
</body>
@@ -26,14 +26,21 @@ import java.awt.*;
* @author Alexander Lobas
*/
public class CaptionStaticDecorator extends StaticDecorator {
private final Color myColor;
public CaptionStaticDecorator(RadComponent component) {
this(component, LightColors.GREEN);
}
public CaptionStaticDecorator(RadComponent component, Color color) {
super(component);
myColor = color;
}
@Override
protected void paint(DecorationLayer layer, Graphics2D g, RadComponent component) {
Rectangle bounds = component.getBounds(layer);
g.setColor(LightColors.GREEN);
g.setColor(myColor);
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
g.setColor(Color.black);
g.drawRect(bounds.x, bounds.y, bounds.width, bounds.height);
@@ -15,14 +15,13 @@
*/
package com.intellij.android.designer.designSurface.layout;
import com.intellij.android.designer.model.RadViewComponent;
import com.intellij.android.designer.model.table.GridInfo;
import com.intellij.android.designer.model.table.RadTableLayoutComponent;
import com.intellij.designer.designSurface.DecorationLayer;
import com.intellij.designer.designSurface.StaticDecorator;
import com.intellij.designer.model.RadComponent;
import java.awt.*;
import java.util.List;
/**
* @author Alexander Lobas
@@ -39,42 +38,17 @@ public class TableLayoutDecorator extends StaticDecorator {
g.setStroke(FlowStaticDecorator.STROKE);
Rectangle bounds = component.getBounds(layer);
int[] columnWidths = ((RadTableLayoutComponent)component).getColumnWidths();
GridInfo gridInfo = ((RadTableLayoutComponent)component).getGridInfo();
if (columnWidths != null && columnWidths.length > 0) {
int x = bounds.x;
for (int i = 0; i < columnWidths.length; i++) {
int width = columnWidths[i];
if (width > 0) {
x += width;
if (i != columnWidths.length - 1 || x < bounds.getMinX()) {
g.drawLine(x, bounds.y, x, bounds.y + bounds.height);
}
}
else {
g.drawLine(x + 2, bounds.y, x + 2, bounds.y + bounds.height);
}
}
bounds.width = Math.max(bounds.width, x - bounds.x);
for (int x : gridInfo.vLines) {
g.drawLine(bounds.x + x, bounds.y, bounds.x + x, bounds.y + gridInfo.height);
}
List<RadComponent> children = component.getChildren();
RadComponent last = children.isEmpty() ? null : children.get(children.size() - 1);
for (RadComponent child : children) {
Rectangle childBounds = child.getBounds(layer);
int y = childBounds.y + childBounds.height + ((RadViewComponent)child).getMargins().height;
if (child != last || y < bounds.getMaxY()) {
g.drawLine(bounds.x, y, bounds.x + bounds.width, y);
}
for (int y : gridInfo.hLines) {
g.drawLine(bounds.x, bounds.y + y, bounds.x + gridInfo.width, bounds.y + y);
}
g.setStroke(stroke);
g.drawRect(bounds.x, bounds.y, bounds.width, bounds.height);
g.drawRect(bounds.x, bounds.y, gridInfo.width, gridInfo.height);
g.drawRect(bounds.x + 1, bounds.y + 1, gridInfo.width - 2, gridInfo.height - 2);
}
}
@@ -16,39 +16,57 @@
package com.intellij.android.designer.designSurface.layout;
import com.intellij.android.designer.designSurface.AbstractEditOperation;
import com.intellij.android.designer.model.RadViewComponent;
import com.intellij.android.designer.model.table.GridInfo;
import com.intellij.android.designer.model.table.GridInsertType;
import com.intellij.android.designer.model.table.RadTableLayoutComponent;
import com.intellij.designer.designSurface.FeedbackLayer;
import com.intellij.designer.designSurface.OperationContext;
import com.intellij.designer.designSurface.feedbacks.AlphaFeedback;
import com.intellij.designer.designSurface.feedbacks.LineInsertFeedback;
import com.intellij.designer.model.RadComponent;
import javax.swing.*;
import java.awt.*;
import java.util.List;
/**
* @author Alexander Lobas
*/
public class TableLayoutOperation extends AbstractEditOperation {
private GridFeedback myFeedback;
private LineInsertFeedback myHInsertFeedback;
private LineInsertFeedback myVInsertFeedback;
private int myColumn;
private int myRow;
private GridInsertType myInsertType;
private boolean myExist;
public TableLayoutOperation(RadComponent container, OperationContext context) {
super(container, context);
}
private void createFeedback() {
if (myFeedback == null) {
FeedbackLayer layer = myContext.getArea().getFeedbackLayer();
myFeedback = new GridFeedback();
myFeedback.setBounds(myContainer.getBounds(layer));
layer.add(myFeedback);
layer.repaint();
}
private GridInfo getGridInfo() {
return ((RadTableLayoutComponent)myContainer).getVirtualGridInfo();
}
@Override
public void showFeedback() {
createFeedback();
if (myFeedback == null) {
FeedbackLayer layer = myContext.getArea().getFeedbackLayer();
myFeedback = new GridFeedback();
myFeedback.setBounds(myContainer.getBounds(layer));
myHInsertFeedback = new LineInsertFeedback(Color.green, true);
myVInsertFeedback = new LineInsertFeedback(Color.green, false);
layer.add(myFeedback);
layer.add(myHInsertFeedback);
layer.add(myVInsertFeedback);
layer.repaint();
}
calculateGridInfo();
myFeedback.repaint();
}
@Override
@@ -56,64 +74,192 @@ public class TableLayoutOperation extends AbstractEditOperation {
if (myFeedback != null) {
FeedbackLayer layer = myContext.getArea().getFeedbackLayer();
layer.remove(myFeedback);
layer.add(myHInsertFeedback);
layer.add(myVInsertFeedback);
layer.repaint();
myFeedback = null;
myHInsertFeedback = null;
myVInsertFeedback = null;
}
}
private void calculateGridInfo() {
GridInfo gridInfo = getGridInfo();
Point location = SwingUtilities.convertPoint(myContext.getArea().getFeedbackLayer(), myContext.getLocation(), myFeedback);
myColumn = getLineIndex(gridInfo.vLines, location.x);
myRow = getLineIndex(gridInfo.hLines, location.y);
RadComponent[][] components = gridInfo.components;
if (components == null) {
myInsertType = GridInsertType.in_cell;
myExist = false;
}
else {
myInsertType = null;
Rectangle bounds = myContainer.getBounds(myContext.getArea().getFeedbackLayer());
Rectangle cellRect = getInsertRect(myExist);
Rectangle inCellRect = getInsertInRect(cellRect);
if (inCellRect.contains(location)) {
myInsertType = GridInsertType.in_cell;
myHInsertFeedback.setVisible(false);
myVInsertFeedback.setVisible(false);
}
else if (location.x < inCellRect.x) {
myInsertType = GridInsertType.before_v_cell;
myHInsertFeedback.setVisible(false);
myVInsertFeedback.setLocation(bounds.x + cellRect.x, bounds.y + cellRect.y);
myVInsertFeedback.setSize(0, cellRect.height);
myVInsertFeedback.setVisible(true);
}
else if (location.x > inCellRect.x) {
myInsertType = GridInsertType.after_v_cell;
myHInsertFeedback.setVisible(false);
myVInsertFeedback.setLocation(bounds.x + cellRect.x + cellRect.width, bounds.y + cellRect.y);
myVInsertFeedback.setSize(0, cellRect.height);
myVInsertFeedback.setVisible(true);
}
else if (location.y < inCellRect.y) {
myInsertType = GridInsertType.before_h_cell;
myHInsertFeedback.setVisible(true);
myHInsertFeedback.setLocation(bounds.x + cellRect.x, bounds.y + cellRect.y);
myHInsertFeedback.setSize(cellRect.width, 0);
myVInsertFeedback.setVisible(false);
}
else if (location.y > inCellRect.y) {
myInsertType = GridInsertType.after_h_cell;
myHInsertFeedback.setVisible(true);
myHInsertFeedback.setLocation(bounds.x + cellRect.x, bounds.y + cellRect.y + cellRect.height);
myHInsertFeedback.setSize(cellRect.width, 0);
myVInsertFeedback.setVisible(false);
}
if (myInsertType == GridInsertType.in_cell) {
if (myRow < components.length && myColumn < components[0].length) {
myExist = components[myRow][myColumn] != null;
}
else {
myExist = false;
}
}
}
}
private static int getLineIndex(int[] line, int location) {
for (int i = 0; i < line.length - 1; i++) {
if (line[i] <= location && location <= line[i + 1]) {
return i;
}
}
return Math.max(0, line.length - 1);
}
private Rectangle getInsertRect(boolean includeSpan) {
GridInfo gridInfo = getGridInfo();
int startColumn = myColumn;
int endColumn = myColumn + 1;
if (includeSpan) {
RadComponent[] columnComponents = gridInfo.components[myRow];
RadComponent existComponent = columnComponents[startColumn];
while (startColumn > 0) {
if (columnComponents[startColumn - 1] == existComponent) {
startColumn--;
}
else {
break;
}
}
while (endColumn < columnComponents.length) {
if (columnComponents[endColumn] == existComponent) {
endColumn++;
}
else {
break;
}
}
}
int x1 = startColumn < gridInfo.vLines.length ? gridInfo.vLines[startColumn] : 0;
int x2 = endColumn < gridInfo.vLines.length ? gridInfo.vLines[endColumn] : gridInfo.width;
int y1 = myRow < gridInfo.hLines.length ? gridInfo.hLines[myRow] : 0;
int y2 = myRow + 1 < gridInfo.hLines.length ? gridInfo.hLines[myRow + 1] : gridInfo.height;
return new Rectangle(x1, y1, x2 - x1, y2 - y1);
}
private static Rectangle getInsertInRect(Rectangle cellRect) {
int borderWidth = getInsertBorderLength(cellRect.width);
int borderHeight = getInsertBorderLength(cellRect.height);
return new Rectangle(cellRect.x + borderWidth, cellRect.y + borderHeight, cellRect.width - 2 * borderWidth,
cellRect.height - 2 * borderHeight);
}
private static int getInsertBorderLength(int length) {
int border = 5;
if (length < 3 * border) {
border = length / 3;
}
return border;
}
@Override
public boolean canExecute() {
return !myExist;
}
@Override
public void execute() throws Exception {
super.execute(); // TODO: Auto-generated method stub
}
//////////////////////////////////////////////////////////////////////////////////////////
//
// Feedback
//
//////////////////////////////////////////////////////////////////////////////////////////
public static final Color COLOR = new Color(80, 110, 160);
private class GridFeedback extends JComponent {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(COLOR);
g.setColor(BorderStaticDecorator.COLOR);
Rectangle bounds = getBounds();
bounds.x = bounds.y = 0;
GridInfo gridInfo = getGridInfo();
int[] columnWidths = ((RadTableLayoutComponent)myContainer).getColumnWidths();
if (columnWidths != null && columnWidths.length > 0) {
int x = bounds.x;
for (int i = 0; i < columnWidths.length; i++) {
int width = columnWidths[i];
if (width > 0) {
x += width;
if (i != columnWidths.length - 1 || x < bounds.getMinX()) {
g.drawLine(x, bounds.y, x, bounds.y + bounds.height);
}
}
else {
g.drawLine(x + 2, bounds.y, x + 2, bounds.y + bounds.height);
}
}
bounds.width = Math.max(bounds.width, x - bounds.x);
for (int x : gridInfo.vLines) {
g.drawLine(x, 0, x, gridInfo.height);
}
for (int y : gridInfo.hLines) {
g.drawLine(0, y, gridInfo.width, y);
}
g.drawRect(0, 0, gridInfo.width - 1, gridInfo.height - 1);
g.drawRect(1, 1, gridInfo.width - 3, gridInfo.height - 3);
List<RadComponent> children = myContainer.getChildren();
RadComponent last = children.isEmpty() ? null : children.get(children.size() - 1);
if (myInsertType == GridInsertType.in_cell) {
Rectangle cellRect = getInsertRect(myExist);
for (RadComponent child : children) {
Rectangle childBounds = child.getBounds(this);
int y = childBounds.y + childBounds.height + ((RadViewComponent)child).getMargins().height;
if (child != last || y < bounds.getMaxY()) {
g.drawLine(bounds.x, y, bounds.x + bounds.width, y);
if (myExist) {
AlphaFeedback.fillRect2(g, cellRect.x, cellRect.y, cellRect.width, cellRect.height, Color.pink);
}
else {
AlphaFeedback.fillRect1(g, cellRect.x, cellRect.y, cellRect.width, cellRect.height, Color.green);
}
}
g.drawRect(bounds.x, bounds.y, bounds.width, bounds.height);
}
}
}
@@ -0,0 +1,31 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.android.designer.model.table;
import com.intellij.designer.model.RadComponent;
import com.intellij.util.ArrayUtil;
/**
* @author Alexander Lobas
*/
public class GridInfo {
public int width;
public int height;
public int[] hLines = ArrayUtil.EMPTY_INT_ARRAY;
public int[] vLines = ArrayUtil.EMPTY_INT_ARRAY;
public boolean[] emptyColumns = ArrayUtil.EMPTY_BOOLEAN_ARRAY;
public RadComponent[][] components;
}
@@ -0,0 +1,29 @@
/*
* 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.android.designer.model.table;
/**
* @author Alexander Lobas
*/
public enum GridInsertType {
in_cell,
before_h_cell,
after_h_cell,
before_v_cell,
after_v_cell,
before_row,
after_row
}
@@ -30,12 +30,20 @@ public class RadCaptionTableColumn extends RadVisualComponent {
private final RadTableLayoutComponent myContainer;
private final int myColumnOffset;
private final int myColumnWidth;
private final StaticDecorator myDecorator = new CaptionStaticDecorator(this);
private final StaticDecorator myDecorator;
public RadCaptionTableColumn(RadTableLayoutComponent container, int columnOffset, int columnWidth) {
public RadCaptionTableColumn(RadTableLayoutComponent container, int columnOffset, int columnWidth, boolean empty) {
myContainer = container;
myColumnOffset = columnOffset;
myColumnWidth = columnWidth;
if (empty) {
myDecorator = new CaptionStaticDecorator(this, Color.PINK);
}
else {
myDecorator = new CaptionStaticDecorator(this);
}
setNativeComponent(container.getNativeComponent());
}
@@ -29,10 +29,17 @@ import java.util.List;
*/
public class RadCaptionTableRow extends RadVisualComponent {
private final RadViewComponent myComponent;
private final StaticDecorator myDecorator = new CaptionStaticDecorator(this);
private final StaticDecorator myDecorator;
public RadCaptionTableRow(RadViewComponent component) {
myComponent = component;
if (RadTableRowLayout.is(component)) {
myDecorator = new CaptionStaticDecorator(this);
} else {
myDecorator = new CaptionStaticDecorator(this, Color.PINK);
}
setNativeComponent(component.getNativeComponent());
}
@@ -97,7 +97,7 @@ public class RadTableLayout extends RadViewLayoutWithData implements ILayoutDeco
@Override
public ComponentDecorator getChildSelectionDecorator(RadComponent component, List<RadComponent> selection) {
if (component.getLayout() instanceof RadTableRowLayout) {
if (RadTableRowLayout.is(component)) {
return super.getChildSelectionDecorator(component, selection);
}
@@ -165,10 +165,15 @@ public class RadTableLayout extends RadViewLayoutWithData implements ILayoutDeco
List<RadComponent> components = new ArrayList<RadComponent>();
if (horizontal) {
int columnOffset = 0;
for (int columnWidth : container.getColumnWidths()) {
components.add(new RadCaptionTableColumn(container, columnOffset, Math.max(columnWidth, 2)));
columnOffset += columnWidth;
GridInfo gridInfo = container.getGridInfo();
int[] lines = gridInfo.vLines;
boolean[] emptyColumns = gridInfo.emptyColumns;
for (int i = 0; i < lines.length - 1; i++) {
components.add(new RadCaptionTableColumn(container,
lines[i],
lines[i + 1] - lines[i],
emptyColumns[i]));
}
}
else {
@@ -16,40 +16,175 @@
package com.intellij.android.designer.model.table;
import com.android.ide.common.rendering.api.ViewInfo;
import com.intellij.android.designer.model.RadViewComponent;
import com.intellij.android.designer.model.RadViewContainer;
import com.intellij.designer.model.RadComponent;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.lang.reflect.Field;
import java.util.List;
/**
* @author Alexander Lobas
*/
public class RadTableLayoutComponent extends RadViewContainer {
private int[] myColumnWidths;
private GridInfo myGridInfo;
private GridInfo myVirtualGridInfo;
@Override
public void setViewInfo(ViewInfo viewInfo) {
super.setViewInfo(viewInfo);
myColumnWidths = null;
myGridInfo = null;
myVirtualGridInfo = null;
}
@Nullable
public int[] getColumnWidths() {
if (myColumnWidths == null) {
try {
Object viewObject = myViewInfo.getViewObject();
Class<?> viewClass = viewObject.getClass();
Field maxWidths = viewClass.getDeclaredField("mMaxWidths");
maxWidths.setAccessible(true);
myColumnWidths = (int[])maxWidths.get(viewObject);
private int[] getColumnWidths() {
try {
Object viewObject = myViewInfo.getViewObject();
Class<?> viewClass = viewObject.getClass();
Field maxWidths = viewClass.getDeclaredField("mMaxWidths");
maxWidths.setAccessible(true);
int[] columnWidths = (int[])maxWidths.get(viewObject);
return columnWidths == null ? ArrayUtil.EMPTY_INT_ARRAY : columnWidths;
}
catch (Throwable e) {
return ArrayUtil.EMPTY_INT_ARRAY;
}
}
public GridInfo getGridInfo() {
if (myGridInfo == null) {
myGridInfo = new GridInfo();
int[] columnWidths = getColumnWidths();
if (columnWidths.length > 0) {
myGridInfo.emptyColumns = new boolean[columnWidths.length];
myGridInfo.vLines = new int[columnWidths.length + 1];
for (int i = 0; i < columnWidths.length; i++) {
int width = Math.max(columnWidths[i], 0);
myGridInfo.emptyColumns[i] = width == 0;
if (width == 0) {
width = 2;
if (i + 1 < columnWidths.length) {
columnWidths[i + 1] -= width;
}
}
myGridInfo.width += width;
myGridInfo.vLines[i + 1] = myGridInfo.width;
}
}
catch (Throwable e) {
}
if (myColumnWidths == null) {
myColumnWidths = ArrayUtil.EMPTY_INT_ARRAY;
List<RadComponent> rows = getChildren();
if (!rows.isEmpty()) {
Rectangle bounds = getBounds();
if (columnWidths.length == 0) {
myGridInfo.width = bounds.width;
}
myGridInfo.hLines = new int[rows.size() + 1];
int index = 1;
for (RadComponent row : rows) {
Rectangle rowBounds = row.getBounds();
myGridInfo.hLines[index++] = myGridInfo.height = rowBounds.y - bounds.y + rowBounds.height;
}
}
}
return myColumnWidths;
return myGridInfo;
}
public GridInfo getVirtualGridInfo() {
if (myVirtualGridInfo == null) {
myVirtualGridInfo = new GridInfo();
GridInfo gridInfo = getGridInfo();
Rectangle bounds = getBounds();
myVirtualGridInfo.width = bounds.width;
myVirtualGridInfo.height = bounds.height;
myVirtualGridInfo.vLines = addLineInfo(gridInfo.vLines, bounds.width - (gridInfo.vLines.length == 0 ? 0 : gridInfo.width));
myVirtualGridInfo.hLines = addLineInfo(gridInfo.hLines, bounds.height - gridInfo.height);
List<RadComponent> rows = getChildren();
if (!rows.isEmpty()) {
int columnSize = Math.max(1, gridInfo.vLines.length - 1);
RadComponent[][] components = new RadComponent[rows.size()][columnSize];
myVirtualGridInfo.components = components;
for (int i = 0; i < components.length; i++) {
RadComponent row = rows.get(i);
if (RadTableRowLayout.is(row)) {
int index = 0;
for (RadComponent column : row.getChildren()) {
int cellIndex = getCellIndex(column);
if (cellIndex > index) {
index = cellIndex;
}
int cellSpan = getCellSnap(column);
for (int j = 0; j < cellSpan; j++) {
components[i][index++] = column;
}
}
}
else {
components[i][0] = row;
}
}
}
}
return myVirtualGridInfo;
}
private static int getCellIndex(RadComponent component) {
try {
String column = ((RadViewComponent)component).getTag().getAttributeValue("android:layout_column");
return Integer.parseInt(column);
}
catch (Throwable e) {
return -1;
}
}
private static int getCellSnap(RadComponent component) {
try {
String span = ((RadViewComponent)component).getTag().getAttributeValue("android:layout_span");
return Integer.parseInt(span);
}
catch (Throwable e) {
return 1;
}
}
private static final int NEW_CELL_SIZE = 32;
private static int[] addLineInfo(int[] oldLines, int delta) {
if (delta > 0) {
int newLength = oldLines.length + delta / NEW_CELL_SIZE;
if (newLength > oldLines.length) {
int[] newLines = new int[newLength];
int startIndex = oldLines.length;
if (oldLines.length > 0) {
System.arraycopy(oldLines, 0, newLines, 0, oldLines.length);
}
else {
startIndex = 1;
}
for (int i = startIndex; i < newLength; i++) {
newLines[i] = newLines[i - 1] + NEW_CELL_SIZE;
}
return newLines;
}
return oldLines;
}
return oldLines;
}
}
@@ -36,6 +36,10 @@ public class RadTableRowLayout extends RadLinearLayout {
return LAYOUT_PARAMS;
}
public static boolean is(RadComponent component) {
return component.getLayout() instanceof RadTableRowLayout;
}
private boolean isTableParent() {
return myContainer.getParent() instanceof RadTableLayoutComponent;
}
@@ -263,7 +263,7 @@ public class AndroidAptCompiler implements SourceGeneratingCompiler {
final String[] libPackages = getLibPackages(module, packageName);
final Module circularDepLibWithSamePackage = AndroidCompileUtil.findCircularDependencyOnLibraryWithSamePackage(facet);
if (circularDepLibWithSamePackage != null) {
if (circularDepLibWithSamePackage != null && !facet.getConfiguration().LIBRARY_PROJECT) {
myContext.addMessage(CompilerMessageCategory.WARNING,
AndroidBundle.message("android.compilation.warning.circular.app.dependency",
packageName, module.getName(),
@@ -163,7 +163,7 @@ public class AndroidAutogenerator {
final String manifestFileOsPath = FileUtil.toSystemDependentName(manifestFile.getPath());
final Module circularDepLibWithSamePackage = AndroidCompileUtil.findCircularDependencyOnLibraryWithSamePackage(facet);
if (circularDepLibWithSamePackage != null) {
if (circularDepLibWithSamePackage != null && !facet.getConfiguration().LIBRARY_PROJECT) {
context.addMessage(CompilerMessageCategory.WARNING, AndroidBundle.message("android.compilation.warning.circular.app.dependency",
packageName, module.getName(),
circularDepLibWithSamePackage.getName()), null, -1, -1);
@@ -655,19 +655,20 @@ public class AndroidCompileUtil {
final GlobalSearchScope moduleScope = facet.getModule().getModuleScope();
initializeGenSourceRoot(module, AndroidRootUtil.getRenderscriptGenSourceRootPath(facet),
FileTypeIndex.getFiles(AndroidRenderscriptFileType.INSTANCE, moduleScope).size() > 0);
FileTypeIndex.getFiles(AndroidRenderscriptFileType.INSTANCE, moduleScope).size() > 0, true);
if (AndroidAptCompiler.isToCompileModule(module, facet.getConfiguration())) {
initializeGenSourceRoot(module, AndroidRootUtil.getAptGenSourceRootPath(facet), true);
initializeGenSourceRoot(module, AndroidRootUtil.getAptGenSourceRootPath(facet), true, true);
}
else {
// we need to include generated-sources/r to compilation, because it contains R.java generated by Maven,
// which should be used in Maven-based resource processing mode
initializeGenSourceRoot(module, AndroidRootUtil.getAptGenSourceRootPath(facet), true, false);
includeAaptGenSourceRootToCompilation(facet);
}
initializeGenSourceRoot(module, AndroidRootUtil.getAidlGenSourceRootPath(facet),
FileTypeIndex.getFiles(AndroidIdlFileType.ourFileType, moduleScope).size() > 0);
FileTypeIndex.getFiles(AndroidIdlFileType.ourFileType, moduleScope).size() > 0, true);
}
private static void includeAaptGenSourceRootToCompilation(AndroidFacet facet) {
@@ -686,7 +687,7 @@ public class AndroidCompileUtil {
}
}
private static void initializeGenSourceRoot(@NotNull Module module, @Nullable String sourceRootPath, boolean createIfNotExist) {
private static void initializeGenSourceRoot(@NotNull Module module, @Nullable String sourceRootPath, boolean createIfNotExist, boolean exclude) {
if (sourceRootPath == null) {
return;
}
@@ -701,7 +702,7 @@ public class AndroidCompileUtil {
if (sourceRoot == null) {
sourceRoot = LocalFileSystem.getInstance().findFileByPath(sourceRootPath);
}
if (sourceRoot != null) {
if (sourceRoot != null && exclude) {
excludeFromCompilation(module.getProject(), sourceRoot);
}
}
@@ -19,14 +19,16 @@ import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.CommandLineBuilder;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.configurations.JavaParameters;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.compiler.CompilerMessageCategory;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.util.Computable;
import com.intellij.util.containers.HashMap;
import org.jetbrains.android.util.AndroidUtils;
import org.jetbrains.android.util.ExecutionStatus;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.execution.MavenExternalParameters;
import org.jetbrains.idea.maven.execution.MavenRunner;
import org.jetbrains.idea.maven.execution.MavenRunnerParameters;
import org.jetbrains.idea.maven.project.MavenProjectsManager;
@@ -42,24 +44,39 @@ public class AndroidMavenExecutor {
private static final Logger LOG = Logger.getInstance("#org.jetbrains.android.compiler.tools.AndroidMavenExecutor");
private static final String BUILD_ERROR_INDICATOR = "[error]";
private static final String FAILED_TO_RESOLVE_ARTIFACT_INDICATOR = "[info] failed to resolve artifact";
private AndroidMavenExecutor() {
}
public static Map<CompilerMessageCategory, List<String>> generateResources(Module module) {
public static Map<CompilerMessageCategory, List<String>> generateResources(final Module module) {
MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(module.getProject());
MavenRunnerParameters parameters =
final MavenRunnerParameters parameters =
new MavenRunnerParameters(true, projectsManager.findProject(module).getDirectory(),
Collections.singletonList("process-resources"),
projectsManager.getExplicitProfiles());
Map<CompilerMessageCategory, List<String>> result = new HashMap<CompilerMessageCategory, List<String>>();
final Map<CompilerMessageCategory, List<String>> result = new HashMap<CompilerMessageCategory, List<String>>();
result.put(CompilerMessageCategory.ERROR, new ArrayList<String>());
try {
JavaParameters javaParams = MavenExternalParameters.createJavaParameters(module.getProject(), parameters);
JavaParameters javaParams = ApplicationManager.getApplication().runReadAction(new Computable<JavaParameters>() {
@Nullable
@Override
public JavaParameters compute() {
try {
return MavenExternalParameters.createJavaParameters(module.getProject(), parameters);
}
catch (ExecutionException e) {
LOG.info(e);
result.get(CompilerMessageCategory.ERROR).add(e.getMessage());
return null;
}
}
});
if (javaParams == null) {
return result;
}
GeneralCommandLine commandLine = CommandLineBuilder.createFromJavaParameters(javaParams);
StringBuilder messageBuilder = new StringBuilder();
@@ -70,13 +87,7 @@ public class AndroidMavenExecutor {
String lcmessage = message.toLowerCase();
int buildErrorIndex = lcmessage.indexOf(BUILD_ERROR_INDICATOR);
if (buildErrorIndex >= 0) {
int failedToResolveIndex = lcmessage.indexOf(FAILED_TO_RESOLVE_ARTIFACT_INDICATOR);
/*if (failedToResolveIndex >= 0) {
result.get(CompilerMessageCategory.ERROR).add("Failed to copy Android resources from Maven artifacts");
}
else {*/
result.get(CompilerMessageCategory.ERROR).add(message.substring(buildErrorIndex));
//}
result.get(CompilerMessageCategory.ERROR).add(message.substring(buildErrorIndex));
}
}
}
@@ -223,6 +223,11 @@ public class GitRevisionNumber implements ShortVcsRevisionNumber {
h.addParameters("--timestamp", "--max-count=1", rev);
h.endOptions();
final String output = h.run();
return parseRevlistOutputAsRevisionNumber(h, output);
}
@NotNull
public static GitRevisionNumber parseRevlistOutputAsRevisionNumber(@NotNull GitSimpleHandler h, @NotNull String output) {
StringTokenizer tokenizer = new StringTokenizer(output, "\n\r \t", false);
Date timestamp = GitUtil.parseTimestampWithNFEReport(tokenizer.nextToken(), h, output);
return new GitRevisionNumber(tokenizer.nextToken(), timestamp);
@@ -728,4 +728,9 @@ public abstract class GitHandler {
public String toString() {
return myCommandLine.toString();
}
public void dontEscapeQuotes() {
myCommandLine.putUserData(GeneralCommandLine.DO_NOT_ESCAPE_QUOTES, true);
}
}
@@ -164,7 +164,7 @@ public class GitVcsPanel {
!crlfPolicyItem(settings).equals(myConvertTextFilesComboBox.getSelectedItem()) ||
!settings.autoUpdateIfPushRejected() == myAutoUpdateIfPushRejected.isSelected() ||
((settings.getSyncSetting() == GitBranchSyncSetting.SYNC) != mySyncBranchControl.isSelected() ||
settings.isAutoCommitOnCherryPick() == myAutoCommitOnCherryPick.isSelected());
settings.isAutoCommitOnCherryPick() != myAutoCommitOnCherryPick.isSelected());
}
/**
@@ -48,7 +48,7 @@ public class ContainedInBranchesConfigDialog extends DialogWrapper {
Collection<String> remoteBranches, final String currentLocal, final String currentRemote) {
super(project, true);
myProject = project;
setTitle("Configure branches presentation");
setTitle("Configure Branches Presentation");
initUi(project, localBranches, remoteBranches, currentLocal, currentRemote);
Disposer.register(myProject, getDisposable());
init();
@@ -79,21 +79,12 @@ public class GitStashChangesSaver extends GitChangesSaver {
}
public void load() throws VcsException {
Collection<VirtualFile> conflictedRoots = new ArrayList<VirtualFile>();
for (VirtualFile root : myStashedRoots) {
boolean conflict = loadRoot(root);
if (conflict) {
conflictedRoots.add(root);
}
loadRoot(root);
}
boolean conflictsResolved = new UnstashConflictResolver(myProject, myGit, myStashedRoots, myParams).merge();
if (conflictsResolved) {
LOG.info("load: all conflicts resolved, dropping stash in " + myStashedRoots);
for (VirtualFile root : conflictedRoots) {
GitStashUtils.dropStash(myProject, root);
}
}
LOG.info("load: conflicts resolved status is " + conflictsResolved + " in roots " + myStashedRoots);
}
@Override
@@ -18,6 +18,7 @@ package git4idea.ui;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationListener;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
@@ -173,27 +174,18 @@ public class GitUnstashDialog extends DialogWrapper {
ProgressManager.getInstance().run(new Task.Modal(myProject, "Removing stash " + stash.getStash(), false) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
GitSimpleHandler h = dropHandler(stash.getStash());
final GitSimpleHandler h = dropHandler(stash.getStash());
try {
h.run();
h.unsilence();
}
catch (VcsException ex) {
try {
//noinspection HardCodedStringLiteral
if (ex.getMessage().startsWith("fatal: Needed a single revision")) {
h = dropHandler(translateStash(stash.getStash()));
h.run();
catch (final VcsException ex) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
GitUIUtil.showOperationError(myProject, ex, h.printableCommandLine());
}
else {
h.unsilence();
throw ex;
}
}
catch (VcsException ex2) {
GitUIUtil.showOperationError(myProject, ex, h.printableCommandLine());
return;
}
});
}
}
});
@@ -205,7 +197,8 @@ public class GitUnstashDialog extends DialogWrapper {
private GitSimpleHandler dropHandler(String stash) {
GitSimpleHandler h = new GitSimpleHandler(myProject, getGitRoot(), GitCommand.STASH);
h.setNoSSH(true);
h.addParameters("drop", stash);
h.addParameters("drop");
addStashParameter(h, stash);
return h;
}
});
@@ -215,23 +208,18 @@ public class GitUnstashDialog extends DialogWrapper {
String resolvedStash;
String selectedStash = getSelectedStash().getStash();
try {
resolvedStash = GitRevisionNumber.resolve(myProject, root, selectedStash).asString();
GitSimpleHandler h = new GitSimpleHandler(project, root, GitCommand.REV_LIST);
h.setNoSSH(true);
h.setSilent(true);
h.addParameters("--timestamp", "--max-count=1");
addStashParameter(h, selectedStash);
h.endOptions();
final String output = h.run();
resolvedStash = GitRevisionNumber.parseRevlistOutputAsRevisionNumber(h, output).asString();
}
catch (VcsException ex) {
try {
//noinspection HardCodedStringLiteral
if (ex.getMessage().startsWith("fatal: bad revision 'stash@")) {
selectedStash = translateStash(selectedStash);
resolvedStash = GitRevisionNumber.resolve(myProject, root, selectedStash).asString();
}
else {
throw ex;
}
}
catch (VcsException ex2) {
GitUIUtil.showOperationError(myProject, ex, "resolving revision");
return;
}
GitUIUtil.showOperationError(myProject, ex, "resolving revision");
return;
}
GitShowAllSubmittedFilesAction.showSubmittedFiles(myProject, resolvedStash, root);
}
@@ -241,13 +229,16 @@ public class GitUnstashDialog extends DialogWrapper {
}
/**
* Translate stash name so that { } are escaped.
*
* @param selectedStash a selected stash
* @return translated name
* Adds {@code stash@{x}} parameter to the handler, quotes it if needed.
*/
private static String translateStash(String selectedStash) {
return selectedStash.replaceAll("([\\{}])", "\\\\$1");
private void addStashParameter(@NotNull GitHandler handler, @NotNull String stash) {
if (GitVersionSpecialty.NEEDS_QUOTES_IN_STASH_NAME.existsIn(myVcs.getVersion())) {
handler.addParameters("\"" + stash + "\"");
handler.dontEscapeQuotes();
}
else {
handler.addParameters(stash);
}
}
/**
@@ -329,6 +320,7 @@ public class GitUnstashDialog extends DialogWrapper {
catch (VcsException e) {
// ignore error
}
myStashList.setSelectedIndex(0);
}
/**
@@ -339,10 +331,9 @@ public class GitUnstashDialog extends DialogWrapper {
}
/**
* @param escaped if true stash name will be escaped
* @return unstash handler
*/
private GitLineHandler handler(boolean escaped) {
private GitLineHandler handler() {
GitLineHandler h = new GitLineHandler(myProject, getGitRoot(), GitCommand.STASH);
h.setNoSSH(true);
String branch = myBranchTextField.getText();
@@ -356,12 +347,7 @@ public class GitUnstashDialog extends DialogWrapper {
h.addParameters("branch", branch);
}
String selectedStash = getSelectedStash().getStash();
if (escaped) {
selectedStash = translateStash(selectedStash);
} else if (GitVersionSpecialty.NEEDS_QUOTES_IN_STASH_NAME.existsIn(myVcs.getVersion())) { // else if, because escaping {} also solves the issue
selectedStash = "\"" + selectedStash + "\"";
}
h.addParameters(selectedStash);
addStashParameter(h, selectedStash);
return h;
}
@@ -396,6 +382,11 @@ public class GitUnstashDialog extends DialogWrapper {
return "reference.VersionControl.Git.Unstash";
}
@Override
public JComponent getPreferredFocusedComponent() {
return myStashList;
}
/**
* Show unstash dialog and process its result
*
@@ -414,32 +405,22 @@ public class GitUnstashDialog extends DialogWrapper {
return;
}
affectedRoots.add(d.getGitRoot());
GitLineHandler h = d.handler(false);
final AtomicBoolean needToEscapedBraces = new AtomicBoolean(false);
GitLineHandler h = d.handler();
final AtomicBoolean conflict = new AtomicBoolean();
h.addLineListener(new GitLineHandlerAdapter() {
public void onLineAvailable(String line, Key outputType) {
if (line.startsWith("fatal: Needed a single revision")) {
needToEscapedBraces.set(true);
} else if (line.contains("Merge conflict")) {
if (line.contains("Merge conflict")) {
conflict.set(true);
}
}
});
int rc = GitHandlerUtil.doSynchronously(h, GitBundle.getString("unstash.unstashing"), h.printableCommandLine(), false);
if (needToEscapedBraces.get()) {
h = d.handler(true);
rc = GitHandlerUtil.doSynchronously(h, GitBundle.getString("unstash.unstashing"), h.printableCommandLine(), false);
}
if (conflict.get()) {
VirtualFile root = d.getGitRoot();
boolean conflictsResolved = new UnstashConflictResolver(project, root, d.getSelectedStash()).merge();
if (conflictsResolved) {
LOG.info("loadRoot " + root + " conflicts resolved, dropping stash");
GitStashUtils.dropStash(project, root);
}
LOG.info("loadRoot " + root + ", conflictsResolved: " + conflictsResolved);
} else if (rc != 0) {
GitUIUtil.showOperationErrors(project, h.errors(), h.printableCommandLine());
}
+1 -1
View File
@@ -1012,7 +1012,7 @@
<projectStructureDetector implementation="org.jetbrains.plugins.groovy.griffon.GriffonProjectStructureDetector"/>
<programRunner implementation="org.jetbrains.plugins.groovy.griffon.GriffonDebuggerRunner"/>
<configurationType implementation="org.jetbrains.plugins.groovy.griffon.GriffonRunConfigurationType"/>
<toolWindow id="Griffon View" anchor="left" secondary="false" icon="/icons/griffon/griffon.png"
<toolWindow id="Griffon View" anchor="left" secondary="false" icon="/icons/griffon/griffonToolWindow.png"
factoryClass="org.jetbrains.plugins.groovy.griffon.GriffonToolWindowFactory"
conditionClass="org.jetbrains.plugins.groovy.griffon.GriffonToolWindowFactory"/>
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* 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.
@@ -143,7 +143,7 @@ public abstract class GroovyCompilerBase implements TranslatingCompiler {
if (profileGroovyc) {
parameters.getVMParametersList().defineProperty("java.library.path", PathManager.getBinPath());
parameters.getVMParametersList().defineProperty("profile.groovy.compiler", "true");
parameters.getVMParametersList().add("-agentlib:yjpagent=disablej2ee,disablecounts,disablealloc,sessionname=GroovyCompiler");
parameters.getVMParametersList().add("-agentlib:yjpagent=disablej2ee,disablealloc,sessionname=GroovyCompiler");
classPathBuilder.add(PathManager.findFileInLibDirectory("yjp-controller-api-redist.jar").getAbsolutePath());
}
@@ -55,7 +55,7 @@ import java.util.Map;
*/
public class GriffonFramework extends MvcFramework {
public static final Icon GRIFFON_ICON = IconLoader.getIcon("/icons/griffon/griffon.png");
public static final Icon GRIFFON_TOOLWINDOW_ICON = IconLoader.getIcon("/icons/griffon/griffonToolWindow.png");
@NonNls private static final String GRIFFON_COMMON_PLUGINS = "-griffonPlugins";
private static final String GLOBAL_PLUGINS_MODULE_NAME = "GriffonGlobalPlugins";
@@ -92,7 +92,7 @@ public class GriffonToolWindowFactory extends MvcToolWindowDescriptor {
@Override
public Icon getModuleNodeIcon() {
return GriffonFramework.GRIFFON_TOOLWINDOW_ICON;
return GriffonFramework.GRIFFON_ICON;
}
@@ -422,6 +422,7 @@ public class MvcModuleStructureSynchronizer extends AbstractProjectComponent {
if (shouldShow && toolWindow == null) {
toolWindow = toolWindowManager.registerToolWindow(id, true, ToolWindowAnchor.LEFT, myProject, true);
toolWindow.setIcon(IconLoader.getIcon(ep.icon));
descriptor.createToolWindowContent(myProject, toolWindow);
}
else if (!shouldShow && toolWindow != null) {
@@ -51,7 +51,6 @@ public abstract class MvcToolWindowDescriptor implements ToolWindowFactory, Cond
}
public void createToolWindowContent(Project project, ToolWindow toolWindow) {
toolWindow.setIcon(myFramework.getIcon());
toolWindow.setAvailable(true, null);
toolWindow.setToHideOnEmptyContent(true);
toolWindow.setTitle(myFramework.getDisplayName());
@@ -23,11 +23,13 @@ package org.jetbrains.idea.maven.wizards;
import com.intellij.ide.util.projectWizard.ModuleWizardStep;
import com.intellij.ide.util.projectWizard.ProjectWizardStepFactory;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.projectImport.ProjectImportProvider;
import com.intellij.projectImport.SelectImportedProjectsStep;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.project.MavenProjectsManager;
import java.io.File;
@@ -36,7 +38,7 @@ public class MavenProjectImportProvider extends ProjectImportProvider {
super(builder);
}
public ModuleWizardStep[] createSteps(WizardContext wizardContext) {
public ModuleWizardStep[] createSteps(final WizardContext wizardContext) {
final ProjectWizardStepFactory stepFactory = ProjectWizardStepFactory.getInstance();
return new ModuleWizardStep[]{new MavenProjectImportStep(wizardContext), new SelectProfilesStep(wizardContext),
new SelectImportedProjectsStep<MavenProject>(wizardContext) {
@@ -50,9 +52,22 @@ public class MavenProjectImportProvider extends ProjectImportProvider {
stringBuilder.append(" [").append(relPath).append("]");
}
}
if (!isElementEnabled(project)) {
stringBuilder.append(" (project is ignored. See Settings -> Maven -> Ignored Files)");
}
return stringBuilder.toString();
}
@Override
protected boolean isElementEnabled(MavenProject mavenProject) {
Project project = wizardContext.getProject();
if (project == null) return true;
return !MavenProjectsManager.getInstance(project).isIgnored(mavenProject);
}
public void updateDataModel() {
super.updateDataModel();
getWizardContext().setProjectName(((MavenProjectBuilder)getBuilder()).getSuggestedProjectName());
@@ -57,4 +57,32 @@ public class AlphaFeedback extends JComponent {
protected void paintOther2(Graphics2D g2d) {
g2d.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
}
//////////////////////////////////////////////////////////////////////////////////////////
//
// Utils
//
//////////////////////////////////////////////////////////////////////////////////////////
public static void fillRect1(Graphics g, int x, int y, int width, int height, Color color) {
fillRect(g, x, y, width, height, color, myComposite1);
}
public static void fillRect2(Graphics g, int x, int y, int width, int height, Color color) {
fillRect(g, x, y, width, height, color, myComposite2);
}
public static void fillRect(Graphics g, int x, int y, int width, int height, Color color, Composite composite) {
Graphics2D g2d = (Graphics2D)g;
Composite oldComposite = g2d.getComposite();
Color oldColor = g.getColor();
g2d.setColor(color);
g2d.setComposite(composite);
g2d.fillRect(x, y, width, height);
g2d.setComposite(oldComposite);
g2d.setColor(oldColor);
}
}
@@ -43,8 +43,8 @@ public class CreateHtmlFileAction extends CreateFileFromTemplateAction implement
protected void buildDialog(Project project, PsiDirectory directory, CreateFileFromTemplateDialog.Builder builder) {
builder
.setTitle(XmlBundle.message("new.html.file.action"))
.addKind("HTML file", StdFileTypes.HTML.getIcon(), FileTemplateManager.INTERNAL_HTML_TEMPLATE_NAME)
.addKind("HTML5 file", StdFileTypes.HTML.getIcon(), FileTemplateManager.INTERNAL_HTML5_TEMPLATE_NAME)
.addKind("HTML file", StdFileTypes.HTML.getIcon(), FileTemplateManager.INTERNAL_HTML5_TEMPLATE_NAME)
.addKind("HTML4 file", StdFileTypes.HTML.getIcon(), FileTemplateManager.INTERNAL_HTML_TEMPLATE_NAME)
.addKind("XHTML file", StdFileTypes.XHTML.getIcon(), FileTemplateManager.INTERNAL_XHTML_TEMPLATE_NAME);
}
@@ -417,7 +417,8 @@ public class ExternalResourceManagerImpl extends ExternalResourceManagerEx imple
@Override
@NotNull
public String getDefaultHtmlDoctype(@NotNull Project project) {
return getProjectResources(project).myDefaultHtmlDoctype;
final String doctype = getProjectResources(project).myDefaultHtmlDoctype;
return XmlUtil.XHTML_URI.equals(doctype) ? XmlUtil.XHTML4_SCHEMA_LOCATION : doctype;
}
@Override
@@ -80,7 +80,7 @@ public class HtmlLanguageLevelForm {
}
public void resetFromDoctype(String doctype) {
if (doctype == null || doctype.length() == 0 || doctype.equals(XmlUtil.XHTML_URI)) {
if (doctype == null || doctype.length() == 0 || doctype.equals(XmlUtil.XHTML4_SCHEMA_LOCATION)) {
myHtml4RadioButton.setSelected(true);
myDoctypeTextField.setEnabled(false);
}
@@ -43,6 +43,7 @@ import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.xml.*;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ConcurrentHashMap;
import com.intellij.xml.Html5SchemaProvider;
import com.intellij.xml.XmlExtension;
import com.intellij.xml.XmlNSDescriptor;
import com.intellij.xml.util.XmlNSDescriptorSequence;
@@ -207,12 +208,19 @@ public class XmlDocumentImpl extends XmlElementImpl implements XmlDocument {
if (nsDescriptor == null) {
String htmlns = ExternalResourceManagerEx.getInstanceEx().getDefaultHtmlDoctype(getProject());
if (htmlns == null || htmlns.length() == 0) {
htmlns = XmlUtil.XHTML_URI;
htmlns = Html5SchemaProvider.HTML5_SCHEMA_LOCATION;
}
nsDescriptor = getDefaultNSDescriptor(htmlns, false);
}
return new HtmlNSDescriptorImpl(nsDescriptor);
}
else if (XmlUtil.XHTML_URI.equals(namespace)) {
String xhtmlNamespace = XmlUtil.getDefaultXhtmlNamespace(getProject());
if (xhtmlNamespace == null || xhtmlNamespace.length() == 0) {
xhtmlNamespace = Html5SchemaProvider.XHTML5_SCHEMA_LOCATION;
}
return getDefaultNSDescriptor(xhtmlNamespace, false);
}
else if (namespace != null && namespace != XmlUtil.EMPTY_URI) {
if (doctype == null || !namespace.equals(XmlUtil.getDtdUri(doctype))) {
boolean documentIsSchemaThatDefinesNs = namespace.equals(XmlUtil.getTargetSchemaNsFromTag(getRootTag()));
@@ -19,6 +19,7 @@ import com.intellij.codeInsight.completion.CompletionUtil;
import com.intellij.codeInsight.daemon.Validator;
import com.intellij.javaee.ExternalResourceManager;
import com.intellij.javaee.ExternalResourceManagerEx;
import com.intellij.javaee.ExternalResourceManagerImpl;
import com.intellij.javaee.UriUtil;
import com.intellij.lang.ASTNode;
import com.intellij.lang.Language;
@@ -35,9 +36,11 @@ import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.patterns.StandardPatterns;
import com.intellij.patterns.StringPattern;
@@ -74,6 +77,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.net.URL;
import java.util.*;
/**
@@ -152,10 +156,16 @@ public class XmlUtil {
@NonNls public static final String WSDL_SCHEMA_URI = "http://schemas.xmlsoap.org/wsdl/";
public static final Key<PsiAnchor> ORIGINAL_ELEMENT = Key.create("ORIGINAL_ELEMENT");
public static final String XHTML4_SCHEMA_LOCATION;
private XmlUtil() {
}
static {
final URL xhtml4SchemaLocationUrl = XmlUtil.class.getResource(ExternalResourceManagerImpl.STANDARD_SCHEMAS + "xhtml1-transitional.xsd");
XHTML4_SCHEMA_LOCATION = VfsUtil.urlToPath(VfsUtil.fixURLforIDEA(FileUtil.unquote(xhtml4SchemaLocationUrl.toExternalForm())));
}
@Nullable
public static String getSchemaLocation(XmlTag tag, String namespace) {
final String uri = ExternalResourceManagerEx.getInstanceEx().getResourceLocation(namespace, tag.getProject());
@@ -604,11 +614,10 @@ public class XmlUtil {
}
public static String getDefaultXhtmlNamespace(Project project) {
String defaultHtmlDoctype = ExternalResourceManagerEx.getInstanceEx().getDefaultHtmlDoctype(project);
if (Html5SchemaProvider.HTML5_SCHEMA_LOCATION.equals(defaultHtmlDoctype)) {
defaultHtmlDoctype = Html5SchemaProvider.XHTML5_SCHEMA_LOCATION;
}
return defaultHtmlDoctype;
final String doctype = ExternalResourceManagerEx.getInstanceEx().getDefaultHtmlDoctype(project);
return Html5SchemaProvider.HTML5_SCHEMA_LOCATION.equals(doctype)
? Html5SchemaProvider.XHTML5_SCHEMA_LOCATION
: doctype;
}
//
//public static void expandTag(@NotNull XmlTag tag) {