<component name="libraryTable">
<library name="JPS-facade">
<CLASSES>
- <root url="jar://$PROJECT_DIR$/lib/rt/jps-incremental/jps-facade.jar!/" />
+ <root url="jar://$PROJECT_DIR$/lib/jps-facade.jar!/" />
</CLASSES>
<JAVADOC />
- <SOURCES />
+ <SOURCES>
+ <root url="jar://$PROJECT_DIR$/lib/rt/jps-incremental/src/jps-sources.zip!/" />
+ </SOURCES>
</library>
</component>
\ No newline at end of file
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" exported="" name="protobuf" level="project" />
<orderEntry type="library" name="Netty" level="project" />
- <orderEntry type="library" name="JPS-facade" level="project" />
+ <orderEntry type="library" exported="" name="JPS-facade" level="project" />
<orderEntry type="module" module-name="util" />
<orderEntry type="module" module-name="annotations" />
</component>
}
message SetupCommand {
+
message PathVariable {
required string name = 1;
required string value = 2;
}
+
+ message GlobalLibrary {
+ required string name = 1;
+ optional string homePath = 2;
+ repeated string path = 3;
+ }
+
repeated PathVariable path_variable = 1;
+ repeated GlobalLibrary global_library = 2;
}
message ReloadProjectCommand {
required Kind kind = 1;
optional string text = 2;
optional string source_file_path = 3;
- optional uint32 line = 4;
- optional uint32 column = 5;
+ 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;
}
required Type response_type = 1;
*/
public class Bootstrap {
+ public static final String JPS_RUNTIME_PATH = "rt/jps-incremental";
+
public static List<File> buildServerProcessClasspath() {
final List<File> cp = new ArrayList<File>();
cp.add(getResourcePath(Server.class));
cp.add(getResourcePath(com.google.protobuf.Message.class));
cp.add(getResourcePath(org.jboss.netty.bootstrap.Bootstrap.class));
- final File jpsJar = getResourcePath(Facade.class);
- final File parentFile = jpsJar.getParentFile();
- final File[] files = parentFile.listFiles();
+ final File jpsFacadeJar = getResourcePath(Facade.class);
+ cp.add(jpsFacadeJar);
+
+ final File jpsRuntime = new File(jpsFacadeJar.getParentFile(), JPS_RUNTIME_PATH);
+ final File[] files = jpsRuntime.listFiles();
if (files != null) {
for (File file : files) {
final String name = file.getName();
name.startsWith("asm") ||
name.startsWith("gant")||
name.startsWith("groovy") ||
- name.startsWith("javac2")
+ name.startsWith("javac2") ||
+ name.startsWith("util")
);
if (shouldAdd) {
cp.add(file);
import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
+import org.jetbrains.jps.server.GlobalLibrary;
import org.jetbrains.jpsservice.impl.JpsClientMessageHandler;
import org.jetbrains.jpsservice.impl.ProtoUtil;
import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
+import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;
@NotNull
public RequestFuture sendCompileRequest(String projectId, List<String> modules, boolean rebuild, JpsServerResponseHandler handler) throws Exception{
- if (myState.get() != State.CONNECTED) {
- throw new Exception("Client not connected");
- }
+ checkConnected();
return sendRequest(
rebuild? ProtoUtil.createRebuildRequest(projectId, modules) : ProtoUtil.createMakeRequest(projectId, modules),
handler
@NotNull
public RequestFuture sendShutdownRequest() throws Exception {
- if (myState.get() != State.CONNECTED) {
- throw new Exception("Client not connected");
- }
+ checkConnected();
return sendRequest(ProtoUtil.createShutdownRequest(true), null);
}
@NotNull
- public RequestFuture sendSetupRequest(final Map<String, String> pathVariables) throws Exception {
+ public RequestFuture sendSetupRequest(final Map<String, String> pathVariables, final List<GlobalLibrary> sdkAndLibs) throws Exception {
+ checkConnected();
+ return sendRequest(ProtoUtil.createSetupRequest(pathVariables, sdkAndLibs), null);
+ }
+
+ @NotNull
+ public RequestFuture sendProjectReloadRequest(Collection<String> projectPaths) throws Exception {
+ checkConnected();
+ return sendRequest(ProtoUtil.createReloadProjectRequest(projectPaths), null);
+ }
+
+ private void checkConnected() throws Exception {
if (myState.get() != State.CONNECTED) {
throw new Exception("Client not connected");
}
- return sendRequest(ProtoUtil.createSetupRequest(pathVariables), null);
}
private RequestFuture sendRequest(JpsRemoteProto.Message.Request request, @Nullable JpsServerResponseHandler handler) {
// @@protoc_insertion_point(class_scope:org.jetbrains.jpsservice.Message.Request.SetupCommand.PathVariable)
}
+ public static final class GlobalLibrary extends
+ com.google.protobuf.GeneratedMessageLite {
+ // Use GlobalLibrary.newBuilder() to construct.
+ private GlobalLibrary() {
+ initFields();
+ }
+ private GlobalLibrary(boolean noInit) {}
+
+ private static final GlobalLibrary defaultInstance;
+ public static GlobalLibrary getDefaultInstance() {
+ return defaultInstance;
+ }
+
+ public GlobalLibrary getDefaultInstanceForType() {
+ return defaultInstance;
+ }
+
+ // required string name = 1;
+ public static final int NAME_FIELD_NUMBER = 1;
+ private boolean hasName;
+ private java.lang.String name_ = "";
+ public boolean hasName() { return hasName; }
+ public java.lang.String getName() { return name_; }
+
+ // optional string homePath = 2;
+ public static final int HOMEPATH_FIELD_NUMBER = 2;
+ private boolean hasHomePath;
+ private java.lang.String homePath_ = "";
+ public boolean hasHomePath() { return hasHomePath; }
+ public java.lang.String getHomePath() { return homePath_; }
+
+ // repeated string path = 3;
+ public static final int PATH_FIELD_NUMBER = 3;
+ private java.util.List<java.lang.String> path_ =
+ java.util.Collections.emptyList();
+ public java.util.List<java.lang.String> getPathList() {
+ return path_;
+ }
+ public int getPathCount() { return path_.size(); }
+ public java.lang.String getPath(int index) {
+ return path_.get(index);
+ }
+
+ private void initFields() {
+ }
+ public final boolean isInitialized() {
+ if (!hasName) return false;
+ return true;
+ }
+
+ public void writeTo(com.google.protobuf.CodedOutputStream output)
+ throws java.io.IOException {
+ getSerializedSize();
+ if (hasName()) {
+ output.writeString(1, getName());
+ }
+ if (hasHomePath()) {
+ output.writeString(2, getHomePath());
+ }
+ for (java.lang.String element : getPathList()) {
+ output.writeString(3, element);
+ }
+ }
+
+ private int memoizedSerializedSize = -1;
+ public int getSerializedSize() {
+ int size = memoizedSerializedSize;
+ if (size != -1) return size;
+
+ size = 0;
+ if (hasName()) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeStringSize(1, getName());
+ }
+ if (hasHomePath()) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeStringSize(2, getHomePath());
+ }
+ {
+ int dataSize = 0;
+ for (java.lang.String element : getPathList()) {
+ dataSize += com.google.protobuf.CodedOutputStream
+ .computeStringSizeNoTag(element);
+ }
+ size += dataSize;
+ size += 1 * getPathList().size();
+ }
+ memoizedSerializedSize = size;
+ return size;
+ }
+
+ public static org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary parseFrom(
+ com.google.protobuf.ByteString data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return newBuilder().mergeFrom(data).buildParsed();
+ }
+ public static org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary parseFrom(
+ com.google.protobuf.ByteString data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return newBuilder().mergeFrom(data, extensionRegistry)
+ .buildParsed();
+ }
+ public static org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary parseFrom(byte[] data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return newBuilder().mergeFrom(data).buildParsed();
+ }
+ public static org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary parseFrom(
+ byte[] data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return newBuilder().mergeFrom(data, extensionRegistry)
+ .buildParsed();
+ }
+ public static org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary parseFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return newBuilder().mergeFrom(input).buildParsed();
+ }
+ public static org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary parseFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return newBuilder().mergeFrom(input, extensionRegistry)
+ .buildParsed();
+ }
+ public static org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary parseDelimitedFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ Builder builder = newBuilder();
+ if (builder.mergeDelimitedFrom(input)) {
+ return builder.buildParsed();
+ } else {
+ return null;
+ }
+ }
+ public static org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary parseDelimitedFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ Builder builder = newBuilder();
+ if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
+ return builder.buildParsed();
+ } else {
+ return null;
+ }
+ }
+ public static org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary parseFrom(
+ com.google.protobuf.CodedInputStream input)
+ throws java.io.IOException {
+ return newBuilder().mergeFrom(input).buildParsed();
+ }
+ public static org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary parseFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return newBuilder().mergeFrom(input, extensionRegistry)
+ .buildParsed();
+ }
+
+ public static Builder newBuilder() { return Builder.create(); }
+ public Builder newBuilderForType() { return newBuilder(); }
+ public static Builder newBuilder(org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary prototype) {
+ return newBuilder().mergeFrom(prototype);
+ }
+ public Builder toBuilder() { return newBuilder(this); }
+
+ public static final class Builder extends
+ com.google.protobuf.GeneratedMessageLite.Builder<
+ org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary, Builder> {
+ private org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary result;
+
+ // Construct using org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary.newBuilder()
+ private Builder() {}
+
+ private static Builder create() {
+ Builder builder = new Builder();
+ builder.result = new org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary();
+ return builder;
+ }
+
+ protected org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary internalGetResult() {
+ return result;
+ }
+
+ public Builder clear() {
+ if (result == null) {
+ throw new IllegalStateException(
+ "Cannot call clear() after build().");
+ }
+ result = new org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary();
+ return this;
+ }
+
+ public Builder clone() {
+ return create().mergeFrom(result);
+ }
+
+ public org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary getDefaultInstanceForType() {
+ return org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary.getDefaultInstance();
+ }
+
+ public boolean isInitialized() {
+ return result.isInitialized();
+ }
+ public org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary build() {
+ if (result != null && !isInitialized()) {
+ throw newUninitializedMessageException(result);
+ }
+ return buildPartial();
+ }
+
+ private org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary buildParsed()
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ if (!isInitialized()) {
+ throw newUninitializedMessageException(
+ result).asInvalidProtocolBufferException();
+ }
+ return buildPartial();
+ }
+
+ public org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary buildPartial() {
+ if (result == null) {
+ throw new IllegalStateException(
+ "build() has already been called on this Builder.");
+ }
+ if (result.path_ != java.util.Collections.EMPTY_LIST) {
+ result.path_ =
+ java.util.Collections.unmodifiableList(result.path_);
+ }
+ org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary returnMe = result;
+ result = null;
+ return returnMe;
+ }
+
+ public Builder mergeFrom(org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary other) {
+ if (other == org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary.getDefaultInstance()) return this;
+ if (other.hasName()) {
+ setName(other.getName());
+ }
+ if (other.hasHomePath()) {
+ setHomePath(other.getHomePath());
+ }
+ if (!other.path_.isEmpty()) {
+ if (result.path_.isEmpty()) {
+ result.path_ = new java.util.ArrayList<java.lang.String>();
+ }
+ result.path_.addAll(other.path_);
+ }
+ return this;
+ }
+
+ public Builder mergeFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ while (true) {
+ int tag = input.readTag();
+ switch (tag) {
+ case 0:
+ return this;
+ default: {
+ if (!parseUnknownField(input, extensionRegistry, tag)) {
+ return this;
+ }
+ break;
+ }
+ case 10: {
+ setName(input.readString());
+ break;
+ }
+ case 18: {
+ setHomePath(input.readString());
+ break;
+ }
+ case 26: {
+ addPath(input.readString());
+ break;
+ }
+ }
+ }
+ }
+
+
+ // required string name = 1;
+ public boolean hasName() {
+ return result.hasName();
+ }
+ public java.lang.String getName() {
+ return result.getName();
+ }
+ public Builder setName(java.lang.String value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ result.hasName = true;
+ result.name_ = value;
+ return this;
+ }
+ public Builder clearName() {
+ result.hasName = false;
+ result.name_ = getDefaultInstance().getName();
+ return this;
+ }
+
+ // optional string homePath = 2;
+ public boolean hasHomePath() {
+ return result.hasHomePath();
+ }
+ public java.lang.String getHomePath() {
+ return result.getHomePath();
+ }
+ public Builder setHomePath(java.lang.String value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ result.hasHomePath = true;
+ result.homePath_ = value;
+ return this;
+ }
+ public Builder clearHomePath() {
+ result.hasHomePath = false;
+ result.homePath_ = getDefaultInstance().getHomePath();
+ return this;
+ }
+
+ // repeated string path = 3;
+ public java.util.List<java.lang.String> getPathList() {
+ return java.util.Collections.unmodifiableList(result.path_);
+ }
+ public int getPathCount() {
+ return result.getPathCount();
+ }
+ public java.lang.String getPath(int index) {
+ return result.getPath(index);
+ }
+ public Builder setPath(int index, java.lang.String value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ result.path_.set(index, value);
+ return this;
+ }
+ public Builder addPath(java.lang.String value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ if (result.path_.isEmpty()) {
+ result.path_ = new java.util.ArrayList<java.lang.String>();
+ }
+ result.path_.add(value);
+ return this;
+ }
+ public Builder addAllPath(
+ java.lang.Iterable<? extends java.lang.String> values) {
+ if (result.path_.isEmpty()) {
+ result.path_ = new java.util.ArrayList<java.lang.String>();
+ }
+ super.addAll(values, result.path_);
+ return this;
+ }
+ public Builder clearPath() {
+ result.path_ = java.util.Collections.emptyList();
+ return this;
+ }
+
+ // @@protoc_insertion_point(builder_scope:org.jetbrains.jpsservice.Message.Request.SetupCommand.GlobalLibrary)
+ }
+
+ static {
+ defaultInstance = new GlobalLibrary(true);
+ org.jetbrains.jpsservice.JpsRemoteProto.internalForceInit();
+ defaultInstance.initFields();
+ }
+
+ // @@protoc_insertion_point(class_scope:org.jetbrains.jpsservice.Message.Request.SetupCommand.GlobalLibrary)
+ }
+
// repeated .org.jetbrains.jpsservice.Message.Request.SetupCommand.PathVariable path_variable = 1;
public static final int PATH_VARIABLE_FIELD_NUMBER = 1;
private java.util.List<org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.PathVariable> pathVariable_ =
return pathVariable_.get(index);
}
+ // repeated .org.jetbrains.jpsservice.Message.Request.SetupCommand.GlobalLibrary global_library = 2;
+ public static final int GLOBAL_LIBRARY_FIELD_NUMBER = 2;
+ private java.util.List<org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary> globalLibrary_ =
+ java.util.Collections.emptyList();
+ public java.util.List<org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary> getGlobalLibraryList() {
+ return globalLibrary_;
+ }
+ public int getGlobalLibraryCount() { return globalLibrary_.size(); }
+ public org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary getGlobalLibrary(int index) {
+ return globalLibrary_.get(index);
+ }
+
private void initFields() {
}
public final boolean isInitialized() {
for (org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.PathVariable element : getPathVariableList()) {
if (!element.isInitialized()) return false;
}
+ for (org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary element : getGlobalLibraryList()) {
+ if (!element.isInitialized()) return false;
+ }
return true;
}
for (org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.PathVariable element : getPathVariableList()) {
output.writeMessage(1, element);
}
+ for (org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary element : getGlobalLibraryList()) {
+ output.writeMessage(2, element);
+ }
}
private int memoizedSerializedSize = -1;
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, element);
}
+ for (org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary element : getGlobalLibraryList()) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeMessageSize(2, element);
+ }
memoizedSerializedSize = size;
return size;
}
result.pathVariable_ =
java.util.Collections.unmodifiableList(result.pathVariable_);
}
+ if (result.globalLibrary_ != java.util.Collections.EMPTY_LIST) {
+ result.globalLibrary_ =
+ java.util.Collections.unmodifiableList(result.globalLibrary_);
+ }
org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand returnMe = result;
result = null;
return returnMe;
}
result.pathVariable_.addAll(other.pathVariable_);
}
+ if (!other.globalLibrary_.isEmpty()) {
+ if (result.globalLibrary_.isEmpty()) {
+ result.globalLibrary_ = new java.util.ArrayList<org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary>();
+ }
+ result.globalLibrary_.addAll(other.globalLibrary_);
+ }
return this;
}
addPathVariable(subBuilder.buildPartial());
break;
}
+ case 18: {
+ org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary.Builder subBuilder = org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary.newBuilder();
+ input.readMessage(subBuilder, extensionRegistry);
+ addGlobalLibrary(subBuilder.buildPartial());
+ break;
+ }
}
}
}
return this;
}
+ // repeated .org.jetbrains.jpsservice.Message.Request.SetupCommand.GlobalLibrary global_library = 2;
+ public java.util.List<org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary> getGlobalLibraryList() {
+ return java.util.Collections.unmodifiableList(result.globalLibrary_);
+ }
+ public int getGlobalLibraryCount() {
+ return result.getGlobalLibraryCount();
+ }
+ public org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary getGlobalLibrary(int index) {
+ return result.getGlobalLibrary(index);
+ }
+ public Builder setGlobalLibrary(int index, org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ result.globalLibrary_.set(index, value);
+ return this;
+ }
+ public Builder setGlobalLibrary(int index, org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary.Builder builderForValue) {
+ result.globalLibrary_.set(index, builderForValue.build());
+ return this;
+ }
+ public Builder addGlobalLibrary(org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ if (result.globalLibrary_.isEmpty()) {
+ result.globalLibrary_ = new java.util.ArrayList<org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary>();
+ }
+ result.globalLibrary_.add(value);
+ return this;
+ }
+ public Builder addGlobalLibrary(org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary.Builder builderForValue) {
+ if (result.globalLibrary_.isEmpty()) {
+ result.globalLibrary_ = new java.util.ArrayList<org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary>();
+ }
+ result.globalLibrary_.add(builderForValue.build());
+ return this;
+ }
+ public Builder addAllGlobalLibrary(
+ java.lang.Iterable<? extends org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary> values) {
+ if (result.globalLibrary_.isEmpty()) {
+ result.globalLibrary_ = new java.util.ArrayList<org.jetbrains.jpsservice.JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary>();
+ }
+ super.addAll(values, result.globalLibrary_);
+ return this;
+ }
+ public Builder clearGlobalLibrary() {
+ result.globalLibrary_ = java.util.Collections.emptyList();
+ return this;
+ }
+
// @@protoc_insertion_point(builder_scope:org.jetbrains.jpsservice.Message.Request.SetupCommand)
}
public boolean hasSourceFilePath() { return hasSourceFilePath; }
public java.lang.String getSourceFilePath() { return sourceFilePath_; }
- // optional uint32 line = 4;
- public static final int LINE_FIELD_NUMBER = 4;
+ // optional uint64 problem_begin_offset = 4;
+ public static final int PROBLEM_BEGIN_OFFSET_FIELD_NUMBER = 4;
+ private boolean hasProblemBeginOffset;
+ private long problemBeginOffset_ = 0L;
+ public boolean hasProblemBeginOffset() { return hasProblemBeginOffset; }
+ public long getProblemBeginOffset() { return problemBeginOffset_; }
+
+ // optional uint64 problem_end_offset = 5;
+ public static final int PROBLEM_END_OFFSET_FIELD_NUMBER = 5;
+ private boolean hasProblemEndOffset;
+ private long problemEndOffset_ = 0L;
+ public boolean hasProblemEndOffset() { return hasProblemEndOffset; }
+ public long getProblemEndOffset() { return problemEndOffset_; }
+
+ // optional uint64 problem_location_offset = 6;
+ public static final int PROBLEM_LOCATION_OFFSET_FIELD_NUMBER = 6;
+ private boolean hasProblemLocationOffset;
+ private long problemLocationOffset_ = 0L;
+ public boolean hasProblemLocationOffset() { return hasProblemLocationOffset; }
+ public long getProblemLocationOffset() { return problemLocationOffset_; }
+
+ // optional uint64 line = 7;
+ public static final int LINE_FIELD_NUMBER = 7;
private boolean hasLine;
- private int line_ = 0;
+ private long line_ = 0L;
public boolean hasLine() { return hasLine; }
- public int getLine() { return line_; }
+ public long getLine() { return line_; }
- // optional uint32 column = 5;
- public static final int COLUMN_FIELD_NUMBER = 5;
+ // optional uint64 column = 8;
+ public static final int COLUMN_FIELD_NUMBER = 8;
private boolean hasColumn;
- private int column_ = 0;
+ private long column_ = 0L;
public boolean hasColumn() { return hasColumn; }
- public int getColumn() { return column_; }
+ public long getColumn() { return column_; }
private void initFields() {
kind_ = org.jetbrains.jpsservice.JpsRemoteProto.Message.Response.CompileMessage.Kind.ERROR;
if (hasSourceFilePath()) {
output.writeString(3, getSourceFilePath());
}
+ if (hasProblemBeginOffset()) {
+ output.writeUInt64(4, getProblemBeginOffset());
+ }
+ if (hasProblemEndOffset()) {
+ output.writeUInt64(5, getProblemEndOffset());
+ }
+ if (hasProblemLocationOffset()) {
+ output.writeUInt64(6, getProblemLocationOffset());
+ }
if (hasLine()) {
- output.writeUInt32(4, getLine());
+ output.writeUInt64(7, getLine());
}
if (hasColumn()) {
- output.writeUInt32(5, getColumn());
+ output.writeUInt64(8, getColumn());
}
}
size += com.google.protobuf.CodedOutputStream
.computeStringSize(3, getSourceFilePath());
}
+ if (hasProblemBeginOffset()) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeUInt64Size(4, getProblemBeginOffset());
+ }
+ if (hasProblemEndOffset()) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeUInt64Size(5, getProblemEndOffset());
+ }
+ if (hasProblemLocationOffset()) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeUInt64Size(6, getProblemLocationOffset());
+ }
if (hasLine()) {
size += com.google.protobuf.CodedOutputStream
- .computeUInt32Size(4, getLine());
+ .computeUInt64Size(7, getLine());
}
if (hasColumn()) {
size += com.google.protobuf.CodedOutputStream
- .computeUInt32Size(5, getColumn());
+ .computeUInt64Size(8, getColumn());
}
memoizedSerializedSize = size;
return size;
if (other.hasSourceFilePath()) {
setSourceFilePath(other.getSourceFilePath());
}
+ if (other.hasProblemBeginOffset()) {
+ setProblemBeginOffset(other.getProblemBeginOffset());
+ }
+ if (other.hasProblemEndOffset()) {
+ setProblemEndOffset(other.getProblemEndOffset());
+ }
+ if (other.hasProblemLocationOffset()) {
+ setProblemLocationOffset(other.getProblemLocationOffset());
+ }
if (other.hasLine()) {
setLine(other.getLine());
}
break;
}
case 32: {
- setLine(input.readUInt32());
+ setProblemBeginOffset(input.readUInt64());
break;
}
case 40: {
- setColumn(input.readUInt32());
+ setProblemEndOffset(input.readUInt64());
+ break;
+ }
+ case 48: {
+ setProblemLocationOffset(input.readUInt64());
+ break;
+ }
+ case 56: {
+ setLine(input.readUInt64());
+ break;
+ }
+ case 64: {
+ setColumn(input.readUInt64());
break;
}
}
return this;
}
- // optional uint32 line = 4;
+ // optional uint64 problem_begin_offset = 4;
+ public boolean hasProblemBeginOffset() {
+ return result.hasProblemBeginOffset();
+ }
+ public long getProblemBeginOffset() {
+ return result.getProblemBeginOffset();
+ }
+ public Builder setProblemBeginOffset(long value) {
+ result.hasProblemBeginOffset = true;
+ result.problemBeginOffset_ = value;
+ return this;
+ }
+ public Builder clearProblemBeginOffset() {
+ result.hasProblemBeginOffset = false;
+ result.problemBeginOffset_ = 0L;
+ return this;
+ }
+
+ // optional uint64 problem_end_offset = 5;
+ public boolean hasProblemEndOffset() {
+ return result.hasProblemEndOffset();
+ }
+ public long getProblemEndOffset() {
+ return result.getProblemEndOffset();
+ }
+ public Builder setProblemEndOffset(long value) {
+ result.hasProblemEndOffset = true;
+ result.problemEndOffset_ = value;
+ return this;
+ }
+ public Builder clearProblemEndOffset() {
+ result.hasProblemEndOffset = false;
+ result.problemEndOffset_ = 0L;
+ return this;
+ }
+
+ // optional uint64 problem_location_offset = 6;
+ public boolean hasProblemLocationOffset() {
+ return result.hasProblemLocationOffset();
+ }
+ public long getProblemLocationOffset() {
+ return result.getProblemLocationOffset();
+ }
+ public Builder setProblemLocationOffset(long value) {
+ result.hasProblemLocationOffset = true;
+ result.problemLocationOffset_ = value;
+ return this;
+ }
+ public Builder clearProblemLocationOffset() {
+ result.hasProblemLocationOffset = false;
+ result.problemLocationOffset_ = 0L;
+ return this;
+ }
+
+ // optional uint64 line = 7;
public boolean hasLine() {
return result.hasLine();
}
- public int getLine() {
+ public long getLine() {
return result.getLine();
}
- public Builder setLine(int value) {
+ public Builder setLine(long value) {
result.hasLine = true;
result.line_ = value;
return this;
}
public Builder clearLine() {
result.hasLine = false;
- result.line_ = 0;
+ result.line_ = 0L;
return this;
}
- // optional uint32 column = 5;
+ // optional uint64 column = 8;
public boolean hasColumn() {
return result.hasColumn();
}
- public int getColumn() {
+ public long getColumn() {
return result.getColumn();
}
- public Builder setColumn(int value) {
+ public Builder setColumn(long value) {
result.hasColumn = true;
result.column_ = value;
return this;
}
public Builder clearColumn() {
result.hasColumn = false;
- result.column_ = 0;
+ result.column_ = 0L;
return this;
}
import org.jboss.netty.channel.*;
import org.jetbrains.annotations.Nullable;
-import org.jetbrains.jps.server.BuildParameters;
-import org.jetbrains.jps.server.BuildType;
-import org.jetbrains.jps.server.Facade;
-import org.jetbrains.jps.server.MessagesConsumer;
+import org.jetbrains.jps.incremental.MessageHandler;
+import org.jetbrains.jps.incremental.messages.BuildMessage;
+import org.jetbrains.jps.incremental.messages.CompilerMessage;
+import org.jetbrains.jps.server.*;
import org.jetbrains.jpsservice.JpsRemoteProto;
import org.jetbrains.jpsservice.Server;
else {
final JpsRemoteProto.Message.Request request = message.getRequest();
final JpsRemoteProto.Message.Request.Type requestType = request.getRequestType();
+ final Facade facade = Facade.getInstance();
switch (requestType) {
case COMPILE_REQUEST :
reply = startBuild(sessionId, ctx, request.getCompileRequest());
break;
-
+ case RELOAD_PROJECT_COMMAND:
+ final JpsRemoteProto.Message.Request.ReloadProjectCommand reloadProjectCommand = request.getReloadProjectCommand();
+ facade.clearProjectCache(reloadProjectCommand.getProjectIdList());
+ break;
case SETUP_COMMAND:
- final Map<String, String> data = new HashMap<String, String>();
+ final Map<String, String> pathVars = new HashMap<String, String>();
final JpsRemoteProto.Message.Request.SetupCommand setupCommand = request.getSetupCommand();
for (JpsRemoteProto.Message.Request.SetupCommand.PathVariable variable : setupCommand.getPathVariableList()) {
- data.put(variable.getName(), variable.getValue());
+ pathVars.put(variable.getName(), variable.getValue());
+ }
+ final List<GlobalLibrary> libs = new ArrayList<GlobalLibrary>();
+ for (JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary library : setupCommand.getGlobalLibraryList()) {
+ libs.add(
+ library.hasHomePath()?
+ new SdkLibrary(library.getName(), library.getHomePath(), library.getPathList()) :
+ new GlobalLibrary(library.getName(), library.getPathList())
+ );
}
- Facade.getInstance().setPathVariables(data);
+ facade.setGlobals(libs, pathVars);
reply = ProtoUtil.toMessage(sessionId, ProtoUtil.createCommandCompletedEvent(null));
break;
final JpsRemoteProto.Message.Request.CompilationRequest.Type compileType = compileRequest.getCommandType();
switch (compileType) {
+ // todo
case CLEAN:
case MAKE:
case REBUILD: {
Channels.write(myChannelContext.getChannel(), ProtoUtil.toMessage(mySessionId, ProtoUtil.createBuildStartedEvent("build started")));
Throwable error = null;
try {
- Facade.getInstance().startBuild(myProjectPath, myModules, myParams, new MessagesConsumer() {
- public void consumeProgressMessage(String message) {
- Channels.write(
- myChannelContext.getChannel(), ProtoUtil.toMessage(mySessionId, ProtoUtil.createCompileProgressMessageResponse(message))
- );
- }
-
- public void consumeCompilerMessage(String compilerName, String message) {
- final JpsRemoteProto.Message.Response.CompileMessage.Kind kind =
- message.contains("error:")? JpsRemoteProto.Message.Response.CompileMessage.Kind.ERROR : JpsRemoteProto.Message.Response.CompileMessage.Kind.INFO;
- Channels.write(
- myChannelContext.getChannel(), ProtoUtil.toMessage(mySessionId, ProtoUtil.createCompileMessageResponse(kind, message, null, -1, -1))
- );
+ Facade.getInstance().startBuild(myProjectPath, myModules, myParams, new MessageHandler() {
+ public void processMessage(BuildMessage buildMessage) {
+ final JpsRemoteProto.Message.Response response;
+ if (buildMessage instanceof CompilerMessage) {
+ final CompilerMessage compilerMessage = (CompilerMessage)buildMessage;
+ response = ProtoUtil.createCompileMessageResponse(
+ compilerMessage.getKind(), compilerMessage.getMessageText(), compilerMessage.getSourcePath(),
+ compilerMessage.getProblemBeginOffset(), compilerMessage.getProblemEndOffset(),
+ compilerMessage.getProblemLocationOffset(), compilerMessage.getLine(), compilerMessage.getColumn()
+ );
+ }
+ else {
+ response = ProtoUtil.createCompileProgressMessageResponse(buildMessage.getMessageText());
+ }
+ Channels.write(myChannelContext.getChannel(), ProtoUtil.toMessage(mySessionId, response));
}
});
}
package org.jetbrains.jpsservice.impl;
import org.jetbrains.annotations.Nullable;
+import org.jetbrains.jps.incremental.messages.BuildMessage;
+import org.jetbrains.jps.incremental.messages.CompilerMessage;
+import org.jetbrains.jps.server.GlobalLibrary;
+import org.jetbrains.jps.server.SdkLibrary;
import org.jetbrains.jpsservice.JpsRemoteProto;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Map;
-import java.util.UUID;
+import java.util.*;
/**
* @author Eugene Zhuravlev
return JpsRemoteProto.Message.Request.newBuilder().setRequestType(JpsRemoteProto.Message.Request.Type.RELOAD_PROJECT_COMMAND).setReloadProjectCommand(builder.build()).build();
}
- public static JpsRemoteProto.Message.Request createSetupRequest(final Map<String, String> pathVars) {
+ public static JpsRemoteProto.Message.Request createSetupRequest(final Map<String, String> pathVars, List<GlobalLibrary> sdkAndLibs) {
final JpsRemoteProto.Message.Request.SetupCommand.Builder cmdBuilder = JpsRemoteProto.Message.Request.SetupCommand.newBuilder();
- if (pathVars.size() > 0) {
- final JpsRemoteProto.Message.Request.SetupCommand.PathVariable.Builder pathVarBuilder =
- JpsRemoteProto.Message.Request.SetupCommand.PathVariable.newBuilder();
-
+ if (!pathVars.isEmpty()) {
for (Map.Entry<String, String> entry : pathVars.entrySet()) {
final String var = entry.getKey();
final String value = entry.getValue();
if (var != null && value != null) {
+ final JpsRemoteProto.Message.Request.SetupCommand.PathVariable.Builder pathVarBuilder =
+ JpsRemoteProto.Message.Request.SetupCommand.PathVariable.newBuilder();
cmdBuilder.addPathVariable(pathVarBuilder.setName(var).setValue(value).build());
}
}
}
+ if (!sdkAndLibs.isEmpty()) {
+ for (GlobalLibrary lib : sdkAndLibs) {
+ final JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary.Builder libBuilder =
+ JpsRemoteProto.Message.Request.SetupCommand.GlobalLibrary.newBuilder();
+ libBuilder.setName(lib.getName()).addAllPath(lib.getPaths());
+ if (lib instanceof SdkLibrary) {
+ libBuilder.setHomePath(((SdkLibrary)lib).getHomePath());
+ }
+ cmdBuilder.addGlobalLibrary(libBuilder.build());
+ }
+ }
+
return JpsRemoteProto.Message.Request.newBuilder().setRequestType(JpsRemoteProto.Message.Request.Type.SETUP_COMMAND).setSetupCommand(cmdBuilder.build()).build();
}
}
public static JpsRemoteProto.Message.Response createCompileInfoMessageResponse(String text, String path) {
- return createCompileMessageResponse(JpsRemoteProto.Message.Response.CompileMessage.Kind.INFO, text, path, -1, -1);
+ return createCompileMessageResponse(BuildMessage.Kind.PROGRESS, text, path, -1L, -1L, -1L, -1, -1);
}
public static JpsRemoteProto.Message.Response createCompileProgressMessageResponse(String text) {
- return createCompileMessageResponse(JpsRemoteProto.Message.Response.CompileMessage.Kind.PROGRESS, text, null, -1, -1);
- }
-
- public static JpsRemoteProto.Message.Response createCompileWarningMessageResponse(String text, String path, int line, int column) {
- return createCompileMessageResponse(JpsRemoteProto.Message.Response.CompileMessage.Kind.WARNING, text, path, line, column);
- }
-
- public static JpsRemoteProto.Message.Response createCompileErrorMessageResponse(String text, String path, int line, int column) {
- return createCompileMessageResponse(JpsRemoteProto.Message.Response.CompileMessage.Kind.ERROR, text, path, line, column);
- }
-
- public static JpsRemoteProto.Message.Response createCompileMessageResponse(final JpsRemoteProto.Message.Response.CompileMessage.Kind msgKind, String text, String path, int line, int column) {
- final JpsRemoteProto.Message.Response.CompileMessage.Builder builder = JpsRemoteProto.Message.Response.CompileMessage.newBuilder().setKind(msgKind);
+ return createCompileMessageResponse(BuildMessage.Kind.PROGRESS, text, null, -1L, -1L, -1L, -1, -1);
+ }
+
+ public static JpsRemoteProto.Message.Response createCompileErrorMessageResponse(String text, String path,
+ long beginOffset,
+ long endOffset,
+ long offset,
+ long line,
+ long column) {
+ return createCompileMessageResponse(CompilerMessage.Kind.ERROR, text, path, beginOffset, endOffset, offset, line, column);
+ }
+
+ public static JpsRemoteProto.Message.Response createCompileMessageResponse(final BuildMessage.Kind kind,
+ String text,
+ String path,
+ long beginOffset, long endOffset, long offset, long line,
+ long column) {
+
+ final JpsRemoteProto.Message.Response.CompileMessage.Builder builder = JpsRemoteProto.Message.Response.CompileMessage.newBuilder();
+ switch (kind) {
+ case ERROR:
+ builder.setKind(JpsRemoteProto.Message.Response.CompileMessage.Kind.ERROR);
+ break;
+ case WARNING:
+ builder.setKind(JpsRemoteProto.Message.Response.CompileMessage.Kind.WARNING);
+ break;
+ case INFO:
+ builder.setKind(JpsRemoteProto.Message.Response.CompileMessage.Kind.INFO);
+ break;
+ default:
+ builder.setKind(JpsRemoteProto.Message.Response.CompileMessage.Kind.PROGRESS);
+ }
if (text != null) {
builder.setText(text);
}
if (path != null) {
builder.setSourceFilePath(path);
}
- if (line >=0) {
+ 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 >=0) {
+ if (column > 0L) {
builder.setColumn(column);
}
return JpsRemoteProto.Message.Response.newBuilder().setResponseType(JpsRemoteProto.Message.Response.Type.COMPILE_MESSAGE).setCompileMessage(builder.build()).build();
*/
package com.intellij.compiler;
+import com.intellij.ProjectTopics;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.project.ProjectManager;
+import com.intellij.openapi.project.ProjectManagerAdapter;
import com.intellij.openapi.projectRoots.JavaSdkType;
+import com.intellij.openapi.projectRoots.ProjectJdkTable;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl;
+import com.intellij.openapi.roots.ModuleRootEvent;
+import com.intellij.openapi.roots.ModuleRootListener;
+import com.intellij.openapi.roots.OrderRootType;
+import com.intellij.openapi.roots.libraries.Library;
+import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar;
import com.intellij.openapi.util.ShutDownTracker;
+import com.intellij.openapi.util.io.FileUtil;
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.openapi.vfs.JarFileSystem;
+import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.net.NetUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
+import org.jetbrains.jps.server.GlobalLibrary;
+import org.jetbrains.jps.server.SdkLibrary;
import org.jetbrains.jpsservice.Bootstrap;
import org.jetbrains.jpsservice.Client;
import java.io.File;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
private volatile Client myServerClient;
private volatile OSProcessHandler myProcessHandler;
- public JpsServerManager() {
+ public JpsServerManager(ProjectManager projectManager) {
+ projectManager.addProjectManagerListener(new ProjectWatcher());
ShutDownTracker.getInstance().registerShutdownTask(new Runnable() {
@Override
public void run() {
final PathMacros pathVars = PathMacros.getInstance();
final Map<String, String> data = new HashMap<String, String>();
for (String name : pathVars.getAllMacroNames()) {
- data.put(name, pathVars.getValue(name));
+ final String path = pathVars.getValue(name);
+ if (path != null) {
+ data.put(name, FileUtil.toSystemIndependentName(path));
+ }
}
- myServerClient.sendSetupRequest(data);
+ final List<GlobalLibrary> globals = new ArrayList<GlobalLibrary>();
+
+ fillSdks(globals);
+ fillGlobalLibraries(globals);
+
+ myServerClient.sendSetupRequest(data, globals);
}
myProcessHandler = processHandler;
return false;
}
+ private static void fillSdks(List<GlobalLibrary> globals) {
+ for (Sdk sdk : ProjectJdkTable.getInstance().getAllJdks()) {
+ final String name = sdk.getName();
+ final String homePath = sdk.getHomePath();
+ if (homePath == null) {
+ continue;
+ }
+ final List<String> paths = convertToLocalPaths(sdk.getRootProvider().getFiles(OrderRootType.CLASSES));
+ globals.add(new SdkLibrary(name, homePath, paths));
+ }
+ }
+
+ private static void fillGlobalLibraries(List<GlobalLibrary> globals) {
+ final Iterator<Library> iterator = LibraryTablesRegistrar.getInstance().getLibraryTable().getLibraryIterator();
+ while (iterator.hasNext()) {
+ Library library = iterator.next();
+ final String name = library.getName();
+
+ if (name != null) {
+ final List<String> paths = convertToLocalPaths(library.getFiles(OrderRootType.CLASSES));
+ globals.add(new GlobalLibrary(name, paths));
+ }
+ }
+ }
+
+ private static List<String> convertToLocalPaths(VirtualFile[] files) {
+ final List<String> paths = new ArrayList<String>();
+ for (VirtualFile file : files) {
+ if (file.isValid()) {
+ paths.add(StringUtil.trimEnd(FileUtil.toSystemIndependentName(file.getPath()), JarFileSystem.JAR_SEPARATOR));
+ }
+ }
+ return paths;
+ }
+
private static Process launchServer(int port) throws ExecutionException {
final Sdk projectJdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk();
final GeneralCommandLine cmdLine = new GeneralCommandLine();
cmdLine.setExePath(((JavaSdkType)projectJdk.getSdkType()).getVMExecutablePath(projectJdk));
+ //cmdLine.addParameter("-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5007");
cmdLine.addParameter("-Xmx256m");
cmdLine.addParameter("-classpath");
}
return builder.toString();
}
+
+ private class ProjectWatcher extends ProjectManagerAdapter {
+ private final Map<Project, MessageBusConnection> myConnections = new HashMap<Project, MessageBusConnection>();
+
+ public void projectOpened(final Project project) {
+ final MessageBusConnection conn = project.getMessageBus().connect();
+ myConnections.put(project, conn);
+ conn.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootListener() {
+ public void beforeRootsChange(final ModuleRootEvent event) {
+ sendReloadRequest(project);
+ }
+
+ public void rootsChanged(final ModuleRootEvent event) {
+ }
+ });
+
+ }
+
+ public void projectClosing(Project project) {
+ sendReloadRequest(project);
+ }
+
+ public void projectClosed(Project project) {
+ final MessageBusConnection conn = myConnections.remove(project);
+ if (conn != null) {
+ conn.disconnect();
+ }
+ }
+
+ private void sendReloadRequest(Project project) {
+ final Client client = myServerClient;
+ if (client != null) {
+ try {
+ client.sendProjectReloadRequest(Collections.singletonList(project.getLocation()));
+ }
+ catch (Exception e) {
+ LOG.info(e);
+ }
+ }
+ }
+ }
}
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileEditor.FileDocumentManager;
+import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.module.LanguageLevelUtil;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.openapi.wm.WindowManager;
+import com.intellij.pom.Navigatable;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.util.*;
else {
final CompilerMessageCategory category = kind == JpsRemoteProto.Message.Response.CompileMessage.Kind.ERROR ? CompilerMessageCategory.ERROR
: kind == JpsRemoteProto.Message.Response.CompileMessage.Kind.WARNING ? CompilerMessageCategory.WARNING : CompilerMessageCategory.INFORMATION;
- compileContext.addMessage(category, compilerMessage.getText(), compilerMessage.getSourceFilePath(), compilerMessage.getLine(),
- compilerMessage.getColumn());
+ Navigatable navigatable = null;
+
+ String sourceFilePath = compilerMessage.hasSourceFilePath()? compilerMessage.getSourceFilePath() : null;
+ if (sourceFilePath != null) {
+ sourceFilePath = FileUtil.toSystemIndependentName(sourceFilePath);
+ }
+ final long offset = compilerMessage.hasProblemLocationOffset()? compilerMessage.getProblemLocationOffset() : -1L;
+ if (sourceFilePath != null && offset >= 0L) {
+ final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(sourceFilePath);
+ if (file != null) {
+ navigatable = new OpenFileDescriptor(myProject, file, (int)offset);
+ }
+ }
+ final String srcUrl = sourceFilePath != null? VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, sourceFilePath) : null;
+ compileContext.addMessage(
+ category, compilerMessage.getText(), srcUrl, (int)compilerMessage.getLine(), (int)compilerMessage.getColumn(), navigatable
+ );
}
}
import com.intellij.openapi.compiler.CompileStatusNotification;
import com.intellij.openapi.compiler.CompilerManager;
import com.intellij.openapi.project.Project;
-import com.intellij.util.containers.SequenceIterator;
+import com.intellij.util.containers.ContainerUtil;
-import java.util.Collection;
-import java.util.Iterator;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
/**
* @author cdr
final CompilerManager compilerManager = CompilerManager.getInstance(project);
final CompilerConfigurationImpl configuration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(project);
- Collection<BackendCompiler> compilers = configuration.getRegisteredJavaCompilers();
- final Iterator<BackendCompiler> it = new SequenceIterator<BackendCompiler>(compilers.iterator(),compilers.iterator(),compilers.iterator(),compilers.iterator(),compilers.iterator(),compilers.iterator(),compilers.iterator());
+ List<BackendCompiler> compilers = (List<BackendCompiler>)configuration.getRegisteredJavaCompilers();
+ final List<BackendCompiler> allCompilers = ContainerUtil.concat(compilers, compilers, compilers, compilers, compilers, compilers, compilers);
+ final int[] i = new int[1];
CompileStatusNotification callback = new CompileStatusNotification() {
volatile long start;
return;
}
final long finish = System.currentTimeMillis();
- //System.out.println("Compiled with " +
- // compiler.getName() +
- // " in " +
- // TimeUnit.MILLISECONDS.toMinutes(finish - start) + "m" +TimeUnit.MILLISECONDS.toSeconds((finish - start)%60000) + "s" +
- // " with " +
- // errors +
- // " errors, " +
- // warnings +
- // " warnings, aborted=" +
- // aborted+"; free memory="+Runtime.getRuntime().freeMemory()+" bytes");
+ System.out.println("Compiled with '" +
+ compiler.getPresentableName() + "' " +
+ " in " +
+ TimeUnit.MILLISECONDS.toMinutes(finish - start) + "m" +
+ TimeUnit.MILLISECONDS.toSeconds((finish - start)%60000) + "s" +
+ " with " +
+ errors +
+ " errors, " +
+ warnings +
+ " warnings, aborted=" +
+ aborted+"; free memory="+Runtime.getRuntime().freeMemory()+" bytes");
//ProfilingUtil.forceCaptureMemorySnapshot();
next();
}
void next() {
- if (!it.hasNext()) return;
- compiler = it.next();
+ if (i[0] >= allCompilers.size()) return;
+ compiler = allCompilers.get(i[0]++);
if (compiler.getId().equals("Jikes")|| compiler.getId().contains("Eclipse")) {
next();
return;
List<JavaFileObject> result = new ArrayList<JavaFileObject>(size);
for (File file : files) {
- JavaFileObject fileObject = new JavaVirtualByIoFile(file, JavaFileObject.Kind.SOURCE);
+ JavaFileObject fileObject = new JavaIoFile(file, JavaFileObject.Kind.SOURCE);
result.add(fileObject);
}
if (results == null) results = new SmartList<JavaFileObject>();
if (kind == JavaFileObject.Kind.SOURCE && child.getFileSystem() instanceof JarFileSystem) continue; //for some reasdon javac looks for java files inside jar
- // do not use VFS to read .class content
- JavaFileObject fileObject =
- kind == JavaFileObject.Kind.CLASS && child.getFileSystem() == LocalFileSystem.getInstance() ?
- new JavaIoFile(new File(child.getPath()), kind) : new JavaVirtualFile(child, kind);
+ // use VFS to read content inside .jar
+ JavaFileObject fileObject = !child.getPath().contains("!/") ? new JavaIoFile(new File(child.getPath()), kind) : new JavaVirtualFile(child, kind);
results.add(fileObject);
}
}
@Override
public boolean isSameFile(FileObject a, FileObject b) {
- if ((a instanceof FileVirtualObject && b instanceof FileVirtualObject) || (a instanceof Output && b instanceof Output)) {
+ if (a instanceof FileVirtualObject && b instanceof FileVirtualObject || a instanceof Output && b instanceof Output) {
return a.equals(b);
}
return myStandardFileManager.isSameFile(a, b);
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
-import com.intellij.openapi.roots.*;
+import com.intellij.openapi.roots.OrderEnumerator;
+import com.intellij.openapi.roots.OrderRootType;
+import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.packaging.elements.*;
import com.intellij.packaging.impl.elements.LibraryPackagingElement;
import com.intellij.packaging.impl.elements.ManifestFileUtil;
+import com.intellij.util.CommonProcessors;
import com.intellij.util.PathUtil;
import com.intellij.util.Processor;
-import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.Nullable;
if (!includeTests) {
orderEnumerator = orderEnumerator.productionOnly();
}
- orderEnumerator.using(myContext.getModulesProvider()).withoutSdk().runtimeOnly().recursively().forEach(new Processor<OrderEntry>() {
+ final OrderEnumerator enumerator = orderEnumerator.using(myContext.getModulesProvider()).withoutSdk().runtimeOnly().recursively();
+ enumerator.forEachLibrary(new CommonProcessors.CollectProcessor<Library>(libraries));
+ enumerator.forEachModule(new Processor<Module>() {
@Override
- public boolean process(OrderEntry orderEntry) {
- if (orderEntry instanceof ModuleSourceOrderEntry) {
- Module module = orderEntry.getOwnerModule();
- archive.addOrFindChild(factory.createModuleOutput(module));
- if (includeTests) {
- archive.addOrFindChild(factory.createTestModuleOutput(module));
- }
- }
- else if (orderEntry instanceof LibraryOrderEntry) {
- ContainerUtil.addIfNotNull(((LibraryOrderEntry)orderEntry).getLibrary(), libraries);
+ public boolean process(Module module) {
+ archive.addOrFindChild(factory.createModuleOutput(module));
+ if (includeTests) {
+ archive.addOrFindChild(factory.createTestModuleOutput(module));
}
return true;
}
<properties>
<componentClass value="javax.swing.JComboBox"/>
<labelLocation value="West"/>
- <text resource-bundle="messages/ExecutionBundle" key="applet.configuration.use.classpath.and.jdk.of.module.label"/>
+ <text resource-bundle="messages/ExecutionBundle" key="application.configuration.use.classpath.and.jdk.of.module.label"/>
</properties>
</component>
<grid id="c178e" layout-manager="GridLayoutManager" row-count="2" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
*/
package com.intellij.openapi.roots.ui.configuration;
+import com.intellij.ui.awt.RelativePoint;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
/**
* Called when user invokes "Fix" action
*/
- public void fix(JComponent contextComponent) {
+ public void fix(JComponent contextComponent, RelativePoint relativePoint) {
}
public boolean canBeFixed() {
/*
- * Copyright 2000-2010 JetBrains s.r.o.
+ * Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.wm.impl.content.GraphicsConfig;
+import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.labels.LinkLabel;
if (deepestComponentAt instanceof ToolbarAlikeButton) {
final String name = ((ToolbarAlikeButton)deepestComponentAt).getButtonName();
if (FIX_ACTION_NAME.equals(name)) {
- onClickFix(error, (JComponent)deepestComponentAt);
+ onClickFix(error, (JComponent)deepestComponentAt, e);
}
else if (NAVIGATE_ACTION_NAME.equals(name)) {
error.navigate();
}
}
- private void onClickFix(@NotNull final ConfigurationError error, JComponent component) {
- error.fix(component);
+ private void onClickFix(@NotNull final ConfigurationError error, JComponent component, MouseEvent e) {
+ error.fix(component, new RelativePoint(e));
}
@Override
}
@Override
- public void onClick() {
+ public void onClick(MouseEvent e) {
onViewChange();
}
}, BorderLayout.NORTH);
myBehavior = new BaseButtonBehavior(this, TimedDeadzone.NULL) {
@Override
protected void execute(MouseEvent e) {
- onClick();
+ onClick(e);
}
};
return myName;
}
- public void onClick() {}
+ public void onClick(MouseEvent e) {}
@Override
public Insets getInsets() {
myFakeTextPane.setBorder(BorderFactory.createEmptyBorder(3, 0, 3, 0));
myText.setOpaque(false);
if (UIUtil.isUnderNimbusLookAndFeel()) {
- myText.setBackground(new Color(0, 0, 0, 0));
+ myText.setBackground(UIUtil.TRANSPARENT_COLOR);
}
myText.setEditable(false);
}
@Override
- public void onClick() {
+ public void onClick(MouseEvent e) {
final Object o = myModel.getElementAt(0);
if (o instanceof ConfigurationError) {
- ((ConfigurationError)o).fix(this);
+ ((ConfigurationError)o).fix(this, new RelativePoint(e));
updateView();
final Container ancestor = SwingUtilities.getAncestorOfClass(ConfigurationErrorsComponent.class, this);
if (ancestor != null && ancestor instanceof JComponent) {
}
@Override
- public void onClick() {
+ public void onClick(MouseEvent e) {
final Object o = myModel.getElementAt(0);
if (o instanceof ConfigurationError) {
((ConfigurationError)o).navigate();
}
@Override
- public void onClick() {
+ public void onClick(MouseEvent e) {
final Object o = myModel.getElementAt(0);
if (o instanceof ConfigurationError) {
((ConfigurationError)o).ignore(!((ConfigurationError)o).isIgnored());
return Collections.emptyList();
}
- @Override
- public boolean highlightIfUnused() {
- return false;
- }
-
@Override
public String getId() {
return "project:general";
if (module == moduleEditor.getModule() && Comparing.strEqual(moduleEditor.getName(), oldName)) {
moduleEditor.setModuleName(name);
moduleEditor.updateCompilerOutputPathChanged(ProjectStructureConfigurable.getInstance(myProject).getProjectConfig().getCompilerOutputUrl(), name);
- myContext.getDaemonAnalyzer().queueUpdate(new ModuleProjectStructureElement(myContext, module), true, false);
+ myContext.getDaemonAnalyzer().queueUpdate(new ModuleProjectStructureElement(myContext, module));
return;
}
}
updateCircularDependencyWarning();
}
}
-
- @Override
- public void allProblemsChanged() {
- updateCircularDependencyWarning();
- }
});
init(model);
}
private JPanel myMainPanel;
private JButton myFixButton;
private JLabel myErrorLabel;
- private List<ConfigurationErrorQuickFix> myCurrentQuickFixes;
+ private List<? extends ConfigurationErrorQuickFix> myCurrentQuickFixes;
private String myErrorText;
public ArtifactErrorPanel(final ArtifactEditorImpl artifactEditor) {
artifactEditor.queueValidation();
}
- public void showError(@NotNull String message, @NotNull List<ConfigurationErrorQuickFix> quickFixes) {
+ public void showError(@NotNull String message, @NotNull List<? extends ConfigurationErrorQuickFix> quickFixes) {
myErrorLabel.setVisible(true);
final String errorText = "<html>" + message + "</html>";
if (myErrorLabel.isShowing()) {
return myOriginalArtifact.hashCode();
}
- @Override
- public boolean highlightIfUnused() {
- return false;
- }
-
@Override
public String getPresentableName() {
return "Artifact '" + getActualArtifactName() + "'";
if (problemDescriptions != null) {
for (ProjectStructureProblemDescription description : problemDescriptions) {
final String message = description.getMessage();
- List<ConfigurationErrorQuickFix> quickFixes = Collections.emptyList();
+ List<? extends ConfigurationErrorQuickFix> quickFixes = Collections.emptyList();
if (description instanceof ArtifactProblemDescription) {
final ArtifactProblemDescription artifactProblem = (ArtifactProblemDescription)description;
quickFixes = artifactProblem.getFixes();
context.getModulesConfigurator().addAllModuleChangeListener(new ModuleEditor.ChangeListener() {
public void moduleStateChanged(ModifiableRootModel moduleRootModel) {
for (ProjectStructureElement element : getProjectStructureElements()) {
- myContext.getDaemonAnalyzer().queueUpdate(element, true, false);
+ myContext.getDaemonAnalyzer().queueUpdate(element);
}
}
});
}
}
}
-
- public void allProblemsChanged() {
- for (Map.Entry<Artifact, ArtifactEditorImpl> entry : myArtifactEditors.entrySet()) {
- updateProblems(entry.getKey(), entry.getValue());
- }
- }
});
}
}
public void queueValidation(Artifact artifact) {
- myContext.getDaemonAnalyzer().queueUpdate(getOrCreateArtifactElement(artifact), true, false);
+ myContext.getDaemonAnalyzer().queueUpdate(getOrCreateArtifactElement(artifact));
}
public CompositePackagingElement<?> getRootElement(@NotNull Artifact artifact) {
import com.intellij.openapi.roots.libraries.ui.OrderRoot;
import com.intellij.openapi.roots.ui.configuration.classpath.ClasspathPanel;
import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesModifiableModel;
+import com.intellij.openapi.roots.ui.configuration.projectRoot.ModuleStructureConfigurable;
import com.intellij.openapi.ui.popup.PopupStep;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.PathUtil;
import com.intellij.util.PlatformIcons;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.*;
}
};
}
+
+ public static List<Module> getSuitableModules(@NotNull ModuleStructureConfigurable rootConfigurable, final @Nullable LibraryType type) {
+ final List<Module> modules = new ArrayList<Module>();
+ for (Module module : rootConfigurable.getModules()) {
+ if (type == null || type.isSuitableModule(module, rootConfigurable.getFacetConfigurator())) {
+ modules.add(module);
+ }
+ }
+ return modules;
+ }
}
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
-import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.libraries.Library;
rootConfigurable.selectNodeInTree(libraryNode);
}
- private static List<Module> getSuitableModules(@NotNull ModuleStructureConfigurable rootConfigurable, final @Nullable LibraryType type) {
- final List<Module> modules = new ArrayList<Module>();
- for (Module module : rootConfigurable.getModules()) {
- if (type == null || type.isSuitableModule(module, rootConfigurable.getFacetConfigurator())) {
- modules.add(module);
- }
- }
- return modules;
- }
-
public static AnAction[] createActionOrGroup(@NotNull String text, @NotNull BaseLibrariesConfigurable librariesConfigurable, final @NotNull Project project) {
final LibraryType<?>[] extensions = LibraryType.EP_NAME.getExtensions();
List<LibraryType<?>> suitableTypes = new ArrayList<LibraryType<?>>();
if (librariesConfigurable instanceof ProjectLibrariesConfigurable) {
final ModuleStructureConfigurable configurable = ModuleStructureConfigurable.getInstance(project);
for (LibraryType<?> extension : extensions) {
- if (!getSuitableModules(configurable, extension).isEmpty()) {
+ if (!LibraryEditingUtil.getSuitableModules(configurable, extension).isEmpty()) {
suitableTypes.add(extension);
}
}
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.roots.libraries.LibraryTablePresentation;
+import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar;
import com.intellij.openapi.roots.ui.configuration.artifacts.UsageInArtifact;
import com.intellij.openapi.roots.ui.configuration.libraries.LibraryEditingUtil;
import com.intellij.openapi.roots.ui.configuration.libraryEditor.CreateNewLibraryAction;
super(project);
}
+ public static BaseLibrariesConfigurable getInstance(@NotNull Project project, @NotNull String tableLevel) {
+ if (tableLevel.equals(LibraryTablesRegistrar.PROJECT_LEVEL)) {
+ return ProjectLibrariesConfigurable.getInstance(project);
+ }
+ else {
+ return GlobalLibrariesConfigurable.getInstance(project);
+ }
+ }
public abstract LibraryTablePresentation getLibraryTablePresentation();
}
}
- public void removeLibraryNode(@NotNull Library library) {
- final MyNode node = findNodeByObject(myRoot, library);
+ public void removeLibrary(@NotNull LibraryProjectStructureElement element) {
+ getModelProvider().getModifiableModel().removeLibrary(element.getLibrary());
+ myContext.getDaemonAnalyzer().removeElement(element);
+ final MyNode node = findNodeByObject(myRoot, element.getLibrary());
if (node != null) {
removePaths(TreeUtil.getPathFromRoot(node));
}
updateTree();
}
- public void allProblemsChanged() {
- updateTree();
- }
-
private void updateTree() {
if (!myTree.isShowing()) return;
final ProjectStructureElement selectedElement = mySourceConfigurable.getSelectedElement();
if (!(selectedElement instanceof LibraryProjectStructureElement)) return;
final StructureConfigurableContext context = mySourceConfigurable.myContext;
- final Library originalLibrary = ((LibraryProjectStructureElement)selectedElement).getLibrary();
- final LibraryEx oldLibrary = (LibraryEx)context.getLibrary(originalLibrary.getName(), mySourceConfigurable.getLevel());
+ final LibraryProjectStructureElement libraryElement = (LibraryProjectStructureElement)selectedElement;
+ final LibraryEx oldLibrary = (LibraryEx)context.getLibrary(libraryElement.getLibrary().getName(), mySourceConfigurable.getLevel());
LOG.assertTrue(oldLibrary != null);
final Library newLibrary = doCopy(oldLibrary);
if (newLibrary == null) return;
final ModulesConfigurator configurator = context.getModulesConfigurator();
- final Collection<ProjectStructureElementUsage> usages = context.getDaemonAnalyzer().getUsages(selectedElement);
+ final Collection<ProjectStructureElementUsage> usages = context.getDaemonAnalyzer().getUsages(libraryElement);
for (ProjectStructureElementUsage usage : usages) {
if (usage instanceof UsageInModuleClasspath) {
final Module module = ((UsageInModuleClasspath)usage).getModule();
}
}
else if (usage instanceof UsageInArtifact) {
- final PackagingElement<?> libraryElement = PackagingElementFactory.getInstance().createLibraryFiles(newLibrary.getName(),
- newLibrary.getTable().getTableLevel(), null);
- ((UsageInArtifact)usage).replaceElement(libraryElement);
+ final PackagingElement<?> newLibraryElement = PackagingElementFactory.getInstance().createLibraryFiles(newLibrary.getName(),
+ newLibrary.getTable().getTableLevel(), null);
+ ((UsageInArtifact)usage).replaceElement(newLibraryElement);
}
}
if (!myCopy) {
- mySourceConfigurable.getModelProvider().getModifiableModel().removeLibrary(originalLibrary);
- context.getDaemonAnalyzer().removeElement(selectedElement);
- mySourceConfigurable.removeLibraryNode(originalLibrary);
+ mySourceConfigurable.removeLibrary(libraryElement);
}
ProjectStructureConfigurable.getInstance(myProject).selectProjectOrGlobalLibrary(newLibrary, true);
}
((DefaultTreeModel)myTree.getModel()).reload(parent);
}
myContext.getDaemonAnalyzer().removeElement(new LibraryProjectStructureElement(myContext, library));
- // TODO: myContext.invalidateModules(myContext.myLibraryDependencyCache.get(library.getName()));
}
}
}
modelProxy.addLibraryEntry(library);
myContext.getDaemonAnalyzer().queueUpdate(new ModuleProjectStructureElement(myContext, module));
- /* TODO
- Set<String> modules = myContext.myLibraryDependencyCache.get(library.getName());
- if (modules == null) {
- modules = new HashSet<String>();
- myContext.myLibraryDependencyCache.put(library.getName(), modules);
- }
- modules.add(module.getName());
- */
myTree.repaint();
}
selectNodeInTree(node);
final ProjectStructureDaemonAnalyzer daemonAnalyzer = myContext.getDaemonAnalyzer();
daemonAnalyzer.queueUpdate(new ModuleProjectStructureElement(myContext, module));
- daemonAnalyzer.clearAllProblems(); //missing modules added
+ daemonAnalyzer.queueUpdateForAllElementsWithErrors(); //missing modules added
}
@Nullable
return Collections.emptyList();
}
- @Override
- public boolean highlightIfUnused() {
- return false;
- }
-
@Override
public String getPresentableName() {
return "Facet '" + myFacet.getName() + "' in module '" + myFacet.getModule().getName() + "'";
package com.intellij.openapi.roots.ui.configuration.projectRoot.daemon;
+import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
+import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.roots.JavadocOrderRootType;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.roots.impl.libraries.LibraryEx;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar;
+import com.intellij.openapi.roots.ui.configuration.ChooseModulesDialog;
import com.intellij.openapi.roots.ui.configuration.ModuleEditor;
import com.intellij.openapi.roots.ui.configuration.ProjectStructureConfigurable;
+import com.intellij.openapi.roots.ui.configuration.libraries.LibraryEditingUtil;
import com.intellij.openapi.roots.ui.configuration.libraryEditor.ExistingLibraryEditor;
-import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesModifiableModel;
-import com.intellij.openapi.roots.ui.configuration.projectRoot.LibraryConfigurable;
-import com.intellij.openapi.roots.ui.configuration.projectRoot.StructureConfigurableContext;
+import com.intellij.openapi.roots.ui.configuration.projectRoot.*;
import com.intellij.openapi.ui.NamedConfigurable;
import com.intellij.openapi.vfs.VfsUtil;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
+import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
}
@Override
- public boolean highlightIfUnused() {
+ public boolean shouldShowWarningIfUnused() {
final LibraryTable libraryTable = myLibrary.getTable();
return libraryTable != null && LibraryTablesRegistrar.PROJECT_LEVEL.equals(libraryTable.getTableLevel());
}
+ @Override
+ public ProjectStructureProblemDescription createUnusedElementWarning() {
+ final List<ConfigurationErrorQuickFix> fixes = Arrays.asList(new AddLibraryToDependenciesFix(), new RemoveLibraryFix());
+ return new ProjectStructureProblemDescription(getPresentableName() + " is not used", null, createPlace(), fixes,
+ ProjectStructureProblemType.warning("unused-library"));
+ }
+
@Override
public String getPresentableName() {
return "Library '" + myLibrary.getName() + "'";
}
}
}
+
+ private class AddLibraryToDependenciesFix extends ConfigurationErrorQuickFix {
+ private AddLibraryToDependenciesFix() {
+ super("Add to Dependencies...");
+ }
+
+ @Override
+ public void performFix() {
+ final Project project = myContext.getProject();
+ final ModuleStructureConfigurable moduleStructureConfigurable = ModuleStructureConfigurable.getInstance(project);
+ final List<Module> modules = LibraryEditingUtil.getSuitableModules(moduleStructureConfigurable, ((LibraryEx)myLibrary).getType());
+ if (modules.isEmpty()) return;
+ final ChooseModulesDialog dlg = new ChooseModulesDialog(project, modules, ProjectBundle.message("choose.modules.dialog.title"),
+ ProjectBundle
+ .message("choose.modules.dialog.description", myLibrary.getName()));
+ dlg.show();
+ if (dlg.isOK()) {
+ final List<Module> chosenModules = dlg.getChosenElements();
+ for (Module module : chosenModules) {
+ moduleStructureConfigurable.addLibraryOrderEntry(module, myLibrary);
+ }
+ }
+ }
+ }
+
+ private class RemoveLibraryFix extends ConfigurationErrorQuickFix {
+ private RemoveLibraryFix() {
+ super("Remove Library");
+ }
+
+ @Override
+ public void performFix() {
+ BaseLibrariesConfigurable.getInstance(myContext.getProject(), myLibrary.getTable().getTableLevel()).removeLibrary(LibraryProjectStructureElement.this);
+ }
+ }
}
return myModule.hashCode();
}
- @Override
- public boolean highlightIfUnused() {
- return false;
- }
-
@Override
public String getPresentableName() {
return "Module '" + myModule.getName() + "'";
import com.intellij.openapi.ui.popup.PopupStep;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.ui.awt.RelativePoint;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
-import java.util.List;
/**
* @author nik
}
@Override
- public void fix(final JComponent contextComponent) {
- final List<ConfigurationErrorQuickFix> fixes = myDescription.getFixes();
- if (fixes.size() == 1) {
- fixes.get(0).performFix();
- }
- else {
- JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<ConfigurationErrorQuickFix>(null, fixes) {
- @NotNull
- @Override
- public String getTextFor(ConfigurationErrorQuickFix value) {
- return value.getActionName();
- }
+ public void fix(final JComponent contextComponent, RelativePoint relativePoint) {
+ JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<ConfigurationErrorQuickFix>(null, myDescription.getFixes()) {
+ @NotNull
+ @Override
+ public String getTextFor(ConfigurationErrorQuickFix value) {
+ return value.getActionName();
+ }
- @Override
- public PopupStep onChosen(ConfigurationErrorQuickFix selectedValue, boolean finalChoice) {
- selectedValue.performFix();
- return FINAL_CHOICE;
- }
- }).showUnderneathOf(contextComponent);
- }
+ @Override
+ public PopupStep onChosen(final ConfigurationErrorQuickFix selectedValue, boolean finalChoice) {
+ return doFinalStep(new Runnable() {
+ @Override
+ public void run() {
+ selectedValue.performFix();
+ }
+ });
+ }
+ }).show(relativePoint);
}
}
public void problemsChanged(@NotNull ProjectStructureElement element) {
updateErrors(element);
}
-
- @Override
- public void allProblemsChanged() {
- clearProblems();
- }
});
}
private final MultiValuesMap<ProjectStructureElement, ProjectStructureElementUsage> mySourceElement2Usages = new MultiValuesMap<ProjectStructureElement, ProjectStructureElementUsage>();
private final MultiValuesMap<ProjectStructureElement, ProjectStructureElementUsage> myContainingElement2Usages = new MultiValuesMap<ProjectStructureElement, ProjectStructureElementUsage>();
private final Set<ProjectStructureElement> myElementWithNotCalculatedUsages = new HashSet<ProjectStructureElement>();
+ private final Set<ProjectStructureElement> myElementsToShowWarningIfUnused = new HashSet<ProjectStructureElement>();
+ private final Map<ProjectStructureElement, ProjectStructureProblemDescription> myWarningsAboutUnused = new HashMap<ProjectStructureElement, ProjectStructureProblemDescription>();
private final MergingUpdateQueue myAnalyzerQueue;
private final EventDispatcher<ProjectStructureDaemonAnalyzerListener> myDispatcher = EventDispatcher.create(ProjectStructureDaemonAnalyzerListener.class);
private final AtomicBoolean myStopped = new AtomicBoolean(false);
if (LOG.isDebugEnabled()) {
LOG.debug("updating problems for " + element);
}
+ final ProjectStructureProblemDescription warning = myWarningsAboutUnused.get(element);
+ if (warning != null)
+ problemsHolder.registerProblem(warning);
myProblemHolders.put(element, problemsHolder);
myDispatcher.getMulticaster().problemsChanged(element);
}
addUsage(usage);
}
myElementWithNotCalculatedUsages.remove(element);
+ reportUnusedElements();
}
private static void invokeLater(Runnable runnable) {
if (collectUsages) {
myElementWithNotCalculatedUsages.add(element);
}
+ if (element.shouldShowWarningIfUnused()) {
+ myElementsToShowWarningIfUnused.add(element);
+ }
myAnalyzerQueue.queue(new AnalyzeElementUpdate(element, check, collectUsages));
}
public void removeElement(ProjectStructureElement element) {
myElementWithNotCalculatedUsages.remove(element);
+ myElementsToShowWarningIfUnused.remove(element);
+ myWarningsAboutUnused.remove(element);
myProblemHolders.remove(element);
final Collection<ProjectStructureElementUsage> usages = mySourceElement2Usages.removeAll(element);
if (usages != null) {
}
removeUsagesInElement(element);
myDispatcher.getMulticaster().problemsChanged(element);
+ reportUnusedElements();
+ }
+
+ private void reportUnusedElements() {
+ if (!myElementWithNotCalculatedUsages.isEmpty()) return;
+
+ for (ProjectStructureElement element : myElementsToShowWarningIfUnused) {
+ final ProjectStructureProblemDescription warning;
+ final Collection<ProjectStructureElementUsage> usages = mySourceElement2Usages.get(element);
+ if (usages == null || usages.isEmpty()) {
+ warning = element.createUnusedElementWarning();
+ }
+ else {
+ warning = null;
+ }
+
+ final ProjectStructureProblemDescription old = myWarningsAboutUnused.put(element, warning);
+ ProjectStructureProblemsHolderImpl holder = myProblemHolders.get(element);
+ if (holder == null) {
+ holder = new ProjectStructureProblemsHolderImpl();
+ myProblemHolders.put(element, holder);
+ }
+ if (old != null) {
+ holder.removeProblem(old);
+ }
+ if (warning != null) {
+ holder.registerProblem(warning);
+ }
+ if (old != null || warning != null) {
+ myDispatcher.getMulticaster().problemsChanged(element);
+ }
+ }
}
public boolean isUnused(ProjectStructureElement element) {
- if (!element.highlightIfUnused()) {
+ if (!element.shouldShowWarningIfUnused()) {
return false;
}
if (!myElementWithNotCalculatedUsages.isEmpty()) {
myProblemHolders.clear();
}
- public void clearAllProblems() {
+ public void queueUpdateForAllElementsWithErrors() {
+ List<ProjectStructureElement> toUpdate = new ArrayList<ProjectStructureElement>();
+ for (Map.Entry<ProjectStructureElement, ProjectStructureProblemsHolderImpl> entry : myProblemHolders.entrySet()) {
+ if (entry.getValue().containProblems()) {
+ toUpdate.add(entry.getKey());
+ }
+ }
myProblemHolders.clear();
- myDispatcher.getMulticaster().allProblemsChanged();
+ LOG.debug("Adding to queue updates for " + toUpdate.size() + " problematic elements");
+ for (ProjectStructureElement element : toUpdate) {
+ queueUpdate(element);
+ }
}
public void dispose() {
void usagesCollected(@NotNull ProjectStructureElement containingElement);
void problemsChanged(@NotNull ProjectStructureElement element);
-
- void allProblemsChanged();
}
import com.intellij.openapi.roots.ui.configuration.projectRoot.StructureConfigurableContext;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import java.util.List;
public abstract List<ProjectStructureElementUsage> getUsagesInElement();
- public abstract boolean highlightIfUnused();
+
+ public boolean shouldShowWarningIfUnused() {
+ return false;
+ }
+
+ @Nullable
+ public ProjectStructureProblemDescription createUnusedElementWarning() {
+ return null;
+ }
+
@Override
public abstract boolean equals(Object obj);
private final String myMessage;
private final String myDescription;
private final PlaceInProjectStructure myPlace;
- private final List<ConfigurationErrorQuickFix> myFixes;
+ private final List<? extends ConfigurationErrorQuickFix> myFixes;
private final ProjectStructureProblemType myProblemType;
public ProjectStructureProblemDescription(@NotNull String message,
@Nullable String description,
@NotNull PlaceInProjectStructure place,
- @NotNull List<ConfigurationErrorQuickFix> fixes,
+ @NotNull List<? extends ConfigurationErrorQuickFix> fixes,
@NotNull ProjectStructureProblemType problemType) {
myMessage = message;
myDescription = description;
return myDescription;
}
- public List<ConfigurationErrorQuickFix> getFixes() {
+ public List<? extends ConfigurationErrorQuickFix> getFixes() {
return myFixes;
}
}
}
+ public boolean containProblems() {
+ return myProblemDescriptions != null && !myProblemDescriptions.isEmpty();
+ }
+
+ public void removeProblem(@NotNull ProjectStructureProblemDescription description) {
+ if (myProblemDescriptions != null) {
+ myProblemDescriptions.remove(description);
+ }
+ }
+
@Nullable
public List<ProjectStructureProblemDescription> getProblemDescriptions() {
return myProblemDescriptions;
return mySdk.hashCode();
}
- @Override
- public boolean highlightIfUnused() {
- return false;
- }
-
@Override
public String getPresentableName() {
return "SDK '" + mySdk.getName() + "'";
}
final PsiMethod method = methods[0];
- final JavaMethodCallElement item = new JavaMethodCallElement(method);
- JavaCompletionUtil.qualify(item).setAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
+ final JavaMethodCallElement item = new JavaMethodCallElement(method, false, false);
+ item.setAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
item.setInferenceSubstitutor(SmartCompletionDecorator.calculateMethodReturnTypeSubstitutor(method, expectedType));
result.consume(item);
}
InsertHandlerState state = new InsertHandlerState(context.getSelectionEndOffset(), context.getSelectionEndOffset());
- if (CompletionUtil.isOverwrite(item, completionChar)) {
+ if (completionChar == Lookup.REPLACE_SELECT_CHAR) {
removeEndOfIdentifier(context);
}
else if(context.getOffsetMap().getOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET) != context.getSelectionEndOffset()) {
}
}
- private static void removeEndOfIdentifier(InsertionContext context){
+ public static void removeEndOfIdentifier(InsertionContext context){
final Document document = context.getEditor().getDocument();
JavaCompletionUtil.initOffsets(context.getFile(), context.getProject(), context.getOffsetMap());
document.deleteString(context.getSelectionEndOffset(), context.getOffsetMap().getOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET));
public class ImportStaticLookupActionProvider implements LookupActionProvider {
@Override
public void fillActions(final LookupElement element, Lookup lookup, Consumer<LookupElementAction> consumer) {
- if (!(element instanceof StaticallyImportable)) {
- return;
- }
-
- final StaticallyImportable item = (StaticallyImportable)element;
- if (!item.canBeImported()) {
+ final StaticallyImportable item = element.as(StaticallyImportable.CLASS_CONDITION_KEY);
+ if (item == null || !item.canBeImported()) {
return;
}
addLookupItem(set, tailType, element, file, variant);
}
}
- // TODO: KeywordChooser -> ContextGetter
- else if (comp instanceof KeywordChooser) {
- final String[] keywords = ((KeywordChooser)comp).getKeywords(context, position);
- for (String keyword : keywords) {
- addKeyword(factory, set, tailType, keyword, matcher, file, variant);
- }
- }
}
}
public static final PsiJavaElementPattern.Capture<PsiElement> INSIDE_PARAMETER_LIST =
PsiJavaPatterns.psiElement().withParent(
psiElement(PsiJavaCodeReferenceElement.class).insideStarting(
- psiElement().withParent(PsiParameterList.class)));
+ psiElement().withParent(psiElement(PsiParameterList.class).andNot(psiElement(PsiAnnotationParameterList.class)))));
private static final AndFilter START_OF_CODE_FRAGMENT = new AndFilter(
new ScopeFilter(new AndFilter(
new AfterElementFilter(new TextFilter("{")),
new ScopeFilter(new ClassFilter(JspClassLevelDeclarationStatement.class)));
public static final ElementPattern<PsiElement> START_FOR =
- psiElement().afterLeaf(psiElement().withText("(").afterLeaf("for")).withParents(PsiJavaCodeReferenceElement.class, PsiExpressionStatement.class, PsiForStatement.class);
+ psiElement().afterLeaf(psiElement().withText("(").afterLeaf("for")).withParents(PsiJavaCodeReferenceElement.class,
+ PsiExpressionStatement.class, PsiForStatement.class);
private static final PsiJavaElementPattern.Capture<PsiElement> CLASS_REFERENCE =
psiElement().withParent(psiReferenceExpression().referencing(psiClass()));
+ public static final ElementPattern<PsiElement> EXPR_KEYWORDS = and(
+ psiElement().withParent(psiElement(PsiReferenceExpression.class).withParent(
+ not(
+ or(psiElement(PsiTypeCastExpression.class),
+ psiElement(PsiSwitchLabelStatement.class),
+ psiElement(PsiExpressionStatement.class)
+ )
+ )
+ )),
+ not(psiElement().afterLeaf("."))
+ );
public JavaCompletionData(){
declareCompletionSpaces();
- final CompletionVariant variant = new CompletionVariant(PsiMethod.class,
- new PatternFilter(not(psiElement().afterLeaf("@", "."))));
- variant.includeScopeClass(PsiVariable.class);
- variant.includeScopeClass(PsiClass.class);
- variant.includeScopeClass(PsiFile.class);
- variant.includeScopeClass(PsiParameterList.class);
-
- variant.addCompletion(new ModifierChooser());
-
- registerVariant(variant);
-
initVariantsInFileScope();
initVariantsInClassScope();
initVariantsInMethodScope();
result.addElement(new OverrideableSpace(createKeyword(position, PsiKeyword.FINAL), TailType.SPACE));
}
}
-
+
if (isStatementPosition(position)) {
if (INSIDE_SWITCH.isAcceptable(position, position)) {
result.addElement(new OverrideableSpace(createKeyword(position, PsiKeyword.CASE), TailType.SPACE));
}
}
- final ElementPattern<PsiElement> exprKeywords = and(
- psiElement().withParent(psiElement(PsiReferenceExpression.class).withParent(
- not(
- or(psiElement(PsiTypeCastExpression.class),
- psiElement(PsiSwitchLabelStatement.class),
- psiElement(PsiExpressionStatement.class)
- )
- )
- )),
- not(psiElement().afterLeaf("."))
- );
- if (exprKeywords.accepts(position)) {
+ if (EXPR_KEYWORDS.accepts(position)) {
result.addElement(TailTypeDecorator.withTail(createKeyword(position, PsiKeyword.NEW), TailType.SPACE));
result.addElement(createKeyword(position, PsiKeyword.NULL));
result.addElement(createKeyword(position, PsiKeyword.TRUE));
result.addElement(createKeyword(position, PsiKeyword.FALSE));
}
+ if (INSIDE_PARAMETER_LIST.accepts(position) && !psiElement().afterLeaf(PsiKeyword.FINAL).accepts(position) && !AFTER_DOT.accepts(position)) {
+ result.addElement(TailTypeDecorator.withTail(createKeyword(position, PsiKeyword.FINAL), TailType.SPACE));
+ }
+
+ if (CLASS_START.isAcceptable(position, position) &&
+ PsiTreeUtil.getNonStrictParentOfType(position, PsiLiteralExpression.class, PsiComment.class) == null) {
+ for (String s : ModifierChooser.getKeywords(position)) {
+ result.addElement(new OverrideableSpace(createKeyword(position, s), TailType.SPACE));
+ }
+ }
+
addPrimitiveTypes(result, position);
if (isAfterTypeDot(position)) {
JavaMemberNameCompletionContributor.completeVariableNameForRefactoring(project, set, camelHumpMatcher, varType, varKind, true, false);
}
- public static String[] completeVariableNameForRefactoring(JavaCodeStyleManager codeStyleManager, final PsiType varType,
+ public static String[] completeVariableNameForRefactoring(JavaCodeStyleManager codeStyleManager, @Nullable final PsiType varType,
final VariableKind varKind,
SuggestedNameInfo suggestedNameInfo) {
return JavaMemberNameCompletionContributor
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.lookup.LookupElement;
-import com.intellij.codeInsight.lookup.LookupElementPresentation;
import com.intellij.codeInsight.lookup.VariableLookupItem;
import com.intellij.psi.*;
-import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
shouldImport |= originalPosition != null && PsiTreeUtil.isAncestor(containingClass, originalPosition, false);
if (member instanceof PsiMethod) {
- final JavaMethodCallElement element = new JavaMethodCallElement((PsiMethod)member, true, false);
- element.setShouldBeImported(shouldImport);
- return element;
+ return new JavaMethodCallElement((PsiMethod)member, shouldImport, false);
}
- return new StaticFieldLookupItem((PsiField)member, shouldImport, containingClass);
+ return new VariableLookupItem((PsiField)member, shouldImport);
}
@Override
boolean shouldImport) {
shouldImport |= originalPosition != null && PsiTreeUtil.isAncestor(containingClass, originalPosition, false);
- final JavaMethodCallElement element = new JavaMethodCallElement(overloads.get(0), true, true);
+ final JavaMethodCallElement element = new JavaMethodCallElement(overloads.get(0), shouldImport, true);
element.putUserData(JavaCompletionUtil.ALL_METHODS_ATTRIBUTE, overloads);
- element.setShouldBeImported(shouldImport);
return element;
}
};
return processor;
}
-
- private static class StaticFieldLookupItem extends VariableLookupItem implements StaticallyImportable {
- private final MemberLookupHelper myHelper;
- private final PsiClass myContainingClass;
-
- public StaticFieldLookupItem(PsiField field, boolean shouldImport, PsiClass containingClass) {
- super(field);
- myContainingClass = containingClass;
- myHelper = new MemberLookupHelper(field, containingClass, shouldImport, false);
- }
-
- @Override
- public void setShouldBeImported(boolean shouldImportStatic) {
- myHelper.setShouldBeImported(shouldImportStatic);
- }
-
- @Override
- public boolean canBeImported() {
- return true;
- }
-
- @Override
- public boolean willBeImported() {
- return myHelper.willBeImported();
- }
-
- @Override
- public void renderElement(LookupElementPresentation presentation) {
- super.renderElement(presentation);
- myHelper.renderElement(presentation, getAttribute(FORCE_QUALIFY) != null ? Boolean.TRUE : null, PsiSubstitutor.EMPTY);
- }
-
- @Override
- public void handleInsert(InsertionContext context) {
- if (willBeImported()) {
- context.commitDocument();
- final PsiReferenceExpression ref = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiReferenceExpression.class, false);
- if (ref != null) {
- ref.bindToElementViaStaticImport(myContainingClass);
- PostprocessReformattingAspect.getInstance(ref.getProject()).doPostponedFormatting();
- }
- }
- super.handleInsert(context);
- }
-
- @Override
- protected boolean shouldQualify(PsiField field, InsertionContext context) {
- return !willBeImported() || super.shouldQualify(field, context);
- }
- }
}
}
}
}
- final LookupItem item = PsiTypeLookupItem.createLookupItem(psiType, parameters.getPosition());
+ final PsiTypeLookupItem item = PsiTypeLookupItem.createLookupItem(psiType, parameters.getPosition());
JavaCompletionUtil.setShowFQN(item);
if (psiClass.isInterface() || psiClass.hasModifierProperty(PsiModifier.ABSTRACT)) {
item.setAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
- item.setAttribute(LookupItem.INDICATE_ANONYMOUS, "");
+ item.setIndicateAnonymous(true);
}
return LookupElementDecorator.withInsertHandler(item, myConstructorInsertHandler);
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.SuggestedNameInfo;
import com.intellij.psi.codeStyle.VariableKind;
-import com.intellij.psi.statistics.JavaStatisticsManager;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
+import com.intellij.refactoring.introduceField.InplaceIntroduceFieldPopup;
+import com.intellij.refactoring.introduceVariable.IntroduceVariableBase;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ProcessingContext;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.LinkedHashSet;
new CompletionProvider<CompletionParameters>() {
public void addCompletions(@NotNull final CompletionParameters parameters, final ProcessingContext matchingContext, @NotNull final CompletionResultSet result) {
final Set<LookupElement> lookupSet = new THashSet<LookupElement>();
- final PsiVariable variable = (PsiVariable)parameters.getPosition().getParent();
+ final PsiField variable = (PsiField)parameters.getPosition().getParent();
completeFieldName(lookupSet, variable, result.getPrefixMatcher(), parameters.getInvocationCount() >= 1);
completeMethodName(lookupSet, variable, result.getPrefixMatcher());
for (final LookupElement item : lookupSet) {
PsiElement parent = PsiTreeUtil.getParentOfType(var, PsiCodeBlock.class);
if(parent == null) parent = PsiTreeUtil.getParentOfType(var, PsiMethod.class);
tunePreferencePolicy(LookupItemUtil.addLookupItems(set, getUnresolvedReferences(parent, false), matcher), suggestedNameInfo);
- final String[] nameSuggestions =
- JavaStatisticsManager.getNameSuggestions(type, JavaStatisticsManager.getContext(var), matcher.getPrefix());
- tunePreferencePolicy(LookupItemUtil.addLookupItems(set, nameSuggestions, matcher), suggestedNameInfo);
+
+ PsiExpression initializer = var.getInitializer();
+ if (initializer != null) {
+ SuggestedNameInfo initializerSuggestions = IntroduceVariableBase.getSuggestedName(type, initializer);
+ tunePreferencePolicy(LookupItemUtil.addLookupItems(set, initializerSuggestions.names, matcher), initializerSuggestions);
+ }
}
private static void tunePreferencePolicy(final List<LookupElement> list, final SuggestedNameInfo suggestedNameInfo) {
return ArrayUtil.toStringArray(unresolvedRefs);
}
- private static void completeFieldName(Set<LookupElement> set, PsiVariable var, final PrefixMatcher matcher, boolean includeOverlapped) {
+ private static void completeFieldName(Set<LookupElement> set, PsiField var, final PrefixMatcher matcher, boolean includeOverlapped) {
FeatureUsageTracker.getInstance().triggerFeatureUsed("editing.completion.variable.name");
JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(var.getProject());
tunePreferencePolicy(LookupItemUtil.addLookupItems(set, suggestedNameInfo.names, matcher), suggestedNameInfo);
}
- tunePreferencePolicy(LookupItemUtil.addLookupItems(set, JavaStatisticsManager
- .getNameSuggestions(var.getType(), JavaStatisticsManager.getContext(var), matcher.getPrefix()), matcher), suggestedNameInfo);
tunePreferencePolicy(LookupItemUtil.addLookupItems(set, getUnresolvedReferences(var.getParent(), false), matcher), suggestedNameInfo);
+
+ PsiExpression initializer = var.getInitializer();
+ PsiClass containingClass = var.getContainingClass();
+ if (initializer != null && containingClass != null) {
+ SuggestedNameInfo initializerSuggestions = InplaceIntroduceFieldPopup.
+ suggestFieldName(var.getType(), null, initializer, var.hasModifierProperty(PsiModifier.STATIC), containingClass);
+ tunePreferencePolicy(LookupItemUtil.addLookupItems(set, initializerSuggestions.names, matcher), initializerSuggestions);
+ }
}
public static void completeVariableNameForRefactoring(Project project,
public static String[] completeVariableNameForRefactoring(JavaCodeStyleManager codeStyleManager,
final PrefixMatcher matcher,
- final PsiType varType,
+ @Nullable final PsiType varType,
final VariableKind varKind,
SuggestedNameInfo suggestedNameInfo,
final boolean includeOverlapped, final boolean methodPrefix) {
return ArrayUtil.toStringArray(result);
}
- private static boolean isMethodPrefix(String prefix) {
- return prefix.startsWith(JavaCompletionUtil.IS_PREFIX) || prefix.startsWith(JavaCompletionUtil.GET_PREFIX) || prefix.startsWith(
- JavaCompletionUtil.SET_PREFIX);
- }
-
private static void completeMethodName(Set<LookupElement> set, PsiElement element, final PrefixMatcher matcher){
if(element instanceof PsiMethod) {
final PsiMethod method = (PsiMethod)element;
private final MemberLookupHelper myHelper;
public JavaMethodCallElement(@NotNull PsiMethod method) {
- this(method, false, false);
+ super(method, method.getName());
+ myMethod = method;
+ myHelper = null;
+ myContainingClass = method.getContainingClass();
}
- public JavaMethodCallElement(PsiMethod method, boolean canImportStatic, boolean mergedOverloads) {
+ public JavaMethodCallElement(PsiMethod method, boolean shouldImportStatic, boolean mergedOverloads) {
super(method, method.getName());
myMethod = method;
myContainingClass = method.getContainingClass();
- myHelper = canImportStatic ? new MemberLookupHelper(method, myContainingClass, false, mergedOverloads) : null;
+ myHelper = new MemberLookupHelper(method, myContainingClass, shouldImportStatic, mergedOverloads);
+ if (!shouldImportStatic) {
+ forceQualify();
+ }
}
public PsiType getType() {
return !getInferenceSubstitutor().equals(PsiSubstitutor.EMPTY) && myMethod.getParameterList().getParametersCount() == 0;
}
- private boolean mayNeedTypeParameters(InsertionContext context) {
+ private static boolean mayNeedTypeParameters(InsertionContext context) {
final PsiElement leaf = context.getFile().findElementAt(context.getStartOffset());
if (PsiTreeUtil.getParentOfType(leaf, PsiExpressionList.class, true, PsiCodeBlock.class, PsiModifierListOwner.class) == null) {
if (PsiTreeUtil.getParentOfType(leaf, PsiConditionalExpression.class, true, PsiCodeBlock.class, PsiModifierListOwner.class) == null) {
import com.intellij.codeInsight.lookup.DefaultLookupItemRenderer;
import com.intellij.codeInsight.lookup.LookupElementPresentation;
import com.intellij.codeInsight.lookup.LookupItem;
+import com.intellij.codeInsight.lookup.PsiTypeLookupItem;
import com.intellij.codeInsight.lookup.impl.JavaElementLookupRenderer;
import com.intellij.openapi.util.ClassConditionKey;
import com.intellij.openapi.util.Comparing;
String tailText = StringUtil.notNullize((String) item.getAttribute(LookupItem.TAIL_TEXT_ATTR));
PsiSubstitutor substitutor = (PsiSubstitutor)item.getAttribute(LookupItem.SUBSTITUTOR);
- if (item.getAttribute(LookupItem.INDICATE_ANONYMOUS) != null &&
+ if (item instanceof PsiTypeLookupItem && ((PsiTypeLookupItem)item).isIndicateAnonymous() &&
(psiClass.isInterface() || psiClass.hasModifierProperty(PsiModifier.ABSTRACT))) {
tailText = "{...}" + tailText;
}
package com.intellij.codeInsight.completion;
import com.intellij.psi.*;
-import com.intellij.psi.filters.*;
-import com.intellij.psi.filters.classes.InterfaceFilter;
+import com.intellij.psi.filters.FilterPositionUtil;
import com.intellij.psi.impl.source.jsp.jspJava.JspClassLevelDeclarationStatement;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
-import com.intellij.util.containers.HashMap;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
-import java.util.Map;
/**
* Created by IntelliJ IDEA.
*/
@SuppressWarnings({"HardCodedStringLiteral"})
-public class ModifierChooser
- implements KeywordChooser{
- private static final Map<ElementFilter, String[][]> myMap = new HashMap<ElementFilter, String[][]>();
+public class ModifierChooser {
- static {
- myMap.put(new NotFilter(new InterfaceFilter()), new String[][]{
- new String[]{"public", "protected", "private"},
- new String[]{"static"},
- new String[]{"final", "abstract"},
- new String[]{"native"},
- new String[]{"synchronized"},
- new String[]{"strictfp"},
- new String[]{"volatile"},
- new String[]{"transient"}
- });
+ static String[] getKeywords(@NotNull PsiElement position) {
+ final PsiModifierList list = findModifierList(position);
+ if (list == null && !shouldSuggestModifiers(position)) {
+ return ArrayUtil.EMPTY_STRING_ARRAY;
+ }
- myMap.put(new InterfaceFilter(), new String[][]{
- new String[]{"public", "protected"},
- new String[]{"static"},
- new String[]{"final"}
- });
+ PsiElement scope = position.getParent();
+ while (scope != null) {
+ if (scope instanceof PsiJavaFile) {
+ return addClassModifiers(list);
+ }
+ if (scope instanceof PsiClass) {
+ return addMemberModifiers(list, ((PsiClass)scope).isInterface());
+ }
+ scope = scope.getParent();
+ if (scope instanceof PsiDirectory) break;
+ }
+ return ArrayUtil.EMPTY_STRING_ARRAY;
+ }
- myMap.put(new ClassFilter(PsiJavaFile.class), new String[][]{
+ public static String[] addClassModifiers(PsiModifierList list) {
+ return addKeywords(list, new String[][]{
new String[]{"public"},
new String[]{"final", "abstract"}
});
+ }
- myMap.put(new ClassFilter(PsiParameterList.class), new String[][]{
+ public static String[] addMemberModifiers(PsiModifierList list, final boolean inInterface) {
+ return addKeywords(list, inInterface ? new String[][]{
+ new String[]{"public", "protected"},
+ new String[]{"static"},
new String[]{"final"}
+ } : new String[][]{
+ new String[]{"public", "protected", "private"},
+ new String[]{"static"},
+ new String[]{"final", "abstract"},
+ new String[]{"native"},
+ new String[]{"synchronized"},
+ new String[]{"strictfp"},
+ new String[]{"volatile"},
+ new String[]{"transient"}
});
}
- public String[] getKeywords(CompletionContext context, PsiElement position) {
- if (JavaCompletionData.INSIDE_SWITCH.isAcceptable(position, position)) {
- return ArrayUtil.EMPTY_STRING_ARRAY;
- }
-
+ private static String[] addKeywords(PsiModifierList list, String[][] keywordSets) {
final List<String> ret = new ArrayList<String>();
- try {
- PsiElement scope;
-
- if (position == null) {
- scope = context.file;
- }
- else {
- scope = position.getParent();
- }
-
- final PsiModifierList list = getModifierList(position);
-
- scopes:
- while (scope != null) {
- for (final Object o : myMap.keySet()) {
- final ElementFilter filter = (ElementFilter)o;
- if (filter.isClassAcceptable(scope.getClass()) && filter.isAcceptable(scope, scope.getParent())) {
- final String[][] keywordSets = myMap.get(filter);
- for (int i = 0; i < keywordSets.length; i++) {
- final String[] keywords = keywordSets[keywordSets.length - i - 1];
- boolean containModifierFlag = false;
- if (list != null) {
- for (@Modifier String keyword : keywords) {
- if (list.hasExplicitModifier(keyword)) {
- containModifierFlag = true;
- break;
- }
- }
- }
- if (!containModifierFlag) {
- ContainerUtil.addAll(ret, keywords);
- }
- }
- break scopes;
+ for (int i = 0; i < keywordSets.length; i++) {
+ final String[] keywords = keywordSets[keywordSets.length - i - 1];
+ boolean containModifierFlag = false;
+ if (list != null) {
+ for (@Modifier String keyword : keywords) {
+ if (list.hasExplicitModifier(keyword)) {
+ containModifierFlag = true;
+ break;
}
}
- scope = scope.getParent();
- if (scope instanceof JspClassLevelDeclarationStatement) {
- scope = scope.getContext();
- }
- if (scope instanceof PsiDirectory) break;
}
- }
- catch (Exception e) {
+ if (!containModifierFlag) {
+ ContainerUtil.addAll(ret, keywords);
+ }
}
return ArrayUtil.toStringArray(ret);
}
- private static PsiModifierList getModifierList(PsiElement element)
- throws Exception{
- if(element == null){
- return null;
- }
- if(element.getParent() instanceof PsiModifierList)
+ @Nullable
+ public static PsiModifierList findModifierList(@NotNull PsiElement element) {
+ if(element.getParent() instanceof PsiModifierList) {
return (PsiModifierList)element.getParent();
-
- final PsiElement prev = FilterPositionUtil.searchNonSpaceNonCommentBack(element);
-
- if(prev != null) {
- final PsiModifierList modifierList = PsiTreeUtil.getParentOfType(prev, PsiModifierList.class);
- if(modifierList != null){
- return modifierList;
- }
}
+ return PsiTreeUtil.getParentOfType(FilterPositionUtil.searchNonSpaceNonCommentBack(element), PsiModifierList.class);
+ }
+
+ private static boolean shouldSuggestModifiers(PsiElement element) {
PsiElement parent = element.getParent();
while(parent != null && (parent instanceof PsiJavaCodeReferenceElement
- || parent instanceof PsiErrorElement || parent instanceof PsiTypeElement
- || parent instanceof PsiMethod || parent instanceof PsiVariable
- || parent instanceof PsiDeclarationStatement || parent instanceof PsiImportList
- || parent instanceof PsiDocComment
- || element.getText().equals(parent.getText()))){
+ || parent instanceof PsiErrorElement || parent instanceof PsiTypeElement
+ || parent instanceof PsiMethod || parent instanceof PsiVariable
+ || parent instanceof PsiDeclarationStatement || parent instanceof PsiImportList
+ || parent instanceof PsiDocComment
+ || element.getText().equals(parent.getText()))){
parent = parent.getParent();
if (parent instanceof JspClassLevelDeclarationStatement) {
parent = parent.getContext();
}
}
- if(parent == null) throw new Exception();
- for (final Object o : myMap.keySet()) {
- final ElementFilter filter = (ElementFilter)o;
- if (filter.isClassAcceptable(parent.getClass()) && filter.isAcceptable(parent, parent.getParent())) {
- if (parent instanceof PsiParameterList) {
- if (prev == null || Arrays.asList(new String[]{"(", ","}).contains(prev.getText())
- || Arrays.asList(new String[]{"(", ","}).contains(element.getText())) {
- return null;
- }
- }
- else if (prev == null || JavaCompletionData.END_OF_BLOCK.isAcceptable(element, prev.getParent())) {
- return null;
- }
+ if(parent == null) return false;
+
+ PsiElement prev = FilterPositionUtil.searchNonSpaceNonCommentBack(element);
+
+ if (parent instanceof PsiJavaFile || parent instanceof PsiClass) {
+ if (prev == null || JavaCompletionData.END_OF_BLOCK.isAcceptable(element, prev.getParent())) {
+ return true;
}
}
- throw new Exception("Can't find modifier list");
+ return false;
}
- public String toString(){
- return "modifier-chooser";
- }
}
package com.intellij.codeInsight.completion;
+import com.intellij.openapi.util.ClassConditionKey;
+
/**
* @author peter
*/
public interface StaticallyImportable {
+ ClassConditionKey<StaticallyImportable> CLASS_CONDITION_KEY = ClassConditionKey.create(StaticallyImportable.class);
+
void setShouldBeImported(boolean shouldImportStatic);
boolean canBeImported();
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.tree.IElementType;
+import com.intellij.psi.tree.TokenSet;
+import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
+import static com.intellij.openapi.util.text.StringUtil.unescapeStringCharacters;
+
public class StringLiteralCopyPasteProcessor implements CopyPastePreProcessor {
+
+ private static final TokenSet SYMBOL_LITERAL_TYPES = TokenSet.create(JavaTokenType.STRING_LITERAL, JavaTokenType.CHARACTER_LITERAL);
+
+ @SuppressWarnings("ForLoopThatDoesntUseLoopVariable")
+ @Override
public String preprocessOnCopy(final PsiFile file, final int[] startOffsets, final int[] endOffsets, final String text) {
- boolean isLiteral = true;
- for (int i = 0; i < startOffsets.length && isLiteral; i++) {
- if (findLiteralTokenType(file, startOffsets[i], endOffsets[i]) == null) {
- isLiteral = false;
+ // The main idea is to un-escape string/char literals content if necessary.
+ // Example:
+ // Suppose we have a following text at the editor: String s = "first <selection>line \n second</selection> line"
+ // When user copies the selection we want to transform text \n to the real line feed, i.e. clipboard should contains the following:
+ // line
+ // second
+ //
+ // However, we don't want to un-escape literal content if it's copied completely.
+ // Example:
+ // String s = <selection>"my string"</selection>;
+
+ StringBuilder buffer = new StringBuilder();
+ int givenTextOffset = 0;
+ boolean textWasChanged = false;
+ for (
+ int i = 0;
+ i < startOffsets.length && givenTextOffset < text.length();
+ i++, givenTextOffset++, buffer.append('\n')) // LF is added for block selection
+ {
+ // Calculate offsets offsets of the selection interval being processed now.
+ final int fileStartOffset = startOffsets[i];
+ final int fileEndOffset = endOffsets[i];
+ int givenTextStartOffset = Math.min(givenTextOffset, text.length());
+ final int givenTextEndOffset = Math.min(givenTextOffset + (fileEndOffset - fileStartOffset), text.length());
+ givenTextOffset = givenTextEndOffset;
+ for (
+ PsiElement element = file.findElementAt(fileStartOffset);
+ givenTextStartOffset < givenTextEndOffset;
+ element = PsiTreeUtil.nextLeaf(element))
+ {
+ if (element == null) {
+ buffer.append(text.substring(givenTextStartOffset, givenTextEndOffset));
+ break;
+ }
+ TextRange elementRange = element.getTextRange();
+ int escapedStartOffset;
+ int escapedEndOffset;
+ if (element instanceof PsiJavaToken && SYMBOL_LITERAL_TYPES.contains(((PsiJavaToken)element).getTokenType())
+ // We don't want to un-escape if complete literal is copied.
+ && (elementRange.getStartOffset() < fileStartOffset || elementRange.getEndOffset() > fileEndOffset))
+ {
+ escapedStartOffset = elementRange.getStartOffset() + 1 /* String/char literal quote */;
+ escapedEndOffset = elementRange.getEndOffset() - 1 /* String/char literal quote */;
+ }
+ else {
+ escapedStartOffset = escapedEndOffset = elementRange.getStartOffset();
+ }
+
+ // Process text to the left of the escaped fragment (if any).
+ int numberOfSymbolsToCopy = escapedStartOffset - Math.max(fileStartOffset, elementRange.getStartOffset());
+ if (numberOfSymbolsToCopy > 0) {
+ buffer.append(text.substring(givenTextStartOffset, givenTextStartOffset + numberOfSymbolsToCopy));
+ givenTextStartOffset += numberOfSymbolsToCopy;
+ }
+
+ // Process escaped text (un-escape it).
+ numberOfSymbolsToCopy = Math.min(escapedEndOffset, fileEndOffset) - Math.max(fileStartOffset, escapedStartOffset);
+ if (numberOfSymbolsToCopy > 0) {
+ textWasChanged = true;
+ buffer.append(unescapeStringCharacters(text.substring(givenTextStartOffset, givenTextStartOffset + numberOfSymbolsToCopy)));
+ givenTextStartOffset += numberOfSymbolsToCopy;
+ }
+
+ // Process text to the right of the escaped fragment (if any).
+ numberOfSymbolsToCopy = Math.min(fileEndOffset, elementRange.getEndOffset()) - Math.max(fileStartOffset, escapedEndOffset);
+ if (numberOfSymbolsToCopy > 0) {
+ buffer.append(text.substring(givenTextStartOffset, givenTextStartOffset + numberOfSymbolsToCopy));
+ givenTextStartOffset += numberOfSymbolsToCopy;
+ }
}
}
-
- return isLiteral ? StringUtil.unescapeStringCharacters(text) : null;
+ return textWasChanged ? buffer.toString() : null;
}
-
+
public String preprocessOnPaste(final Project project, final PsiFile file, final Editor editor, String text, final RawText rawText) {
final Document document = editor.getDocument();
PsiDocumentManager.getInstance(project).commitDocument(document);
if (rawText != null && rawText.rawText != null) return rawText.rawText; // Copied from the string literal. Copy as is.
return escapeCharCharacters(text);
}
- else {
- text = escapePastedLiteral(text);
- }
return text;
}
if (!(elementAtSelectionEnd instanceof PsiJavaToken)) {
return null;
}
- if (((PsiJavaToken)elementAtSelectionEnd).getTokenType() == tokenType) {
+ PsiJavaToken tokenAtSelectionEnd = (PsiJavaToken)elementAtSelectionEnd;
+ if (tokenAtSelectionEnd.getTokenType() == tokenType && tokenAtSelectionEnd.getTextRange().getStartOffset() < selectionEnd) {
return tokenType;
}
}
return tokenType;
}
- @Nullable
- private static PsiElement next(final @NotNull PsiElement element) {
- for (PsiElement anchor = element; anchor != null; anchor = anchor.getParent()) {
- final PsiElement result = element.getNextSibling();
- if (result != null) {
- return result;
- }
- }
- return null;
- }
-
@NotNull
public static String escapeCharCharacters(@NotNull String s) {
StringBuilder buffer = new StringBuilder();
StringUtil.escapeStringCharacters(s.length(), s, "\'", buffer);
return buffer.toString();
}
-
- /**
- * There is a possible case that pasted string contains string literal. We need to escape problem symbols within it then
- * (see IDEA-74544 for the problem example).
- *
- * @param s target string to paste
- * @return string that should be actually pasted
- */
- @SuppressWarnings("AssignmentToForLoopParameter")
- public static String escapePastedLiteral(@NotNull String s) {
- StringBuilder buffer = new StringBuilder();
- int literalStart = -1;
- int literalEnd = 0;
- for (int i = 0; i < s.length(); i++) {
- char c = s.charAt(i);
- switch (c) {
- case '\\': i++;break;
- case '"':
- if (literalStart < 0) {
- literalStart = i + 1;
- buffer.append(s, literalEnd, literalStart);
- }
- else {
- literalEnd = i;
- buffer.append(StringUtil.escapeStringCharacters(s.substring(literalStart, literalEnd)));
- literalStart = -1;
- }
- }
- }
- if (literalEnd < s.length()) {
- buffer.append(s.substring(Math.max(literalStart, literalEnd)));
- }
- return buffer.toString();
- }
}
public class PsiTypeLookupItem extends LookupItem {
public static final ClassConditionKey<PsiTypeLookupItem> CLASS_CONDITION_KEY = ClassConditionKey.create(PsiTypeLookupItem.class);
private final boolean myDiamond;
+ private boolean myIndicateAnonymous;
private PsiTypeLookupItem(Object o, @NotNull @NonNls String lookupString, boolean diamond) {
super(o, lookupString);
myDiamond = diamond;
}
+
+ public void setIndicateAnonymous(boolean indicateAnonymous) {
+ myIndicateAnonymous = indicateAnonymous;
+ }
+
+ public boolean isIndicateAnonymous() {
+ return myIndicateAnonymous;
+ }
+
@Override
public boolean equals(final Object o) {
return super.equals(o) && o instanceof PsiTypeLookupItem && getBracketsCount() == ((PsiTypeLookupItem) o).getBracketsCount();
import com.intellij.codeInsight.AutoPopupController;
import com.intellij.codeInsight.TailType;
-import com.intellij.codeInsight.completion.CodeCompletionFeatures;
-import com.intellij.codeInsight.completion.CompletionUtil;
-import com.intellij.codeInsight.completion.InsertionContext;
-import com.intellij.codeInsight.completion.JavaCompletionUtil;
+import com.intellij.codeInsight.completion.*;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
+import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
/**
* @author peter
*/
-public class VariableLookupItem extends LookupItem<PsiVariable> implements TypedLookupItem {
+public class VariableLookupItem extends LookupItem<PsiVariable> implements TypedLookupItem, StaticallyImportable {
+ @Nullable private final MemberLookupHelper myHelper;
+
public VariableLookupItem(PsiVariable object) {
super(object, object.getName());
+ myHelper = null;
+ }
+
+ public VariableLookupItem(PsiField field, boolean shouldImport) {
+ super(field, field.getName());
+ myHelper = new MemberLookupHelper(field, field.getContainingClass(), shouldImport, false);
+ if (!shouldImport) {
+ forceQualify();
+ }
}
public PsiType getType() {
public void setSubstitutor(@NotNull PsiSubstitutor substitutor) {
setAttribute(SUBSTITUTOR, substitutor);
}
+
+ @Override
+ public void setShouldBeImported(boolean shouldImportStatic) {
+ assert myHelper != null;
+ myHelper.setShouldBeImported(shouldImportStatic);
+ }
+
+ @Override
+ public boolean canBeImported() {
+ return myHelper != null;
+ }
+
+ @Override
+ public boolean willBeImported() {
+ return myHelper != null && myHelper.willBeImported();
+ }
+
+ @Override
+ public void renderElement(LookupElementPresentation presentation) {
+ super.renderElement(presentation);
+ if (myHelper != null) {
+ myHelper.renderElement(presentation, getAttribute(FORCE_QUALIFY) != null ? Boolean.TRUE : null, PsiSubstitutor.EMPTY);
+ }
+ }
@Override
public LookupItem<PsiVariable> forceQualify() {
@Override
public void handleInsert(InsertionContext context) {
- super.handleInsert(context);
-
PsiVariable variable = getObject();
+
context.getDocument().replaceString(context.getStartOffset(), context.getTailOffset(), variable.getName());
+ context.commitDocument();
+ if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
+ DefaultInsertHandler.removeEndOfIdentifier(context);
+ context.commitDocument();
+ }
- PsiDocumentManager.getInstance(context.getProject()).commitDocument(context.getDocument());
- if (variable instanceof PsiField && shouldQualify((PsiField)variable, context)) {
- qualifyFieldReference(context, (PsiField)variable);
+ if (variable instanceof PsiField) {
+ if (willBeImported()) {
+ final PsiReferenceExpression
+ ref = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiReferenceExpression.class, false);
+ if (ref != null) {
+ ref.bindToElementViaStaticImport(((PsiField)variable).getContainingClass());
+ PostprocessReformattingAspect.getInstance(ref.getProject()).doPostponedFormatting();
+ }
+ }
+ else if (shouldQualify((PsiField)variable, context)) {
+ qualifyFieldReference(context, (PsiField)variable);
+ }
}
PsiReferenceExpression ref = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getTailOffset() - 1, PsiReferenceExpression.class, false);
}
}
- protected boolean shouldQualify(PsiField field, InsertionContext context) {
+ private boolean shouldQualify(PsiField field, InsertionContext context) {
+ if (myHelper != null && !myHelper.willBeImported()) {
+ return true;
+ }
+
if (getAttribute(FORCE_QUALIFY) != null) {
return true;
}
PsiReference reference = context.getFile().findReferenceAt(context.getStartOffset());
- if (reference instanceof PsiReferenceExpression && !((PsiReferenceExpression) reference).isQualified()) {
- final PsiVariable target = JavaPsiFacade.getInstance(context.getProject()).getResolveHelper().resolveReferencedVariable(field.getName(), (PsiElement)reference);
+ if (reference instanceof PsiReferenceExpression && !((PsiReferenceExpression)reference).isQualified()) {
+ final PsiVariable target = JavaPsiFacade.getInstance(context.getProject()).getResolveHelper()
+ .resolveReferencedVariable(field.getName(), (PsiElement)reference);
return !field.getManager().areElementsEquivalent(target, CompletionUtil.getOriginalOrSelf(field));
}
return false;
import com.intellij.ide.highlighter.JavaFileHighlighter;
import com.intellij.lang.StdLanguages;
import com.intellij.openapi.editor.Document;
-import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
protected abstract boolean isInContext(@NotNull PsiElement element);
- @Override
- public boolean isInContext(@NotNull final FileType fileType) {
- return false;
- }
-
@NotNull
@Override
public SyntaxHighlighter createHighlighter() {
package com.intellij.codeInsight.template;
import com.intellij.lang.StdLanguages;
-import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
}
return false;
}
-
- @Override
- public boolean isInContext(@NotNull FileType fileType) {
- return false;
- }
-
}
package com.intellij.codeInsight.template;
import com.intellij.lang.StdLanguages;
-import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.JavaTokenType;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
}
return false;
}
-
- @Override
- public boolean isInContext(@NotNull FileType fileType) {
- return false;
- }
-
-
}
package com.intellij.codeInsight.template;
import com.intellij.codeInsight.CodeInsightBundle;
-import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
return false;
}
- @Override
- public boolean isInContext(@NotNull FileType fileType) {
- return false;
- }
-
@Override
public boolean isExpandableFromEditor() {
return false;
import com.intellij.openapi.roots.CompilerModuleExtension;
import com.intellij.openapi.roots.CompilerProjectExtension;
import com.intellij.openapi.roots.OrderRootType;
-import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.pointers.VirtualFilePointer;
-import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager;
import com.intellij.util.ArrayUtil;
import org.jdom.Element;
private VirtualFilePointer duplicatePointer(VirtualFilePointer pointer) {
if (pointer == null) return null;
- final VirtualFilePointerListener listener =
- ((ProjectRootManagerImpl)ProjectRootManager.getInstance(myModule.getProject())).getVirtualFilePointerListener();
final VirtualFilePointerManager filePointerManager = VirtualFilePointerManager.getInstance();
- return filePointerManager.duplicate(pointer, this, listener);
+ return filePointerManager.duplicate(pointer, this, null);
}
}
private VirtualFilePointer createPointer(final String url) {
- final VirtualFilePointerListener listener =
- ((ProjectRootManagerImpl)ProjectRootManager.getInstance(myModule.getProject())).getVirtualFilePointerListener();
- return VirtualFilePointerManager.getInstance().create(url, this, listener);
+ return VirtualFilePointerManager.getInstance().create(url, this, null);
}
public void setCompilerOutputPath(final String url) {
}
public void setCompilerOutputUrl(String compilerOutputUrl) {
- VirtualFilePointer pointer = VirtualFilePointerManager.getInstance()
- .create(compilerOutputUrl, myProject, ProjectRootManagerImpl.getInstanceImpl(myProject).getVirtualFilePointerListener());
+ VirtualFilePointer pointer = VirtualFilePointerManager.getInstance().create(compilerOutputUrl, myProject, null);
setCompilerOutputPointer(pointer);
final LocalFileSystem.WatchRequest watchRequest =
LocalFileSystem.getInstance().addRootToWatch(ProjectRootManagerImpl.extractLocalPath(compilerOutputUrl), true);
return null;
}
- return JavaCompletionUtil.qualify(new VariableLookupItem(field));
+ return new VariableLookupItem(field, false);
}
@Nullable
}
- JavaMethodCallElement item = new JavaMethodCallElement(method);
+ JavaMethodCallElement item = new JavaMethodCallElement(method, false, false);
item.setInferenceSubstitutor(substitutor);
- return JavaCompletionUtil.qualify(item);
+ return item;
}
}
String oldText = blockCandidate.getText();
// There is a possible case that target block to wrap ends with single-line comment. Example:
- // if (true) i = 1; // Cool assignement
+ // if (true) i = 1; // Cool assignment
// We can't just surround target block of code with curly braces because the closing one will be treated as comment as well.
// Hence, we perform a check if we have such situation at the moment and insert new line before the closing brace.
int lastLineFeedIndex = oldText.lastIndexOf("\n");
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
+import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
assert classes != null;
if (defaultTargetDirectory == null) {
defaultTargetDirectory = classes.keySet().iterator().next().getContainingDirectory();
+ } else {
+ Project project = defaultTargetDirectory.getProject();
+ VirtualFile sourceRootForFile = ProjectRootManager.getInstance(project).getFileIndex()
+ .getSourceRootForFile(defaultTargetDirectory.getVirtualFile());
+ if (sourceRootForFile == null) {
+ final PsiFile[] files = new PsiFile[elements.length];
+ for (int i = 0, elementsLength = elements.length; i < elementsLength; i++) {
+ files[i] = elements[i].getContainingFile();
+ }
+ CopyFilesOrDirectoriesHandler.copyAsFiles(files, defaultTargetDirectory, project);
+ return;
+ }
}
Project project = defaultTargetDirectory.getProject();
Object targetDirectory = null;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.*;
+import com.intellij.psi.codeStyle.SuggestedNameInfo;
import com.intellij.psi.util.PsiExpressionTrimRenderer;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.JavaRefactoringSettings;
@Override
protected String[] suggestNames(PsiType defaultType, String propName) {
- return IntroduceFieldDialog.createGenerator(myStatic, (PsiLocalVariable)getLocalVariable(), myExpr, getLocalVariable() != null, null, myParentClass)
- .getSuggestedNameInfo(defaultType).names;
+ return suggestFieldName(defaultType, (PsiLocalVariable)getLocalVariable(), myExpr, myStatic, myParentClass).names;
+ }
+
+ public static SuggestedNameInfo suggestFieldName(@Nullable PsiType defaultType,
+ @Nullable final PsiLocalVariable localVariable,
+ final PsiExpression initializer,
+ final boolean forStatic,
+ @NotNull final PsiClass parentClass) {
+ return IntroduceFieldDialog.
+ createGenerator(forStatic, localVariable, initializer, localVariable != null, null, parentClass).
+ getSuggestedNameInfo(defaultType);
}
public void setReplaceAllOccurrences(boolean replaceAllOccurrences) {
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.RefactoringMessageUtil;
import com.intellij.util.ArrayUtil;
+import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
static NameSuggestionsGenerator createGenerator(final boolean willBeDeclaredStatic,
final PsiLocalVariable localVariable,
final PsiExpression initializerExpression,
- final boolean isInvokedOnDeclaration, final String enteredName, final PsiClass parentClass) {
+ final boolean isInvokedOnDeclaration, @Nullable final String enteredName, final PsiClass parentClass) {
return new NameSuggestionsGenerator() {
private final JavaCodeStyleManager myCodeStyleManager = JavaCodeStyleManager.getInstance(localVariable != null ? localVariable.getProject()
: initializerExpression.getProject());
protected static final String REFACTORING_NAME = RefactoringBundle.message("introduce.variable.title");
public static final Key<Boolean> NEED_PARENTHESIS = Key.create("NEED_PARENTHESIS");
- public static SuggestedNameInfo getSuggestedName(PsiType type, final PsiExpression expression) {
+ public static SuggestedNameInfo getSuggestedName(@Nullable PsiType type, @NotNull final PsiExpression expression) {
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(expression.getProject());
final SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, expression, type);
final String[] strings = JavaCompletionUtil
Collections.sort(items, new Comparator<DirectoryChooser.ItemWrapper>() {
@Override
public int compare(DirectoryChooser.ItemWrapper o1, DirectoryChooser.ItemWrapper o2) {
+ if (o1 == null) return -1;
+ if (o2 == null) return 1;
return getPresentableText(o1, project).compareToIgnoreCase(getPresentableText(o2, project));
}
});
+++ /dev/null
-package com.intellij.codeInsight.editorActions;
-
-import org.jetbrains.annotations.NotNull;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
-
-/**
- * @author Denis Zhdanov
- * @since 10/4/11 1:28 PM
- */
-public class StringLiteralCopyPasteProcessorTest {
-
- @Test
- public void escapePastedStringLiteral() {
- doEscapePastedStringLiteralTest("identity", "identity");
- doEscapePastedStringLiteralTest("\"complete \n literal\"", "\"complete \\n literal\"");
- doEscapePastedStringLiteralTest("\"incomplete \n literal", "\"incomplete \n literal");
- doEscapePastedStringLiteralTest("partial \"string \n literal\"", "partial \"string \\n literal\"");
- }
-
- private static void doEscapePastedStringLiteralTest(@NotNull String initial, @NotNull String expected) {
- assertEquals(expected, StringLiteralCopyPasteProcessor.escapePastedLiteral(initial));
- }
-}
public Result<MostlySingularMultiMap<String, SymbolCollectingProcessor.ResultWithContext>> compute() {
SymbolCollectingProcessor p = new SymbolCollectingProcessor();
myFile.processDeclarationsNoGuess(p, ResolveState.initial(), myFile, myFile);
- return Result.create(p.getResults(), PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT);
+ MostlySingularMultiMap<String, SymbolCollectingProcessor.ResultWithContext> results = p.getResults();
+ return Result.create(results, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT);
}
}
import com.intellij.psi.impl.source.tree.SharedImplUtil;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.javadoc.PsiDocComment;
+import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.javadoc.PsiDocTagValue;
import com.intellij.psi.javadoc.PsiDocToken;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
/**
* @author mike
*/
@NotNull
public PsiElement[] getVariants() {
final PsiElement firstChild = getFirstChild();
+
+ Set<String> usedNames = new HashSet<String>();
+ for (PsiDocTag tag : comment.getTags()) {
+ if (tag.getName().equals("param")) {
+ PsiDocTagValue valueElement = tag.getValueElement();
+ if (valueElement != null) {
+ usedNames.add(valueElement.getText());
+ }
+ }
+ }
+
+ PsiNamedElement[] result = PsiNamedElement.EMPTY_ARRAY;
if (firstChild instanceof PsiDocToken && ((PsiDocToken)firstChild).getTokenType().equals(JavaDocTokenType.DOC_TAG_VALUE_LT)) {
- return ((PsiTypeParameterListOwner)owner).getTypeParameters();
+ result = ((PsiTypeParameterListOwner)owner).getTypeParameters();
} else if (owner instanceof PsiMethod) {
- return ((PsiMethod)owner).getParameterList().getParameters();
+ result = ((PsiMethod)owner).getParameterList().getParameters();
+ }
+ List<PsiElement> filtered = new ArrayList<PsiElement>();
+ for (PsiNamedElement namedElement : result) {
+ if (!usedNames.contains(namedElement.getName())) {
+ filtered.add(namedElement);
+ }
}
- return PsiElement.EMPTY_ARRAY;
+ return filtered.toArray(new PsiElement[filtered.size()]);
}
public boolean isSoft(){
import com.intellij.psi.scope.JavaScopeProcessorEvent;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.util.containers.MostlySingularMultiMap;
+import org.jetbrains.annotations.NotNull;
/**
* @author max
private final PsiNamedElement myElement;
private final PsiElement myFileContext;
- public ResultWithContext(PsiNamedElement element, PsiElement fileContext) {
+ public ResultWithContext(@NotNull PsiNamedElement element, PsiElement fileContext) {
myElement = element;
myFileContext = fileContext;
}
+ @NotNull
public PsiNamedElement getElement() {
return myElement;
}
public PsiElement getFileContext() {
return myFileContext;
}
+
+ @Override
+ public String toString() {
+ return myElement.toString();
+ }
}
}
--- /dev/null
+/**
+ * @<caret>
+ */
+
+class C{}
\ No newline at end of file
--- /dev/null
+class Test {
+ /**
+ * @<caret>
+ */
+ public void foo() throws Exception {}
+}
\ No newline at end of file
--- /dev/null
+class Test {
+ /**
+ * @exception <caret>
+ */
+ public void foo() throws Exception {}
+}
\ No newline at end of file
--- /dev/null
+class Test {
+ /**
+ * @exception <caret>
+ */
+ public void foo() throws java.io.IOException, IllegalStateException {}
+}
\ No newline at end of file
--- /dev/null
+class C{
+
+ /**
+ * @<caret>
+ */
+ private int myField;
+}
\ No newline at end of file
--- /dev/null
+/**
+ * Some text {@link Fub<caret>
+ */
+
+class C{}
+
+
+class Fubar {
+ void foo();
+ void bar();
+}
+
+class Fubar2 {}
\ No newline at end of file
--- /dev/null
+/**
+ * Some text {@link Fubar#<caret>
+ */
+
+class C{}
+
+
+class Fubar {
+ void foo();
+ void bar();
+}
+
+class Fubar2 {}
\ No newline at end of file
--- /dev/null
+/**
+ * @see #foo(Object) <caret>
+ */
+class Test1<T> {
+ public void foo(T bar) {
+ }
+}
\ No newline at end of file
--- /dev/null
+/**
+ * @see #fo<caret>
+ */
+class Test1<T> {
+ public void foo(T bar) {
+ }
+}
\ No newline at end of file
--- /dev/null
+/**
+ * {@link java.<caret>}
+ */
+class A{}
--- /dev/null
+/**
+ * Some text {@<caret>
+ */
+
+class C{}
\ No newline at end of file
--- /dev/null
+/**
+ * Some text {@link Fubar#fo<caret>#
+ */
+
+class Fubar {
+ void foo();
+}
\ No newline at end of file
--- /dev/null
+/**
+ * Some text {@link Fubar#foo()} <caret>#
+ */
+
+class Fubar {
+ void foo();
+}
\ No newline at end of file
--- /dev/null
+class C{
+
+ /**
+ * @<caret>
+ */
+ private int foo() {}
+}
\ No newline at end of file
--- /dev/null
+class C{
+
+ /**
+ * @s<caret>
+ */
+ private int foo() {}
+}
\ No newline at end of file
--- /dev/null
+class C{
+
+ /**
+ * @param <caret>
+ */
+ private int foo(int a, char b, String c) {}
+}
\ No newline at end of file
--- /dev/null
+class C{
+
+ /**
+ * @param a<caret>
+ */
+ private int foo(int a1, char a2, String a3) {}
+}
\ No newline at end of file
--- /dev/null
+class C{
+
+ /**
+ * @param a1
+ * @param a<caret>
+ * @param a4
+ */
+ private int foo(int a1, char a2, String a3, boolean a4) {}
+}
\ No newline at end of file