Merge branch 'master' of git@git.labs.intellij.net:idea/community

This commit is contained in:
Kirill Kalishev
2010-03-16 13:22:45 +03:00
236 changed files with 5061 additions and 5811 deletions
@@ -1703,6 +1703,9 @@ public class CompileDriver {
if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) {
return false;
}
if (LOG.isDebugEnabled() && items.length > 0) {
LOG.debug("Start processing files by " + adapter.getCompiler().getDescription());
}
final CompileScope scope = context.getCompileScope();
final List<FileProcessingCompiler.ProcessingItem> toProcess = new ArrayList<FileProcessingCompiler.ProcessingItem>();
final Set<String> allUrls = new HashSet<String>();
@@ -1806,7 +1809,6 @@ public class CompileDriver {
final VirtualFile file = aProcessed.getFile();
vFiles.add(file);
if (LOG.isDebugEnabled()) {
LOG.debug("File processed by " + adapter.getCompiler().getDescription());
LOG.debug("\tFile processed " + file.getPresentableUrl() + "; ts=" + file.getTimeStamp());
}
@@ -110,7 +110,7 @@ public class RmicCompiler implements ClassPostProcessingCompiler{
}
if (!VfsUtil.isAncestor(outputDir, outputClassFile, true)) {
LOG.assertTrue(false, outputClassFile.getPath() + " should be located under the output root " + outputDir.getPath());
LOG.error(outputClassFile.getPath() + " should be located under the output root " + outputDir.getPath());
}
final ProcessingItem item = createProcessingItem(module, outputClassFile, outputDir,
@@ -31,10 +31,7 @@ import com.intellij.util.Processor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.*;
/**
* @author nik
@@ -87,9 +84,10 @@ public class ArtifactCompileScope {
Set<Artifact> artifacts = new HashSet<Artifact>();
final ArtifactManager artifactManager = ArtifactManager.getInstance(project);
final Set<Module> modules = new HashSet<Module>(Arrays.asList(compileScope.getAffectedModules()));
final List<Module> allModules = Arrays.asList(ModuleManager.getInstance(project).getModules());
for (Artifact artifact : artifactManager.getArtifacts()) {
if (artifact.isBuildOnMake()) {
if (modules.containsAll(Arrays.asList(ModuleManager.getInstance(project).getModules()))
if (modules.containsAll(allModules)
|| containsModuleOutput(artifact, modules, artifactManager)) {
artifacts.add(artifact);
}
@@ -84,6 +84,9 @@ public class IncrementalArtifactsCompiler implements PackagingCompiler {
final CompileContext context = builderContext.getCompileContext();
final Set<Artifact> artifactsToBuild = ArtifactCompileScope.getArtifactsToBuild(project, context.getCompileScope());
if (LOG.isDebugEnabled()) {
LOG.debug("artifacts to build: " + artifactsToBuild);
}
List<Artifact> additionalArtifacts = new ArrayList<Artifact>();
for (BuildParticipantProvider provider : BuildParticipantProvider.EXTENSION_POINT_NAME.getExtensions()) {
for (Module module : ModuleManager.getInstance(project).getModules()) {
@@ -93,6 +96,9 @@ public class IncrementalArtifactsCompiler implements PackagingCompiler {
}
}
}
if (LOG.isDebugEnabled() && !additionalArtifacts.isEmpty()) {
LOG.debug("additional artifacts to build: " + additionalArtifacts);
}
artifactsToBuild.addAll(additionalArtifacts);
final List<Artifact> allArtifacts = new ArrayList<Artifact>(Arrays.asList(ArtifactManager.getInstance(project).getArtifacts()));
@@ -120,7 +126,7 @@ public class IncrementalArtifactsCompiler implements PackagingCompiler {
ArtifactPackagingProcessingItem[] allProcessingItems = collectItems(builderContext, context.getProject());
if (LOG.isDebugEnabled()) {
int num = Math.min(100, allProcessingItems.length);
int num = Math.min(5000, allProcessingItems.length);
LOG.debug("All files (" + num + " of " + allProcessingItems.length + "):");
for (int i = 0; i < num; i++) {
LOG.debug(allProcessingItems[i].getFile().getPath());
@@ -203,7 +209,7 @@ public class IncrementalArtifactsCompiler implements PackagingCompiler {
final boolean testMode = ApplicationManager.getApplication().isUnitTestMode();
if (LOG.isDebugEnabled()) {
int num = Math.min(100, items.length);
int num = Math.min(200, items.length);
LOG.debug("Files to process (" + num + " of " + items.length + "):");
for (int i = 0; i < num; i++) {
LOG.debug(items[i].getFile().getPath());
@@ -80,9 +80,12 @@ public class ModuleOutputPackagingElement extends PackagingElement<ModuleOutputP
@NotNull ArtifactIncrementalCompilerContext compilerContext, @NotNull ArtifactType artifactType) {
final Module module = findModule(resolvingContext);
if (module != null) {
final VirtualFile output = CompilerModuleExtension.getInstance(module).getCompilerOutputPath();
if (output != null) {
creator.addDirectoryCopyInstructions(output, null);
final CompilerModuleExtension extension = CompilerModuleExtension.getInstance(module);
if (extension != null) {
final VirtualFile output = extension.getCompilerOutputPath();
if (output != null) {
creator.addDirectoryCopyInstructions(output, null);
}
}
}
}
@@ -50,6 +50,7 @@ import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.SpeedSearchBase;
import com.intellij.ui.TreeSpeedSearch;
import com.sun.jdi.*;
@@ -500,6 +501,20 @@ public abstract class DebuggerTree extends DebuggerTreeBase implements DataProvi
descriptor = myNodeManager.getStaticDescriptor(stackDescriptor, type);
}
myChildren.add(myNodeManager.createNode(descriptor, evaluationContext));
if (thisObjectReference != null && evaluationContext.getDebugProcess().getVirtualMachineProxy().canGetSyntheticAttribute()) {
final ReferenceType thisRefType = thisObjectReference.referenceType();
if (thisRefType instanceof ClassType && thisRefType.name().contains("$")) { // makes sense for nested classes only
final ClassType clsType = (ClassType)thisRefType;
for (Field field : clsType.fields()) {
if (field.isSynthetic() && StringUtil.startsWith(field.name(), FieldDescriptorImpl.OUTER_LOCAL_VAR_FIELD_PREFIX)) {
final FieldDescriptorImpl fieldDescriptor = myNodeManager.getFieldDescriptor(stackDescriptor, thisObjectReference, field);
myChildren.add(myNodeManager.createNode(fieldDescriptor, evaluationContext));
}
}
}
}
try {
buildVariables(stackDescriptor, evaluationContext);
if (NodeRendererSettings.getInstance().getClassRenderer().SORT_ASCENDING) {
@@ -39,6 +39,7 @@ import com.sun.jdi.*;
import org.jetbrains.annotations.NotNull;
public class FieldDescriptorImpl extends ValueDescriptorImpl implements FieldDescriptor{
public static final String OUTER_LOCAL_VAR_FIELD_PREFIX = "val$";
private final Field myField;
private final ObjectReference myObject;
private Boolean myIsPrimitive = null;
@@ -66,7 +67,7 @@ public class FieldDescriptorImpl extends ValueDescriptorImpl implements FieldDes
final ReferenceType type = myField.declaringType();
final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
final String fieldName = myField.name();
if (fieldName.startsWith("val$")) {
if (fieldName.startsWith(OUTER_LOCAL_VAR_FIELD_PREFIX)) {
// this field actually mirrors a local variable in the outer class
String varName = fieldName.substring(fieldName.lastIndexOf('$') + 1);
PsiElement element = PositionUtil.getContextElement(context);
@@ -137,7 +138,17 @@ public class FieldDescriptorImpl extends ValueDescriptorImpl implements FieldDes
}
public String getName() {
return myField.name();
final String fieldName = myField.name();
return isOuterLocalVariableValue()? fieldName.substring(OUTER_LOCAL_VAR_FIELD_PREFIX.length()) : fieldName;
}
public boolean isOuterLocalVariableValue() {
try {
return DebuggerUtils.isSynthetic(myField) && myField.name().startsWith(OUTER_LOCAL_VAR_FIELD_PREFIX);
}
catch (UnsupportedOperationException e) {
return false;
}
}
public String calcValueName() {
@@ -166,10 +177,10 @@ public class FieldDescriptorImpl extends ValueDescriptorImpl implements FieldDes
}
else {
//noinspection HardCodedStringLiteral
fieldName = "this." + getName();
fieldName = isOuterLocalVariableValue()? getName() : "this." + getName();
}
try {
return (PsiReferenceExpression)elementFactory.createExpressionFromText(fieldName, null);
return elementFactory.createExpressionFromText(fieldName, null);
}
catch (IncorrectOperationException e) {
throw new EvaluateException(DebuggerBundle.message("error.invalid.field.name", getName()), e);
@@ -110,8 +110,12 @@ public abstract class ValueDescriptorImpl extends NodeDescriptorImpl implements
myStoredEvaluationContext.getDebugProcess().getManagerThread().invoke(new SuspendContextCommandImpl(myStoredEvaluationContext.getSuspendContext()) {
public void contextAction() throws Exception {
// re-setting the context will cause value recalculation
setContext(myStoredEvaluationContext);
semaphore.up();
try {
setContext(myStoredEvaluationContext);
}
finally {
semaphore.up();
}
}
});
semaphore.waitFor();
@@ -21,6 +21,7 @@ import com.intellij.debugger.engine.DebuggerManagerThreadImpl;
import com.intellij.debugger.engine.DebuggerUtils;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluationContext;
import com.intellij.debugger.ui.impl.watch.FieldDescriptorImpl;
import com.intellij.debugger.ui.impl.watch.MessageDescriptor;
import com.intellij.debugger.ui.impl.watch.NodeManagerImpl;
import com.intellij.debugger.ui.impl.watch.ValueDescriptorImpl;
@@ -29,6 +30,7 @@ import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.DefaultJDOMExternalizer;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiElementFactory;
import com.intellij.psi.PsiExpression;
@@ -162,15 +164,14 @@ public class ClassRenderer extends NodeRendererImpl{
builder.setChildren(children);
}
private boolean shouldDisplay(TypeComponent component) {
if (!SHOW_SYNTHETICS && DebuggerUtils.isSynthetic(component)) {
private boolean shouldDisplay(Field field) {
final boolean isSynthetic = DebuggerUtils.isSynthetic(field);
if (!SHOW_SYNTHETICS && isSynthetic) {
return false;
}
if (!(component instanceof Field)) {
return true;
if (isSynthetic && StringUtil.startsWith(field.name(), FieldDescriptorImpl.OUTER_LOCAL_VAR_FIELD_PREFIX)) {
return false;
}
final Field field = (Field)component;
if(!SHOW_STATIC && field.isStatic()) {
return false;
}
@@ -383,7 +383,7 @@ public class ProjectStructureConfigurable extends BaseConfigurable implements Se
public ActionCallback select(@NotNull LibraryOrderEntry libraryOrderEntry, final boolean requestFocus) {
final Library lib = libraryOrderEntry.getLibrary();
if (lib != null && lib.getTable() == null) {
if (lib == null || lib.getTable() == null) {
Place place = new Place().putPath(CATEGORY, myModulesConfig);
place.putPath(BaseStructureConfigurable.TREE_OBJECT, libraryOrderEntry.getOwnerModule());
return navigateTo(place, requestFocus);
@@ -274,21 +274,21 @@ public abstract class BaseLibrariesConfigurable extends BaseStructureConfigurabl
for (VirtualFile file : files) {
if (mySaveAsCb.isSelected() && myPathTf.getText().trim().length() > 0) {
final File copy = new File(new File(myPathTf.getText()), file.getName());
if (copy.mkdirs()) {
try {
final File fromFile = VfsUtil.virtualToIoFile(file);
if (fromFile.isFile()) {
FileUtil.copy(fromFile, copy);
} else {
FileUtil.copyDir(fromFile, copy);
}
model.addRoot(LocalFileSystem.getInstance().refreshAndFindFileByIoFile(copy), type);
if (!copy.getParentFile().exists() && !copy.getParentFile().mkdirs()) continue;
try {
final File fromFile = VfsUtil.virtualToIoFile(file);
if (fromFile.isFile()) {
FileUtil.copy(fromFile, copy);
} else {
FileUtil.copyDir(fromFile, copy);
}
catch (IOException e1) {
//skip
}
continue;
model.addRoot(LocalFileSystem.getInstance().refreshAndFindFileByIoFile(copy), type);
}
catch (IOException e1) {
LOG.error(e1);
}
continue;
}
model.addRoot(file, type);
@@ -46,8 +46,14 @@ public class ProjectStructureProblemsHolderImpl implements ProjectStructureProbl
try {
buf.append("<html><body>");
if (myProblemDescriptions != null) {
int problems = 0;
for (ProjectStructureProblemDescription problemDescription : myProblemDescriptions) {
buf.append(problemDescription.getMessage()).append("<br>");
problems++;
if (problems >= 10 && myProblemDescriptions.size() > 12) {
buf.append(myProblemDescriptions.size() - problems).append(" more problems...<br>");
break;
}
}
}
buf.append("</body></html>");
@@ -55,11 +55,11 @@ import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.impl.PsiClassImplUtil;
import com.intellij.psi.impl.search.PsiSearchHelperImpl;
import com.intellij.psi.impl.source.jsp.jspJava.JspxImportStatement;
import com.intellij.psi.jsp.JspFile;
import com.intellij.psi.jsp.JspSpiUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiSearchHelper;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.searches.MethodReferencesSearch;
import com.intellij.psi.search.searches.OverridingMethodsSearch;
@@ -525,12 +525,12 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
// some classes may have references from within XML outside dependent modules, e.g. our actions
if (member instanceof PsiClass) scope = scope.uniteWith(GlobalSearchScope.projectScope(myProject));
PsiSearchHelperImpl.Result cheapEnough = ((PsiSearchHelperImpl)myFile.getManager().getSearchHelper()).isItCheapEnoughToSearch(myFile, name, scope);
if (cheapEnough == PsiSearchHelperImpl.Result.TOO_MANY_OCCURRENCES) return false;
PsiSearchHelper.SearchCostResult cheapEnough = myFile.getManager().getSearchHelper().isCheapEnoughToSearch(name, scope, myFile);
if (cheapEnough == PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES) return false;
//search usages if it cheap
//if count is 0 there is no usages since we've called myRefCountHolder.isReferenced() before
if (cheapEnough == PsiSearchHelperImpl.Result.ZERO_OCCURRENCES && !canbeReferencedViaWeirdNames(member)) return true;
if (cheapEnough == PsiSearchHelper.SearchCostResult.ZERO_OCCURRENCES && !canbeReferencedViaWeirdNames(member)) return true;
Query<PsiReference> query = member instanceof PsiMethod
? MethodReferencesSearch.search((PsiMethod)member, scope, true)
@@ -32,11 +32,13 @@ import com.intellij.codeInsight.intention.QuickFixFactory;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.util.*;
import com.intellij.xml.util.XmlStringUtil;
import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -558,7 +560,7 @@ public class HighlightMethodUtil {
return createMismatchedArgumentsHtmlTooltip(list, parameters, methodName, substitutor, aClass);
}
private static String createMismatchedArgumentsHtmlTooltip(PsiExpressionList list,
private static String createShortMismatchedArgumentsHtmlTooltip(PsiExpressionList list,
PsiParameter[] parameters,
String methodName,
PsiSubstitutor substitutor,
@@ -572,11 +574,86 @@ public class HighlightMethodUtil {
Integer.valueOf(cols - parameters.length + 1), parensizedName,
HighlightUtil.formatClass(aClass, false),
createMismatchedArgsHtmlTooltipParamsRow(parameters, substitutor, expressions),
createMismatchedArgsHtmlTooltipExpressionsRow(expressions, parameters, substitutor, cols)
createMismatchedArgsHtmlTooltipArgumentsRow(expressions, parameters, substitutor, cols)
);
}
private static String createMismatchedArgsHtmlTooltipExpressionsRow(final PsiExpression[] expressions, final PsiParameter[] parameters,
private static String esctrim(@NotNull String s) {
return StringUtil.first(XmlStringUtil.escapeString(s), 40, true);
}
private static String createMismatchedArgumentsHtmlTooltip(PsiExpressionList list,
PsiParameter[] parameters,
String methodName,
PsiSubstitutor substitutor,
PsiClass aClass) {
if (Math.max(parameters.length, list.getExpressions().length) <= 2) {
return createShortMismatchedArgumentsHtmlTooltip(list, parameters, methodName, substitutor, aClass);
}
else {
return createLongMismatchedArgumentsHtmlTooltip(list, parameters, methodName, substitutor, aClass);
}
}
private static String createLongMismatchedArgumentsHtmlTooltip(PsiExpressionList list,
PsiParameter[] parameters,
String methodName,
PsiSubstitutor substitutor,
PsiClass aClass) {
PsiExpression[] expressions = list.getExpressions();
@NonNls @Language("HTML")
String s = "<html><body><table border=0>" +
" <caption align=top><nobr><b>" + methodName + "() </b> in <b>" + HighlightUtil.formatClass(aClass, false) +"</b> cannot be applied to:</nobr></caption>"+
" <tr><th colspan=2 align=left>Expected<br>Parameters:</th><th align=left>Actual<br>Arguments:</th></tr>"
+" <tr><td colspan=3><hr></td></tr>"
;
for (int i = 0; i < Math.max(parameters.length,expressions.length); i++) {
PsiParameter parameter = i < parameters.length ? parameters[i] : null;
PsiExpression expression = i < expressions.length ? expressions[i] : null;
@NonNls String mismatchColor = showShortType(i, parameters, expressions, substitutor) ? null : "red";
s += "<tr>";
s += "<td><b><nobr>";
if (parameter != null) {
s += esctrim(parameter.getName()) +":";
}
s += "</nobr></b></td>";
s += "<td><b><nobr>";
if (parameter != null) {
PsiType type = substitutor.substitute(parameter.getType());
s += "<font " + (mismatchColor == null ? "" : "color=" + mismatchColor) + ">" +
esctrim(showShortType(i, parameters, expressions, substitutor)
? type.getPresentableText()
: HighlightUtil.formatType(type))
+ "</font>"
;
}
s += "</nobr></b></td>";
s += "<td><b><nobr>";
if (expression != null) {
PsiType type = expression.getType();
s += "<font " + (mismatchColor == null ? "" : "color=" + mismatchColor) + ">" +
esctrim(expression.getText()) + "&nbsp;&nbsp;"+
(mismatchColor == null || type == null || type == PsiType.NULL ? "" : "("+esctrim(HighlightUtil.formatType(type))+")")
+ "</font>"
;
}
s += "</nobr></b></td>";
s += "</tr>";
}
s+= " </table></body></html>";
return s;
}
private static String createMismatchedArgsHtmlTooltipArgumentsRow(final PsiExpression[] expressions, final PsiParameter[] parameters,
final PsiSubstitutor substitutor, final int cols) {
@NonNls String ms = "";
for (int i = 0; i < expressions.length; i++) {
@@ -80,7 +80,7 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
}
}
};
@SuppressWarnings({"UnusedDeclaration"}) //in plugin.xml
public HighlightVisitorImpl(Project project) {
this(JavaPsiFacade.getInstance(project).getResolveHelper());
@@ -111,10 +111,18 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
element.accept(this);
if (myRefCountHolder != null) {
registerReferencesFromInjectedFragments(element);
instantiateInjections(element);
}
}
private void instantiateInjections(final PsiElement element) {
InjectedLanguageUtil.enumerate(element, myFile, new PsiLanguageInjectionHost.InjectedPsiVisitor() {
public void visit(@NotNull final PsiFile injectedPsi, @NotNull final List<PsiLanguageInjectionHost.Shred> places) {
// no op
}
}, false);
}
private void registerReferencesFromInjectedFragments(final PsiElement element) {
InjectedLanguageUtil.enumerate(element, myFile, new PsiLanguageInjectionHost.InjectedPsiVisitor() {
public void visit(@NotNull final PsiFile injectedPsi, @NotNull final List<PsiLanguageInjectionHost.Shred> places) {
@@ -280,6 +288,7 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
@Override public void visitComment(PsiComment comment) {
super.visitComment(comment);
if (!myHolder.hasErrorResults()) myHolder.add(HighlightUtil.checkUnclosedComment(comment));
if (!myHolder.hasErrorResults()) registerReferencesFromInjectedFragments(comment);
}
@Override public void visitContinueStatement(PsiContinueStatement statement) {
@@ -510,6 +519,7 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
super.visitLiteralExpression(expression);
if (myHolder.hasErrorResults()) return;
myHolder.add(HighlightUtil.checkLiteralExpressionParsingError(expression));
if (!myHolder.hasErrorResults()) registerReferencesFromInjectedFragments(expression);
}
@Override public void visitMethod(PsiMethod method) {
@@ -15,9 +15,9 @@
*/
package com.intellij.codeInspection.varScopeCanBeNarrowed;
import com.intellij.codeInsight.CodeInsightUtil;
import com.intellij.codeInsight.daemon.GroupNames;
import com.intellij.codeInsight.daemon.ImplicitUsageProvider;
import com.intellij.codeInsight.CodeInsightUtil;
import com.intellij.codeInspection.InspectionsBundle;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
@@ -29,6 +29,7 @@ import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
@@ -153,13 +154,13 @@ public class FieldCanBeLocalInspection extends BaseLocalInspectionTool {
}
}
}
final Collection<PsiVariable> writtenVariables = ControlFlowUtil.getWrittenVariables(controlFlow, 0, controlFlow.getSize(), false);
final Ref<Collection<PsiVariable>> writtenVariables = new Ref<Collection<PsiVariable>>();
final List<PsiReferenceExpression> readBeforeWrites = ControlFlowUtil.getReadBeforeWrite(controlFlow);
for (final PsiReferenceExpression readBeforeWrite : readBeforeWrites) {
final PsiElement resolved = readBeforeWrite.resolve();
if (resolved instanceof PsiField) {
final PsiField field = (PsiField)resolved;
if (writtenVariables.contains(field)){
if (!(field.getType() instanceof PsiPrimitiveType) || getWrittenVariables(controlFlow, writtenVariables).contains(field)){
PsiElement parent = body.getParent();
if (!(parent instanceof PsiMethod) ||
!((PsiMethod)parent).isConstructor() ||
@@ -177,6 +178,13 @@ public class FieldCanBeLocalInspection extends BaseLocalInspectionTool {
}
}
private static Collection<PsiVariable> getWrittenVariables(ControlFlow controlFlow, Ref<Collection<PsiVariable>> writtenVariables) {
if (writtenVariables.get() == null) {
writtenVariables.set(ControlFlowUtil.getWrittenVariables(controlFlow, 0, controlFlow.getSize(), false));
}
return writtenVariables.get();
}
private static void removeFieldsReferencedFromInitializers(final PsiClass aClass, final Set<PsiField> candidates) {
aClass.accept(new JavaRecursiveElementWalkingVisitor() {
@Override public void visitMethod(PsiMethod method) {
@@ -549,18 +549,16 @@ public class JavaDocumentationProvider implements CodeDocumentationProvider, Ext
@Nullable
private static String generateExternalJavadoc(final PsiElement element, String fromUrl, boolean checkCompiled, JavaDocExternalFilter filter) {
if (!checkCompiled || element instanceof PsiCompiledElement) {
try {
String externalDoc = filter.getExternalDocInfoForElement(fromUrl, element);
if (externalDoc != null && externalDoc.length() > 0) {
return externalDoc;
}
}
catch (Exception e) {
//try to generate some javadoc
private static String fetchExternalJavadoc(final PsiElement element, String fromUrl, JavaDocExternalFilter filter) {
try {
String externalDoc = filter.getExternalDocInfoForElement(fromUrl, element);
if (externalDoc != null && externalDoc.length() > 0) {
return externalDoc;
}
}
catch (Exception e) {
//try to generate some javadoc
}
return null;
}
@@ -762,7 +760,7 @@ public class JavaDocumentationProvider implements CodeDocumentationProvider, Ext
if (docURLs != null) {
for (String docURL : docURLs) {
try {
final String javadoc = generateExternalJavadoc(element, docURL, true, docFilter);
final String javadoc = fetchExternalJavadoc(element, docURL, docFilter);
if (javadoc != null) return javadoc;
}
catch (IndexNotReadyException e) {
@@ -21,6 +21,7 @@ import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.*;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.augment.PsiAugmentProvider;
import com.intellij.psi.filters.OrFilter;
import com.intellij.psi.impl.compiled.ClsElementImpl;
import com.intellij.psi.impl.source.PsiImmediateClassType;
@@ -554,6 +555,10 @@ public class PsiClassImplUtil {
if (!processor.execute(field, state)) return false;
}
}
for (PsiField field : PsiAugmentProvider.collectAugments(aClass, PsiField.class)) {
if (!processor.execute(field, state)) return false;
}
}
if (classHint == null || classHint.shouldProcess(ElementClassHint.DeclaractionKind.METHOD)) {
@@ -566,6 +571,10 @@ public class PsiClassImplUtil {
}
if (!processor.execute(method, state)) return false;
}
for (PsiMethod method : PsiAugmentProvider.collectAugments(aClass, PsiMethod.class)) {
if (!processor.execute(method, state)) return false;
}
}
if (classHint == null || classHint.shouldProcess(ElementClassHint.DeclaractionKind.CLASS)) {
@@ -27,7 +27,6 @@ import com.intellij.openapi.ui.Queryable;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.augment.PsiAugmentProvider;
import com.intellij.psi.impl.InheritanceImplUtil;
import com.intellij.psi.impl.PsiClassImplUtil;
import com.intellij.psi.impl.PsiImplUtil;
@@ -52,7 +51,6 @@ import com.intellij.psi.stubs.IStubElementType;
import com.intellij.psi.stubs.PsiFileStub;
import com.intellij.psi.stubs.StubElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
@@ -304,16 +302,12 @@ public class PsiClassImpl extends JavaStubPsiElement<PsiClassStub<?>> implements
@NotNull
public PsiField[] getFields() {
final PsiField[] owns = getStubOrPsiChildren(Constants.FIELD_BIT_SET, PsiField.ARRAY_FACTORY);
final List<PsiField> augments = PsiAugmentProvider.collectAugments(this, PsiField.class);
return ArrayUtil.mergeArrayAndCollection(owns, augments, PsiField.ARRAY_FACTORY);
return getStubOrPsiChildren(Constants.FIELD_BIT_SET, PsiField.ARRAY_FACTORY);
}
@NotNull
public PsiMethod[] getMethods() {
final PsiMethod[] owns = getStubOrPsiChildren(Constants.METHOD_BIT_SET, PsiMethod.ARRAY_FACTORY);
final List<PsiMethod> augments = PsiAugmentProvider.collectAugments(this, PsiMethod.class);
return ArrayUtil.mergeArrayAndCollection(owns, augments, PsiMethod.ARRAY_FACTORY);
return getStubOrPsiChildren(Constants.METHOD_BIT_SET, PsiMethod.ARRAY_FACTORY);
}
@NotNull
@@ -671,7 +671,10 @@ public class ImportHelper{
PsiElement currentFileResolveScope = resolveResult.getCurrentFileResolveScope();
if (!(currentFileResolveScope instanceof PsiImportStatementBase)) continue;
if (context != null && currentFileResolveScope instanceof JspxImportStatement && context != ((JspxImportStatement)currentFileResolveScope).getDeclarationFile()) {
if (context != null &&
(!currentFileResolveScope.isValid() ||
currentFileResolveScope instanceof JspxImportStatement &&
context != ((JspxImportStatement)currentFileResolveScope).getDeclarationFile())) {
continue;
}
@@ -28,4 +28,10 @@ public class MethodProcessorSetupFailedException extends Exception{
public MethodProcessorSetupFailedException(@NonNls String message){
super(message);
}
@SuppressWarnings({"NonSynchronizedMethodOverridesSynchronizedMethod"})
@Override
public Throwable fillInStackTrace() {
return this;
}
}
@@ -56,20 +56,23 @@ public class JavaMethodsConflictResolver implements PsiConflictResolver{
public CandidateInfo resolveConflict(List<CandidateInfo> conflicts){
if (conflicts.isEmpty()) return null;
if (conflicts.size() == 1) return conflicts.get(0);
checkParametersNumber(conflicts, myActualParameterTypes.length, true);
if (conflicts.size() == 1) return conflicts.get(0);
checkSameSignatures(conflicts);
if (conflicts.size() == 1) return conflicts.get(0);
checkAccessLevels(conflicts);
if (conflicts.size() == 1) return conflicts.get(0);
checkParametersNumber(conflicts, myActualParameterTypes.length);
checkParametersNumber(conflicts, myActualParameterTypes.length, false);
if (conflicts.size() == 1) return conflicts.get(0);
final int applicabilityLevel = checkApplicability(conflicts);
if (conflicts.size() == 1) return conflicts.get(0);
checkSpecifics(conflicts, applicabilityLevel);
checkSpecifics(conflicts, applicabilityLevel);
if (conflicts.size() == 1) return conflicts.get(0);
THashSet<CandidateInfo> uniques = new THashSet<CandidateInfo>(conflicts);
@@ -196,9 +199,12 @@ public class JavaMethodsConflictResolver implements PsiConflictResolver{
return ((MethodCandidateInfo)info).isApplicable();
}
private static void checkParametersNumber(final List<CandidateInfo> conflicts, final int argumentsCount) {
private static void checkParametersNumber(final List<CandidateInfo> conflicts,
final int argumentsCount,
boolean checkForStaticAccessProblem) {
boolean parametersNumberMatch = false;
for (CandidateInfo info : conflicts) {
if (checkForStaticAccessProblem && !info.isStaticsScopeCorrect()) return;
if (info instanceof MethodCandidateInfo) {
final PsiMethod method = ((MethodCandidateInfo)info).getElement();
if (method.isVarArgs()) return;
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<problems/>
@@ -0,0 +1,11 @@
import java.util.*;
public class Outer {
private Map<String, String> value = new HashMap<String, String>();
public class Inner {
public Inner(String s) {
if (!value.containsKey(s)) value.put(s, "");
}
}
}
@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="UTF-8"?>
<problems>
</problems>
@@ -0,0 +1,8 @@
import java.util.*;
public class Test {
private final Map<String, String> myModuleToOutput = new HashMap<String, String>();
void foo() {
if (myModuleToOutput.containsKey(null)) myModuleToOutput.put("", "");
}
}
@@ -26,4 +26,6 @@ public class FieldCanBeLocalTest extends InspectionTestCase {
public void testStaticAccess() throws Exception { doTest(); }
public void testInnerClassConstructor() throws Exception { doTest(); }
public void testLocalVar2InnerClass() throws Exception { doTest(); }
public void testStateField() throws Exception { doTest(); }
public void testLocalStateVar2InnerClass() throws Exception { doTest(); }
}
@@ -32,8 +32,9 @@ public class DummyIdentifierPatcher extends FileCopyPatcher {
public void patchFileCopy(@NotNull final PsiFile fileCopy, @NotNull final Document document, @NotNull final OffsetMap map) {
if (StringUtil.isEmpty(myDummyIdentifier)) return;
document.replaceString(map.getOffset(CompletionInitializationContext.START_OFFSET), map.getOffset(CompletionInitializationContext.SELECTION_END_OFFSET),
myDummyIdentifier);
int startOffset = map.getOffset(CompletionInitializationContext.START_OFFSET);
int endOffset = map.getOffset(CompletionInitializationContext.SELECTION_END_OFFSET);
document.replaceString(startOffset, endOffset, myDummyIdentifier);
}
@Override
@@ -162,9 +162,14 @@ public class JdkUtil {
writer.close();
}
String classpath = PathUtil.getJarPathForClass(commandLineWrapper);
final Class<UrlClassLoader> ourUrlClassLoader = UrlClassLoader.class;
if (ourUrlClassLoader.getName().equals(parametersList.getPropertyValue("java.system.class.loader"))) {
classpath += File.pathSeparator + PathUtil.getJarPathForClass(ourUrlClassLoader);
}
commandLine.addParameter("-classpath");
commandLine.addParameter(PathUtil.getJarPathForClass(commandLineWrapper) + File.pathSeparator +
PathUtil.getJarPathForClass(UrlClassLoader.class));
commandLine.addParameter(classpath);
}
catch (IOException e) {
LOG.error(e);
@@ -179,4 +179,10 @@ public interface PsiSearchHelper {
@NotNull String text,
short searchContext,
boolean caseSensitive);
SearchCostResult isCheapEnoughToSearch(@NotNull String name, @NotNull GlobalSearchScope scope, @Nullable PsiFile fileToIgnoreOccurencesIn);
enum SearchCostResult {
ZERO_OCCURRENCES, FEW_OCCURRENCES, TOO_MANY_OCCURRENCES
}
}
@@ -29,13 +29,13 @@ import org.jetbrains.annotations.NotNull;
import java.util.Collection;
public abstract class StubIndex {
private static StubIndex ourInstance = CachedSingletonsRegistry.markCachedField(StubIndex.class);
private static class StubIndexHolder {
private static final StubIndex ourInstance = ApplicationManager.getApplication().getComponent(StubIndex.class);
}
public static StubIndex getInstance() {
if (ourInstance == null) {
ourInstance = ApplicationManager.getApplication().getComponent(StubIndex.class);
}
return ourInstance;
return StubIndexHolder.ourInstance;
}
public abstract <Key, Psi extends PsiElement> Collection<Psi> get(
@@ -28,6 +28,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PsiTreeUtil {
@@ -49,8 +50,8 @@ public class PsiTreeUtil {
public static boolean isAncestor(@Nullable PsiElement ancestor, @NotNull PsiElement element, boolean strict) {
if (ancestor == null) return false;
// fast path to avoid loading tree
if ((ancestor instanceof StubBasedPsiElement && (((StubBasedPsiElement)ancestor).getStub() != null)) ||
(element instanceof StubBasedPsiElement && ((StubBasedPsiElement)element).getStub() != null)) {
if (ancestor instanceof StubBasedPsiElement && ((StubBasedPsiElement)ancestor).getStub() != null ||
element instanceof StubBasedPsiElement && ((StubBasedPsiElement)element).getStub() != null) {
if (ancestor.getContainingFile() != element.getContainingFile()) return false;
}
@@ -345,7 +346,7 @@ public class PsiTreeUtil {
@NotNull
public static PsiElement[] collectElements(@Nullable PsiElement element, @NotNull PsiElementFilter filter) {
PsiElementProcessor.CollectFilteredElements processor = new PsiElementProcessor.CollectFilteredElements(filter);
PsiElementProcessor.CollectFilteredElements<PsiElement> processor = new PsiElementProcessor.CollectFilteredElements<PsiElement>(filter);
processElements(element, processor);
return processor.toArray();
}
@@ -551,7 +552,8 @@ public class PsiTreeUtil {
return false;
}
public static PsiElement[] filterAncestors(PsiElement[] elements) {
@NotNull
public static PsiElement[] filterAncestors(@NotNull PsiElement[] elements) {
if (LOG.isDebugEnabled()) {
for (PsiElement element : elements) {
LOG.debug("element = " + element);
@@ -559,9 +561,7 @@ public class PsiTreeUtil {
}
ArrayList<PsiElement> filteredElements = new ArrayList<PsiElement>();
for (PsiElement element : elements) {
filteredElements.add(element);
}
filteredElements.addAll(Arrays.asList(elements));
int previousSize;
do {
@@ -56,6 +56,11 @@ public class ControlFlowUtil {
public void clear() {
myIndex = -1;
}
@Override
public String toString() {
return "Stack(" + (myIndex + 1) + ") elements";
}
}
public static int[] postOrder(Instruction[] flow) {
@@ -74,7 +79,7 @@ public class ControlFlowUtil {
while (!stack.isEmpty()) {
final int num = stack.pop();
result[num] = N++;
result[N++] = num;
for (Instruction succ : flow[num].allSucc()) {
final int succNum = succ.num();
if (!visited[succNum]) {
@@ -21,10 +21,12 @@ package com.intellij.codeInsight.daemon.impl;
import com.intellij.codeHighlighting.TextEditorHighlightingPass;
import com.intellij.codeInsight.highlighting.BraceMatchingUtil;
import com.intellij.lang.LanguageParserDefinitions;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.editor.highlighter.HighlighterIterator;
import com.intellij.openapi.editor.markup.CustomHighlighterRenderer;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
@@ -36,6 +38,7 @@ import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.TokenSet;
import com.intellij.util.containers.IntStack;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.NotNull;
@@ -182,7 +185,7 @@ public class IndentsPass extends TextEditorHighlightingPass implements DumbAware
private List<IndentGuideDescriptor> buildDescriptors() {
if (!myEditor.getSettings().isIndentGuidesShown()) return Collections.emptyList();
int[] lineIndents = calcIndents(myDocument);
int[] lineIndents = calcIndents();
List<IndentGuideDescriptor> descriptors = new ArrayList<IndentGuideDescriptor>();
@@ -191,13 +194,14 @@ public class IndentsPass extends TextEditorHighlightingPass implements DumbAware
lines.push(0);
indents.push(0);
final CharSequence chars = myDocument.getCharsSequence();
for (int line = 1; line < lineIndents.length; line++) {
int curIndent = lineIndents[line];
while (!indents.empty() && curIndent <= indents.peek()) {
final int level = indents.pop();
int startLine = lines.pop();
descriptors.add(new IndentGuideDescriptor(level, startLine, line));
descriptors.add(createDescriptor(level, startLine, line, chars));
}
int prevLine = line - 1;
@@ -213,23 +217,47 @@ public class IndentsPass extends TextEditorHighlightingPass implements DumbAware
final int level = indents.pop();
if (level > 0) {
int startLine = lines.pop();
descriptors.add(new IndentGuideDescriptor(level, startLine, myDocument.getLineCount()));
descriptors.add(createDescriptor(level, startLine, myDocument.getLineCount(), chars));
}
}
return descriptors;
}
private int[] calcIndents(Document doc) {
private IndentGuideDescriptor createDescriptor(int level, int startLine, int endLine, CharSequence chars) {
while (startLine > 0 && isBlankLine(startLine, chars)) startLine--;
return new IndentGuideDescriptor(level, startLine, endLine);
}
private boolean isBlankLine(int line, CharSequence chars) {
int startOffset = myDocument.getLineStartOffset(line);
return CharArrayUtil.shiftForward(chars, startOffset, " \t") >= myDocument.getLineEndOffset(line);
}
private int[] calcIndents() {
final Document doc = myDocument;
CharSequence chars = doc.getCharsSequence();
int[] lineIndents = new int[doc.getLineCount()];
TokenSet comments = LanguageParserDefinitions.INSTANCE.forLanguage(myFile.getLanguage()).getCommentTokens();
int prevColumn = -1;
final EditorHighlighter highlighter = myEditor.getHighlighter();
for (int line = 0; line < lineIndents.length; line++) {
int lineStart = myDocument.getLineStartOffset(line);
int lineEnd = myDocument.getLineEndOffset(line);
int lineStart = doc.getLineStartOffset(line);
int lineEnd = doc.getLineEndOffset(line);
int nonWhitespaceOffset = CharArrayUtil.shiftForward(chars, lineStart, " \t");
if (nonWhitespaceOffset < lineEnd) {
lineIndents[line] = myEditor.calcColumnNumber(nonWhitespaceOffset, line);
final int column = myEditor.calcColumnNumber(nonWhitespaceOffset, line);
if (column < prevColumn) {
final HighlighterIterator it = highlighter.createIterator(nonWhitespaceOffset);
if (comments.contains(it.getTokenType())) {
lineIndents[line] = -1;
continue;
}
}
lineIndents[line] = column;
prevColumn = column;
}
else {
lineIndents[line] = -1;
@@ -243,13 +271,17 @@ public class IndentsPass extends TextEditorHighlightingPass implements DumbAware
}
else {
int startLine = line;
for (; line < lineIndents.length && lineIndents[line] == -1; line++);
while (line < lineIndents.length && lineIndents[line] == -1) {
//noinspection AssignmentToForLoopParameter
line++;
}
int bottomIndent = line < lineIndents.length ? lineIndents[line] : topIndent;
int indent = Math.min(topIndent, bottomIndent);
if (bottomIndent < topIndent) {
int nonWhitespaceOffset = CharArrayUtil.shiftForward(chars, myDocument.getLineStartOffset(line), " \t");
HighlighterIterator iterator = myEditor.getHighlighter().createIterator(nonWhitespaceOffset);
int nonWhitespaceOffset = CharArrayUtil.shiftForward(chars, doc.getLineStartOffset(line), " \t");
HighlighterIterator iterator = highlighter.createIterator(nonWhitespaceOffset);
if (BraceMatchingUtil.isRBraceToken(iterator, chars, myFile.getFileType())) {
indent = topIndent;
}
@@ -260,6 +292,7 @@ public class IndentsPass extends TextEditorHighlightingPass implements DumbAware
lineIndents[blankLine] = Math.min(topIndent, indent);
}
//noinspection AssignmentToForLoopParameter
line--; // will be incremented back at the end of the loop;
}
}
@@ -23,7 +23,7 @@ import java.util.*;
public class DFAEngine<E> {
private static final Logger LOG = Logger.getInstance(DFAEngine.class.getName());
private static final double TIME_LIMIT = 5*10e9;
private static final double TIME_LIMIT = 3*10e9;
private final Instruction[] myFlow;
@@ -86,6 +86,9 @@ public class DFAEngine<E> {
worklist.add(instruction);
visited[number] = true;
// It is essential to apply this check!!!
// This gives us more chances that resulting info will be closer to expected result
// Also it is used as indicator that "equals" method is implemented correctly in E
while (true) {
count++;
if (count > limit){
@@ -105,6 +108,9 @@ public class DFAEngine<E> {
final DFAMap<E> joinedE = join(currentInstruction, info);
final DFAMap<E> newE = myDfa.fun(joinedE, currentInstruction);
if (!mySemilattice.eq(newE, oldE)) {
if (LOG.isDebugEnabled()){
LOG.debug("Number: " + currentNumber + " old: " + oldE.keySet() + " new: " + newE.keySet());
}
info.set(currentNumber, newE);
for (Instruction next : getNext(currentInstruction)) {
worklist.add(next);
@@ -37,7 +37,7 @@ public class DFAMap<V> {
public DFAMap() {
}
public DFAMap(DFAMap<V> initialMap) {
private DFAMap(DFAMap<V> initialMap) {
myK = initialMap.myK;
myV = initialMap.myV;
myAll = initialMap.myAll == null ? null : new HashMap<String,V>(initialMap.myAll);
@@ -71,6 +71,7 @@ public class DFAMap<V> {
}
}
@Nullable
public V get(String key) {
if (myAll != null) {
return myAll.get(key);
@@ -166,6 +167,27 @@ public class DFAMap<V> {
}
public DFAMap<V> asWritable() {
return this;
return new DFAMap<V>(this);
}
@Override
public String toString() {
if (this == ourEmptyMap){
return "Empty Map";
}
if (myAll != null){
return myAll.toString();
}
if (myK != null){
return "{" + myK + "=" + myV + "}";
}
return "Empty";
}
public Set<String> keySet() {
if (myAll != null){
return myAll.keySet();
}
return myK != null ? Collections.singleton(myK) : Collections.<String>emptySet();
}
}
@@ -18,6 +18,8 @@ import com.intellij.codeInsight.controlflow.Instruction;
import org.jetbrains.annotations.NotNull;
public interface DfaInstance<E> {
// Please ensure that E has correctly implemented equals method
// Invariant: fun must create new instance of DFAMap if modifies it
DFAMap<E> fun(DFAMap<E> e, Instruction instruction);
@@ -20,6 +20,7 @@ import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.codeInsight.actions.BaseCodeInsightAction;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.navigation.NavigationUtil;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.ide.util.DefaultPsiElementCellRenderer;
@@ -65,10 +66,9 @@ public class GotoDeclarationAction extends BaseCodeInsightAction implements Code
public void invoke(@NotNull final Project project, @NotNull Editor editor, @NotNull PsiFile file) {
PsiDocumentManager.getInstance(project).commitAllDocuments();
PsiElement element;
try {
int offset = editor.getCaretModel().getOffset();
element = findTargetElement(project, editor, offset);
PsiElement element = findTargetElement(project, editor, offset);
if (element == null) {
FeatureUsageTracker.getInstance().triggerFeatureUsed("navigation.goto.declaration");
chooseAmbiguousTarget(editor, offset);
@@ -109,7 +109,10 @@ public class GotoDeclarationAction extends BaseCodeInsightAction implements Code
return true;
}
};
chooseAmbiguousTarget(editor, offset,navigateProcessor, CodeInsightBundle.message("declaration.navigation.title"));
boolean found = chooseAmbiguousTarget(editor, offset, navigateProcessor, CodeInsightBundle.message("declaration.navigation.title"));
if (!found) {
HintManager.getInstance().showErrorHint(editor, "Cannot find declaration to go to");
}
}
// returns true if processor is run or is going to be run after showing popup
@@ -127,7 +130,7 @@ public class GotoDeclarationAction extends BaseCodeInsightAction implements Code
processor.execute(element);
return true;
}
else if (candidates.size() > 1) {
if (candidates.size() > 1) {
PsiElement[] elements = candidates.toArray(new PsiElement[candidates.size()]);
final TextRange range = reference.getRangeInElement();
final String refText = range.substring(reference.getElement().getText());
@@ -43,23 +43,13 @@ public class CustomTemplateCallback {
private Project myProject;
private RangeMarker myGlobalMarker;
private RangeMarker myEndOffsetMarker;
//private final Map<Object, MyCheckpoint> myCheckpoints = new HashMap<Object, MyCheckpoint>();
private final Map<Object, RangeMarker> myCheckpoints = new HashMap<Object, RangeMarker>();
/*private static class MyCheckpoint {
int myFixedLength = null;
RangeMarker myFixedOffset;
}*/
public CustomTemplateCallback(Editor editor, PsiFile file) {
myEditor = editor;
myFile = file;
myProject = file.getProject();
myTemplateManager = TemplateManagerImpl.getInstance(myProject);
}
public void fixInitialEditorState() {
myStartOffset = myEditor.getCaretModel().getOffset();
myGlobalMarker = myEditor.getDocument().createRangeMarker(myStartOffset, myStartOffset);
myGlobalMarker.setGreedyToLeft(true);
@@ -305,6 +305,10 @@ public class TemplateImpl extends Template implements SchemeElement {
return variable;
}
public void removeVariable(int i) {
myVariables.remove(i);
}
public int getVariableCount() {
return myVariables.size();
}
@@ -246,7 +246,6 @@ public class TemplateManagerImpl extends TemplateManager implements ProjectCompo
int caretOffset = editor.getCaretModel().getOffset();
if (customLiveTemplate.isApplicable(file, caretOffset, false)) {
final CustomTemplateCallback callback = new CustomTemplateCallback(editor, file);
callback.fixInitialEditorState();
String key = customLiveTemplate.computeTemplateKey(callback);
if (key != null) {
int offsetBeforeKey = caretOffset - key.length();
@@ -26,6 +26,7 @@ import com.intellij.openapi.components.PathMacroManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.psi.PsiElement;
import com.intellij.util.ArrayUtil;
@@ -39,7 +40,6 @@ import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
/**
* @author max
@@ -263,7 +263,7 @@ public abstract class DescriptorProviderInspection extends InspectionTool implem
@NonNls final String template = description.getDescriptionTemplate();
int line = description instanceof ProblemDescriptor ? ((ProblemDescriptor)description).getLineNumber() : -1;
final String text = description instanceof ProblemDescriptor ? ((ProblemDescriptor)description).getPsiElement().getText() : "";
@NonNls String problemText = template.replaceAll("#ref", Matcher.quoteReplacement(text)).replaceAll(" #loc ", " ");
@NonNls String problemText = StringUtil.replace(StringUtil.replace(template, "#ref", StringUtil.quoteReplacement(text)), " #loc ", " ");
Element element = refEntity.getRefManager().export(refEntity, parentNode, line);
@NonNls Element problemClassElement = new Element(InspectionsBundle.message("inspection.export.results.problem.element.tag"));
@@ -214,6 +214,10 @@ public class LanguageConsoleImpl implements Disposable, TypeSafeDataProvider {
myUiUpdateRunnable = uiUpdateRunnable;
}
public void flushAllUiUpdates() {
myUpdateQueue.flush();
}
public LightVirtualFile getHistoryFile() {
return myHistoryFile;
}
@@ -3,7 +3,7 @@
<grid id="cae26" binding="myWholePanel" layout-manager="GridLayoutManager" row-count="5" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="13" y="24" width="615" height="128"/>
<xy x="13" y="24" width="615" height="165"/>
</constraints>
<properties/>
<border type="none"/>
@@ -25,15 +25,6 @@
</constraints>
<properties/>
</component>
<xy id="49cf" binding="myComponentPlace" layout-manager="XYLayout" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="0" row-span="1" col-span="2" vsize-policy="2" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children/>
</xy>
<xy id="ceb6c" binding="myOutlinePanel" layout-manager="XYLayout" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
@@ -79,6 +70,22 @@
<grid row="4" column="1" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<scrollpane id="9da09">
<constraints>
<grid row="1" column="0" row-span="1" col-span="2" vsize-policy="7" hsize-policy="7" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<xy id="49cf" binding="myComponentPlace" layout-manager="XYLayout" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints/>
<properties/>
<border type="none"/>
<children/>
</xy>
</children>
</scrollpane>
</children>
</grid>
</form>
@@ -578,50 +578,51 @@ public class RunContentManagerImpl implements RunContentManager, Disposable {
}
private void waitForProcess(final RunContentDescriptor descriptor) {
String progressTitle = ExecutionBundle.message("terminating.process.progress.title", descriptor.getDisplayName());
ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
private ProgressIndicator myProgressIndicator;
private final Semaphore mySemaphore = new Semaphore();
public void run() {
final Semaphore semaphore = new Semaphore();
semaphore.down();
private final Runnable myWaitThread = new Runnable() {
public void run() {
descriptor.getProcessHandler().waitFor();
mySemaphore.up();
}
};
private final Runnable myCancelListener = new Runnable() {
public void run() {
while(true) {
if(myProgressIndicator != null && (myProgressIndicator.isCanceled() || !myProgressIndicator.isRunning())) {
mySemaphore.up();
break;
}
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
public void run() {
final ProcessHandler processHandler = descriptor.getProcessHandler();
try {
synchronized (this) {
wait(2000);
if (processHandler != null) {
processHandler.waitFor();
}
}
catch (InterruptedException ignore) {
finally {
semaphore.up();
}
}
}
};
});
final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
public void run() {
myProgressIndicator = ProgressManager.getInstance().getProgressIndicator();
if (myProgressIndicator != null) {
myProgressIndicator.setText(ExecutionBundle.message("waiting.for.vm.detach.progress.text"));
if (progressIndicator != null) {
progressIndicator.setText(ExecutionBundle.message("waiting.for.vm.detach.progress.text"));
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
public void run() {
while(true) {
if(progressIndicator.isCanceled() || !progressIndicator.isRunning()) {
semaphore.up();
break;
}
try {
synchronized (this) {
wait(2000L);
}
}
catch (InterruptedException ignore) {
}
}
}
});
}
ApplicationManager.getApplication().executeOnPooledThread(myWaitThread);
ApplicationManager.getApplication().executeOnPooledThread(myCancelListener);
mySemaphore.down();
mySemaphore.waitFor();
semaphore.waitFor();
}
}, progressTitle, true, myProject);
}, ExecutionBundle.message("terminating.process.progress.title", descriptor.getDisplayName()), true, myProject);
}
public interface MyRunContentListener extends EventListener {
@@ -184,6 +184,7 @@ public class ShowUsagesAction extends AnAction {
usageViewSettings.GROUP_BY_MODULE = false;
usageViewSettings.GROUP_BY_PACKAGE = false;
usageViewSettings.GROUP_BY_USAGE_TYPE = false;
usageViewSettings.GROUP_BY_SCOPE = false;
UsageViewManager manager = UsageViewManager.getInstance(handler.getProject());
final UsageViewImpl usageView = (UsageViewImpl)manager.createUsageView(UsageTarget.EMPTY_ARRAY, Usage.EMPTY_ARRAY, presentation, null);
@@ -194,6 +195,7 @@ public class ShowUsagesAction extends AnAction {
usageViewSettings.GROUP_BY_MODULE = save.GROUP_BY_MODULE;
usageViewSettings.GROUP_BY_PACKAGE = save.GROUP_BY_PACKAGE;
usageViewSettings.GROUP_BY_USAGE_TYPE = save.GROUP_BY_USAGE_TYPE;
usageViewSettings.GROUP_BY_SCOPE = save.GROUP_BY_SCOPE;
}
});
@@ -694,4 +696,4 @@ public class ShowUsagesAction extends AnAction {
return null;
}
}
}
}
@@ -48,7 +48,7 @@ public abstract class GotoActionBase extends AnAction {
protected abstract void gotoActionPerformed(AnActionEvent e);
public final void update(final AnActionEvent event) {
public void update(final AnActionEvent event) {
final Presentation presentation = event.getPresentation();
final DataContext dataContext = event.getDataContext();
final Project project = PlatformDataKeys.PROJECT.getData(dataContext);
@@ -59,6 +59,7 @@ import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
@@ -457,14 +458,15 @@ public class FavoritesTreeViewPanel extends JPanel implements DataProvider {
}
}
private PsiDirectory getDirectory() {
@Nullable
private PsiDirectory[] getSelectedDirectories() {
if (myBuilder == null) return null;
final Object[] selectedNodeElements = getSelectedNodeElements();
if (selectedNodeElements.length != 1) return null;
for (FavoriteNodeProvider nodeProvider : Extensions.getExtensions(FavoriteNodeProvider.EP_NAME, myProject)) {
final PsiElement psiElement = nodeProvider.getPsiElement(selectedNodeElements[0]);
if (psiElement instanceof PsiDirectory) {
return (PsiDirectory)psiElement;
return new PsiDirectory[]{(PsiDirectory)psiElement};
} else if (psiElement instanceof PsiDirectoryContainer) {
final String moduleName = nodeProvider.getElementModuleName(selectedNodeElements[0]);
GlobalSearchScope searchScope = GlobalSearchScope.projectScope(myProject);
@@ -474,16 +476,15 @@ public class FavoritesTreeViewPanel extends JPanel implements DataProvider {
searchScope = GlobalSearchScope.moduleScope(module);
}
}
final PsiDirectory[] directories = ((PsiDirectoryContainer)psiElement).getDirectories(searchScope);
if (directories.length == 1) return directories[0];
return ((PsiDirectoryContainer)psiElement).getDirectories(searchScope);
}
}
return null;
}
public PsiDirectory[] getDirectories() {
PsiDirectory directory = getDirectory();
return directory == null ? PsiDirectory.EMPTY_ARRAY : new PsiDirectory[]{directory};
final PsiDirectory[] directories = getSelectedDirectories();
return directories == null ? PsiDirectory.EMPTY_ARRAY : directories;
}
public PsiDirectory getOrChooseDirectory() {
@@ -20,7 +20,7 @@ import com.intellij.openapi.util.Iconable;
import com.intellij.psi.PsiElement;
import com.intellij.psi.presentation.java.SymbolPresentationUtil;
public class DefaultPsiElementCellRenderer extends PsiElementListCellRenderer {
public class DefaultPsiElementCellRenderer extends PsiElementListCellRenderer<PsiElement> {
protected int getIconFlags() {
return Iconable.ICON_FLAG_VISIBILITY;
}
@@ -33,4 +33,4 @@ public class DefaultPsiElementCellRenderer extends PsiElementListCellRenderer {
return SymbolPresentationUtil.getSymbolContainerText(element);
}
}
}
@@ -99,12 +99,11 @@ public abstract class PsiElementListCellRenderer<T extends PsiElement> extends J
}
}
SimpleTextAttributes nameAttributes;
if (isProblemFile) {
attributes = TextAttributes.merge(new TextAttributes(color, null, Color.red, EffectType.WAVE_UNDERSCORE, Font.PLAIN),attributes);
}
nameAttributes = attributes != null ? SimpleTextAttributes.fromTextAttributes(attributes):null;
SimpleTextAttributes nameAttributes = attributes != null ? SimpleTextAttributes.fromTextAttributes(attributes) : null;
if (nameAttributes == null) nameAttributes = new SimpleTextAttributes(Font.PLAIN, color);
@@ -27,6 +27,7 @@ import com.intellij.openapi.editor.ex.*;
import com.intellij.openapi.editor.impl.DocumentImpl;
import com.intellij.openapi.editor.markup.MarkupModel;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.ProperTextRange;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.UserDataHolderBase;
@@ -40,8 +41,8 @@ import org.jetbrains.annotations.Nullable;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.List;
/**
* @author Alexey
@@ -254,9 +255,47 @@ public class DocumentWindowImpl extends UserDataHolderBase implements Disposable
startOffset += perfixLength;
endOffset -= suffixLength;
s = s.subSequence(perfixLength, s.length() - suffixLength);
deleteString(startOffset, endOffset);
insertString(startOffset, s);
doReplaceString(startOffset, endOffset, s);
}
private void doReplaceString(int startOffset, int endOffset, CharSequence s) {
assert intersectWithEditable(new TextRange(startOffset, startOffset)) != null;
assert intersectWithEditable(new TextRange(endOffset, endOffset)) != null;
List<Pair<TextRange,CharSequence>> hostRangesToModify = new ArrayList<Pair<TextRange, CharSequence>>(myShreds.size());
int offset = startOffset;
int curRangeStart = 0;
for (int i = 0; i < myShreds.size(); i++) {
PsiLanguageInjectionHost.Shred shred = myShreds.get(i);
curRangeStart += shred.prefix.length();
if (offset < curRangeStart) offset = curRangeStart;
RangeMarker hostRange = shred.getHostRangeMarker();
if (!hostRange.isValid()) continue;
int hostRangeLength = hostRange.getEndOffset() - hostRange.getStartOffset();
TextRange range = TextRange.from(curRangeStart, hostRangeLength);
if (range.contains(offset) || range.getEndOffset() == offset/* in case of inserting at the end*/) {
TextRange rangeToModify = new TextRange(offset, Math.min(range.getEndOffset(), endOffset));
TextRange hostRangeToModify = rangeToModify.shiftRight(hostRange.getStartOffset() - curRangeStart);
CharSequence toReplace = i == myShreds.size() - 1 ? s : s.subSequence(0, Math.min(hostRangeToModify.getLength(), s.length()));
s = s.subSequence(toReplace.length(), s.length());
hostRangesToModify.add(Pair.create(hostRangeToModify, toReplace));
offset = rangeToModify.getEndOffset();
}
curRangeStart += hostRangeLength;
curRangeStart += shred.suffix.length();
if (curRangeStart >= endOffset) break;
}
int delta = 0;
for (Pair<TextRange, CharSequence> pair : hostRangesToModify) {
TextRange hostRange = pair.getFirst();
CharSequence replace = pair.getSecond();
myDelegate.replaceString(hostRange.getStartOffset() + delta, hostRange.getEndOffset() + delta, replace);
delta -= hostRange.getLength() - replace.length();
}
}
public boolean isWritable() {
@@ -25,11 +25,16 @@
package com.intellij.openapi.editor.actions;
import com.intellij.codeInsight.editorActions.SelectWordUtil;
import com.intellij.codeInsight.highlighting.BraceMatchingUtil;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.highlighter.HighlighterIterator;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.text.CharArrayUtil;
import java.util.ArrayList;
import java.util.List;
@@ -111,7 +116,23 @@ public class SelectWordAtCaretAction extends TextComponentEditorAction implement
private static void selectWithGuide(Editor editor, IndentGuideDescriptor guide) {
final Document doc = editor.getDocument();
int startOffset = editor.logicalPositionToOffset(new LogicalPosition(guide.startLine, 0));
int endOffset = Math.min(editor.logicalPositionToOffset(new LogicalPosition(guide.endLine + 1, 0)), doc.getTextLength());
int endOffset = Math.min(doc.getLineStartOffset(guide.endLine), doc.getTextLength());
final VirtualFile file = ((EditorEx)editor).getVirtualFile();
if (file != null) {
// Make sure selection contains closing matching brace.
final CharSequence chars = doc.getCharsSequence();
int nonWhitespaceOffset = CharArrayUtil.shiftForward(chars, endOffset, " \t\n");
HighlighterIterator iterator = ((EditorEx)editor).getHighlighter().createIterator(nonWhitespaceOffset);
if (BraceMatchingUtil.isRBraceToken(iterator, chars, file.getFileType())) {
if (((EditorEx)editor).calcColumnNumber(iterator.getStart(), doc.getLineNumber(iterator.getStart())) == guide.indentLevel) {
endOffset = iterator.getEnd();
endOffset = CharArrayUtil.shiftForward(chars, endOffset, " \t");
if (endOffset < chars.length() && chars.charAt(endOffset) == '\n') endOffset++;
}
}
}
editor.getSelectionModel().setSelection(startOffset, endOffset);
}
@@ -32,7 +32,6 @@ import java.util.ArrayList;
import java.util.List;
public class DefaultScopesProvider implements CustomScopesProvider {
private static NamedScope myAllScope;
private NamedScope myProblemsScope;
private final Project myProject;
@@ -55,27 +54,28 @@ public class DefaultScopesProvider implements CustomScopesProvider {
return list;
}
private static class NamedScopeHolder {
private static final NamedScope myAllScope = new NamedScope("All", new PackageSet() {
public boolean contains(final PsiFile file, final NamedScopesHolder holder) {
return true;
}
public PackageSet createCopy() {
return this;
}
public String getText() {
return FilePatternPackageSet.SCOPE_FILE + ":*//*";
}
public int getNodePriority() {
return 0;
}
});
}
public static NamedScope getAllScope() {
if (myAllScope == null) {
myAllScope = new NamedScope("All", new PackageSet() {
public boolean contains(final PsiFile file, final NamedScopesHolder holder) {
return true;
}
public PackageSet createCopy() {
return this;
}
public String getText() {
return FilePatternPackageSet.SCOPE_FILE + ":*//*";
}
public int getNodePriority() {
return 0;
}
});
}
return myAllScope;
return NamedScopeHolder.myAllScope;
}
public NamedScope getProblemsScope() {
@@ -100,4 +100,4 @@ public class DefaultScopesProvider implements CustomScopesProvider {
}
return myProblemsScope;
}
}
}
@@ -26,6 +26,7 @@ import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.PsiDocumentManagerImpl;
import com.intellij.psi.impl.PsiToDocumentSynchronizer;
import org.jetbrains.annotations.NotNull;
public class FormattingDocumentModelImpl implements FormattingDocumentModel{
@@ -56,7 +57,7 @@ public class FormattingDocumentModelImpl implements FormattingDocumentModel{
}
private static Document getDocumentToBeUsedFor(final PsiFile file) {
public static Document getDocumentToBeUsedFor(final PsiFile file) {
final Project project = file.getProject();
final Document document = PsiDocumentManager.getInstance(project).getDocument(file);
if (document == null) return null;
@@ -91,4 +92,11 @@ public class FormattingDocumentModelImpl implements FormattingDocumentModel{
public PsiFile getFile() {
return myFile;
}
public static boolean canUseDocumentModel(@NotNull Document document,@NotNull PsiFile file) {
PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(file.getProject());
return !psiDocumentManager.isUncommited(document) &&
!psiDocumentManager.isDocumentBlockedByPsi(document) &&
file.getText().equals(document.getText());
}
}
@@ -158,11 +158,11 @@ public class PsiSearchHelperImpl implements PsiSearchHelper {
return processElementsWithWord(occurenceProcessor, searchScope, identifier, UsageSearchContext.IN_COMMENTS, true);
}
public boolean processElementsWithWord(@NotNull TextOccurenceProcessor processor,
public boolean processElementsWithWord(@NotNull final TextOccurenceProcessor processor,
@NotNull SearchScope searchScope,
@NotNull String text,
@NotNull final String text,
short searchContext,
boolean caseSensitively) {
final boolean caseSensitively) {
if (text.length() == 0) {
throw new IllegalArgumentException("Cannot search for elements with empty text");
}
@@ -179,10 +179,11 @@ public class PsiSearchHelperImpl implements PsiSearchHelper {
PsiElement[] scopeElements = scope.getScope();
final boolean ignoreInjectedPsi = scope.isIgnoreInjectedPsi();
for (final PsiElement scopeElement : scopeElements) {
if (!processElementsWithWordInScopeElement(scopeElement, processor, text, caseSensitively, ignoreInjectedPsi)) return false;
}
return true;
return JobUtil.invokeConcurrentlyUnderMyProgress(Arrays.asList(scopeElements), new Processor<PsiElement>() {
public boolean process(PsiElement scopeElement) {
return processElementsWithWordInScopeElement(scopeElement, processor, text, caseSensitively, ignoreInjectedPsi);
}
}, "textsearch");
}
}
@@ -200,7 +201,7 @@ public class PsiSearchHelperImpl implements PsiSearchHelper {
}).booleanValue();
}
private boolean processElementsWithTextInGlobalScope(final TextOccurenceProcessor processor,
private boolean processElementsWithTextInGlobalScope(@NotNull final TextOccurenceProcessor processor,
final GlobalSearchScope scope,
final StringSearcher searcher,
final short searchContext,
@@ -424,10 +425,7 @@ public class PsiSearchHelperImpl implements PsiSearchHelper {
myManager.getCacheManager().processFilesWithWord(processor, word, UsageSearchContext.IN_STRINGS, scope, true);
}
public static enum Result {
ZERO_OCCURRENCES, FEW_OCCURRENCES, TOO_MANY_OCCURRENCES
}
public Result isItCheapEnoughToSearch(@Nullable final PsiFile fileToIgnoreOccurencesIn, @NotNull String name, @NotNull GlobalSearchScope scope) {
public SearchCostResult isCheapEnoughToSearch(@NotNull String name, @NotNull GlobalSearchScope scope, @Nullable final PsiFile fileToIgnoreOccurencesIn) {
final int[] count = {0};
if (!processFilesWithText(scope, UsageSearchContext.ANY, true, name, new Processor<PsiFile>() {
public boolean process(PsiFile file) {
@@ -438,11 +436,11 @@ public class PsiSearchHelperImpl implements PsiSearchHelper {
}
}
})) {
return Result.TOO_MANY_OCCURRENCES;
return SearchCostResult.TOO_MANY_OCCURRENCES;
}
synchronized (count) {
return count[0] == 0 ? Result.ZERO_OCCURRENCES : Result.FEW_OCCURRENCES;
return count[0] == 0 ? SearchCostResult.ZERO_OCCURRENCES : SearchCostResult.FEW_OCCURRENCES;
}
}
}
@@ -287,13 +287,12 @@ public class FileBasedIndex implements ApplicationComponent {
}
}
private static FileBasedIndex ourInstance = CachedSingletonsRegistry.markCachedField(FileBasedIndex.class);
public static FileBasedIndex getInstance() {
if (ourInstance == null) {
ourInstance = ApplicationManager.getApplication().getComponent(FileBasedIndex.class);
}
private static class FileBasedIndexHolder {
private static final FileBasedIndex ourInstance = ApplicationManager.getApplication().getComponent(FileBasedIndex.class);
}
return ourInstance;
public static FileBasedIndex getInstance() {
return FileBasedIndexHolder.ourInstance;
}
/**
@@ -18,7 +18,7 @@ package com.intellij.history.integration.patches;
import com.intellij.history.integration.IdeaGateway;
import com.intellij.openapi.diff.impl.patch.FilePatch;
import com.intellij.openapi.diff.impl.patch.PatchBuilder;
import com.intellij.openapi.diff.impl.patch.TextPatchBuilder;
import com.intellij.openapi.diff.impl.patch.UnifiedDiffWriter;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.Change;
@@ -35,7 +35,7 @@ public class PatchCreator {
throws IOException, VcsException {
Writer writer = new OutputStreamWriter(new FileOutputStream(filePath));
try {
List<FilePatch> patches = PatchBuilder.buildPatch(changes, gw.getBaseDir(), false, isReverse);
List<FilePatch> patches = TextPatchBuilder.buildPatch(changes, gw.getBaseDir(), isReverse);
String lineSeparator = CodeStyleSettingsManager.getInstance(gw.getProject()).getCurrentSettings().getLineSeparator();
UnifiedDiffWriter.write(patches, writer, lineSeparator);
}
@@ -16,8 +16,10 @@
package com.intellij.historyIntegrTests;
import com.intellij.openapi.diff.impl.patch.BinaryFilePatch;
import com.intellij.openapi.diff.impl.patch.FilePatch;
import com.intellij.openapi.diff.impl.patch.PatchReader;
import com.intellij.openapi.diff.impl.patch.PatchVirtualFileReader;
import com.intellij.openapi.diff.impl.patch.formove.PatchApplier;
import com.intellij.openapi.vfs.VirtualFile;
@@ -44,7 +46,7 @@ public abstract class PatchingTestCase extends IntegrationTestCase {
protected void applyPatch() throws Exception {
List<FilePatch> patches = new ArrayList<FilePatch>();
PatchReader reader = new PatchReader(getFS().refreshAndFindFileByPath(patchFilePath));
PatchReader reader = PatchVirtualFileReader.create(getFS().refreshAndFindFileByPath(patchFilePath));
while (true) {
FilePatch p = reader.readNextPatch();
@@ -52,6 +54,6 @@ public abstract class PatchingTestCase extends IntegrationTestCase {
patches.add(p);
}
new PatchApplier(myProject, root, patches, null, null).execute();
new PatchApplier<BinaryFilePatch>(myProject, root, patches, null, null).execute();
}
}
@@ -91,18 +91,19 @@ public class OSProcessHandler extends ProcessHandler {
public ProcessWaitFor(final Process process) {
myWaitSemaphore.down();
final Runnable action = new Runnable() {
myWaitForThreadFuture = executeOnPooledThread(new Runnable() {
public void run() {
try {
myExitCode = process.waitFor();
}
catch (InterruptedException ignored) {
}
myWaitSemaphore.up();
finally {
myWaitSemaphore.up();
}
}
};
myWaitForThreadFuture = executeOnPooledThread(action);
});
}
public int waitFor() {
@@ -17,7 +17,6 @@ package com.intellij.openapi.fileTypes;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.CachedSingletonsRegistry;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
@@ -31,18 +30,22 @@ import java.util.List;
*/
public abstract class FileTypeManager{
private static FileTypeManager ourInstance = CachedSingletonsRegistry.markCachedField(FileTypeManager.class);
private static class FileTypeManagerHolder {
private static final FileTypeManager ourInstance = createFileTypeManager();
}
/**
* Returns the singleton instance of the FileTypeManager component.
*
* @return the instace of FileTypeManager
*/
public static FileTypeManager getInstance() {
if (ourInstance == null) {
Application app = ApplicationManager.getApplication();
ourInstance = app != null ? app.getComponent(FileTypeManager.class) : new MockFileTypeManager();
}
return ourInstance;
return FileTypeManagerHolder.ourInstance;
}
private static FileTypeManager createFileTypeManager() {
Application app = ApplicationManager.getApplication();
return app == null ? new MockFileTypeManager() : app.getComponent(FileTypeManager.class);
}
public abstract void registerFileType(@NotNull FileType type, @NotNull List<FileNameMatcher> defaultAssociations);
@@ -777,6 +777,10 @@ public abstract class MasterDetailsComponent implements Configurable, Persistent
public boolean isDisplayInBold() {
return myDisplayInBold;
}
public void setDisplayInBold(boolean displayInBold) {
myDisplayInBold = displayInBold;
}
}
@SuppressWarnings({"ConstantConditions"})
@@ -19,8 +19,8 @@ import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.util.concurrency.Semaphore;
import java.util.concurrent.Future;
import java.io.IOException;
import java.util.concurrent.Future;
public class ProcessCloseUtil {
private static final long ourSynchronousWaitTimeout = 1000;
@@ -34,25 +34,32 @@ public class ProcessCloseUtil {
outerSemaphore.down();
final Application application = ApplicationManager.getApplication();
final Future<?> future = application.executeOnPooledThread(new Runnable() {
application.executeOnPooledThread(new Runnable() {
public void run() {
final Semaphore semaphore = new Semaphore();
semaphore.down();
try {
final Semaphore semaphore = new Semaphore();
semaphore.down();
final Runnable closeRunnable = new Runnable() {
public void run() {
closeProcessImpl(process);
semaphore.up();
final Runnable closeRunnable = new Runnable() {
public void run() {
try {
closeProcessImpl(process);
}
finally {
semaphore.up();
}
}
};
final Future<?> innerFuture = application.executeOnPooledThread(closeRunnable);
semaphore.waitFor(ourAsynchronousWaitTimeout);
if ( ! (innerFuture.isDone() || innerFuture.isCancelled())) {
innerFuture.cancel(true); // will call interrupt()
}
};
final Future<?> innerFuture = application.executeOnPooledThread(closeRunnable);
semaphore.waitFor(ourAsynchronousWaitTimeout);
if ( ! (innerFuture.isDone() || innerFuture.isCancelled())) {
innerFuture.cancel(true); // will call interrupt()
}
outerSemaphore.up();
finally {
outerSemaphore.up();
}
}
});
@@ -30,13 +30,13 @@ import java.io.DataOutputStream;
import java.util.List;
public abstract class ManagingFS implements FileSystemInterface {
private static ManagingFS ourInstance = CachedSingletonsRegistry.markCachedField(ManagingFS.class);
private static class ManagingFSHolder {
private static final ManagingFS ourInstance = ApplicationManager.getApplication().getComponent(ManagingFS.class);
}
public static ManagingFS getInstance() {
if (ourInstance == null) {
ourInstance = ApplicationManager.getApplication().getComponent(ManagingFS.class);
}
return ourInstance;
return ManagingFSHolder.ourInstance;
}
@Nullable
@@ -25,7 +25,12 @@ import javax.swing.*;
* @since 5.1
*/
public class DialogUtil {
public static void registerMnemonic(AbstractButton button) {
registerMnemonic(button, UIUtil.MNEMONIC);
}
public static void registerMnemonic(AbstractButton button, char mn) {
String text = button.getText();
if (text != null) {
@@ -34,7 +39,7 @@ public class DialogUtil {
int index = -1;
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (ch != UIUtil.MNEMONIC) {
if (ch != mn) {
realText.append(ch);
}
else if (i + 1 < text.length()) {
@@ -28,7 +28,7 @@ import java.awt.*;
public abstract class OptionsDialog extends DialogWrapper {
private JCheckBox myCheckBoxDoNotShowDialog;
protected JCheckBox myCheckBoxDoNotShowDialog;
protected String getDoNotShowMessage() {
return CommonBundle.message("dialog.options.do.not.show");
@@ -68,6 +68,7 @@ public abstract class OptionsDialog extends DialogWrapper {
final JPanel panel = addDoNotShowCheckBox(southPanel, myCheckBoxDoNotShowDialog);
myCheckBoxDoNotShowDialog.setSelected(!isToBeShown());
DialogUtil.registerMnemonic(myCheckBoxDoNotShowDialog, '&');
return panel;
}
@@ -19,6 +19,7 @@ import com.intellij.ide.highlighter.ProjectFileType;
import com.intellij.ide.impl.ProjectUtil;
import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileElement;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.vfs.VirtualFile;
@@ -66,6 +67,7 @@ public class OpenProjectFileChooserDescriptor extends FileChooserDescriptor {
}
public boolean isFileVisible(final VirtualFile file, final boolean showHiddenFiles) {
if (!showHiddenFiles && FileElement.isFileHidden(file)) return false;
return isProjectFile(file) || super.isFileVisible(file, showHiddenFiles) && file.isDirectory();
}
@@ -16,13 +16,13 @@
package com.intellij.ide.ui.search;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurableGroup;
import com.intellij.openapi.options.MasterDetails;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.options.ConfigurableGroup;
import com.intellij.openapi.options.ex.GlassPanel;
import com.intellij.openapi.options.ex.IdeConfigurablesGroup;
import com.intellij.openapi.options.ex.ProjectConfigurablesGroup;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
@@ -62,11 +62,8 @@ public class SearchUtil {
}
public static void processProjectConfigurables(Project project, HashMap<SearchableConfigurable, TreeSet<OptionDescription>> options) {
processConfigurables(project.getExtensions(Configurable.PROJECT_CONFIGURABLES), options);
processConfigurables(project.getComponents(Configurable.class), options);
final Application app = ApplicationManager.getApplication();
processConfigurables(app.getExtensions(Configurable.APPLICATION_CONFIGURABLES), options);
processConfigurables(app.getComponents(Configurable.class), options);
processConfigurables(new ProjectConfigurablesGroup(project, false).getConfigurables(), options);
processConfigurables(new IdeConfigurablesGroup().getConfigurables(), options);
}
private static void processConfigurables(final Configurable[] configurables,
@@ -157,7 +157,7 @@ public class SearchableOptionsRegistrarImpl extends SearchableOptionsRegistrar {
Set<OptionDescription> configs = myStorage.get(option);
if (configs == null) {
configs = new THashSet<OptionDescription>(3, 0.9f);
myStorage.put(option, configs);
myStorage.put(new String(option), configs);
}
configs.add(new OptionDescription(null, myIdentifierTable.intern(id), hit != null ? myIdentifierTable.intern(hit) : null,
@@ -31,7 +31,7 @@ public class DocumentReferenceByVirtualFile implements DocumentReference {
@Nullable
public Document getDocument() {
assert myFile.isValid() : "should not be called on references to deleted files";
assert myFile.isValid() : "should not be called on references to deleted file: " + myFile;
return FileDocumentManager.getInstance().getDocument(myFile);
}
@@ -19,8 +19,9 @@
*/
package com.intellij.openapi.editor.impl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.IndentGuideDescriptor;
import com.intellij.openapi.editor.IndentsModel;
import com.intellij.openapi.editor.LogicalPosition;
import java.util.ArrayList;
import java.util.List;
@@ -37,9 +38,12 @@ public class IndentsModelImpl implements IndentsModel {
final LogicalPosition pos = myEditor.getCaretModel().getLogicalPosition();
final int column = pos.column;
final int line = pos.line;
for (IndentGuideDescriptor indent : myIndents) {
if (column == indent.indentLevel && line >= indent.startLine && line < indent.endLine) {
return indent;
if (column > 0) {
for (IndentGuideDescriptor indent : myIndents) {
if (column == indent.indentLevel && line >= indent.startLine && line < indent.endLine) {
return indent;
}
}
}
return null;
@@ -15,10 +15,11 @@
*/
package com.intellij.openapi.fileChooser.ex;
import com.intellij.openapi.fileChooser.FileSystemTree;
import com.intellij.openapi.fileChooser.FileSaverDescriptor;
import com.intellij.openapi.fileChooser.FileSaverDialog;
import com.intellij.openapi.fileChooser.FileSystemTree;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileWrapper;
import com.intellij.ui.DocumentAdapter;
@@ -160,4 +161,18 @@ public class FileSaverDialogImpl extends FileChooserDialogImpl implements FileSa
//double check. FileChooserFactoryImpl sets enable ok button
super.setOKActionEnabled(isFileNameExist());
}
@Override
protected void doOKAction() {
final File file = getFile();
if (file != null && file.exists()) {
if (OK_EXIT_CODE != Messages.showYesNoDialog(this.getRootPane(),
UIBundle.message("file.chooser.save.dialog.confirmation", file.getName()),
UIBundle.message("file.chooser.save.dialog.confirmation.title"),
Messages.getWarningIcon())) {
return;
}
}
super.doOKAction();
}
}
@@ -66,7 +66,7 @@ public class ProgressManagerImpl extends ProgressManager {
}
}
};
thread.setPriority(Thread.MIN_PRIORITY + 1);
thread.setPriority(Thread.MAX_PRIORITY - 1);
thread.start();
}
}
@@ -142,8 +142,12 @@ public class SmoothProgressAdapter extends BlockingProgressIndicator {
}
);
super.stop(); // should be last to not leaveModal before closing the dialog
semaphore.up();
try {
super.stop(); // should be last to not leaveModal before closing the dialog
}
finally {
semaphore.up();
}
}
public synchronized void setText(String text) {
@@ -111,7 +111,7 @@ public class DumbServiceImpl extends DumbService {
}
try {
final int size = runner.queryNeededFiles(indicator);
if ((size + runner.getNumberOfPendingUpdateJobs(indicator)) < 50) {
if (application.isHeadlessEnvironment() || (size + runner.getNumberOfPendingUpdateJobs(indicator)) < 50) {
// If not that many files found, process them on the spot, avoiding entering dumb mode
// Consider number of pending tasks as well, becase they may take noticeable time to process even if the number of files is small
if (size > 0) {
@@ -227,10 +227,10 @@ public class DumbServiceImpl extends DumbService {
final Semaphore semaphore = new Semaphore();
semaphore.down();
runWhenSmart(new Runnable() {
public void run() {
semaphore.up();
}
});
public void run() {
semaphore.up();
}
});
semaphore.waitFor();
}
@@ -21,6 +21,8 @@ import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.vfs.InvalidVirtualFileAccessException;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS;
import org.jetbrains.annotations.NotNull;
@@ -74,60 +76,12 @@ public class FileContentQueue {
}
private void put(VirtualFile file) throws InterruptedException {
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
FileContent content = new FileContent(file);
if (file.isValid()) {
final long contentLength = content.getLength();
boolean counterUpdated = false;
try {
if (contentLength < PersistentFS.MAX_INTELLISENSE_FILESIZE) {
synchronized (this) {
while (myTotalSize > SIZE_THRESHOLD) {
if (indicator != null) {
indicator.checkCanceled();
}
wait(300);
}
myTotalSize += contentLength;
counterUpdated = true;
}
content.getBytes(); // Reads the content bytes and caches them.
}
}
catch (IOException e) {
LOG.info(e);
if (counterUpdated) {
synchronized (this) {
myTotalSize -= contentLength; // revert size counter
notifyAll();
}
}
if (!doLoadContent(content)) {
content.setEmptyContent();
}
catch (ProcessCanceledException e) {
if (counterUpdated) {
synchronized (this) {
myTotalSize -= contentLength; // revert size counter
notifyAll();
}
}
throw e;
}
catch (InterruptedException e) {
if (counterUpdated) {
synchronized (this) {
myTotalSize -= contentLength; // revert size counter
notifyAll();
}
}
return;
}
catch (Throwable e) {
LOG.error(e);
}
}
else {
content.setEmptyContent();
@@ -136,6 +90,46 @@ public class FileContentQueue {
myQueue.put(content);
}
private boolean doLoadContent(final FileContent content) throws InterruptedException {
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
final long contentLength = content.getLength();
boolean counterUpdated = false;
try {
if (contentLength < PersistentFS.MAX_INTELLISENSE_FILESIZE) {
synchronized (this) {
while (myTotalSize > SIZE_THRESHOLD) {
if (indicator != null) {
indicator.checkCanceled();
}
wait(300);
}
myTotalSize += contentLength;
counterUpdated = true;
}
content.getBytes(); // Reads the content bytes and caches them.
}
return true;
}
catch (Throwable e) {
if (counterUpdated) {
synchronized (this) {
myTotalSize -= contentLength; // revert size counter
notifyAll();
}
}
if (e instanceof ProcessCanceledException) throw (ProcessCanceledException)e;
if (e instanceof InterruptedException) throw (InterruptedException)e;
if (e instanceof IOException || e instanceof InvalidVirtualFileAccessException) LOG.info(e);
else LOG.error(e);
return false;
}
}
public FileContent take() {
FileContent result;
synchronized (this) {
@@ -152,7 +152,7 @@ public class VirtualFilePointerImpl extends UserDataHolderBase implements Virtua
myLastUpdated = fsModCount;
if (myFile == null) {
LOG.assertTrue(myUrl != null);
LOG.assertTrue(myUrl != null, "Both file & url are null");
myFile = myVirtualFileManager.findFileByUrl(myUrl);
if (myFile != null) {
myUrl = null;
@@ -1,4 +1,3 @@
error.cannot.show.in.external.browser=Cannot show \"{0}\" in external browser
title.cannot.start.browser=Cannot start browser
error.malformed.url=Malformed url: {0}
error.cannot.start.browser=Cannot start browser: {0}
@@ -20,19 +19,15 @@ checkbox.transparent.native.to.ascii.conversion=Transparent native-to-ascii conv
checkbox.autodetect.utf=Autodetect UTF-encoded files
group.http.proxy=HTTP Proxy
group.web.browser=Web Browser
radio.use.system.default.browser=Use system default browser
radio.use.specified.browser=Use
group.general.options=General Options
editbox.ignore.files.and.folders=Ignore files and folders:
checkbox.confirm.application.exit=Confirm application exit
checkbox.use.cyclic.buffer.in.console=Limit run/debug consoles output to:
label.inactive.timeout.sec= sec.
search.in.the.background=Search in the background
checkbox.save.files.automatically=Save files automatically if application is idle for
checkbox.save.files.on.frame.deactivation=Save files on frame deactivation
checkbox.synchronize.files.on.frame.activation=Synchronize files on frame activation
checkbox.reopen.last.project.on.startup=Reopen last project on startup
label.kb= Kb.
treenode.loading= loading...
action.clear.list=_Clear List
action.descriptor.action=Action: {0}
@@ -59,17 +54,11 @@ button.remove=&Remove
button.remove.all=Remove &All
button.move.up=Move &Up
button.move.down=Move &Down
column.bookmark=Bookmark
column.description=Description
title.project.elements.bookmarks=Project Elements Bookmarks
bookmark.file.X.line.Y={0}, line {1}
button.view.source=&View Source
title.editor.bookmarks=Editor Bookmarks
bookmark.method.at.line={0}, {1}{2}, line {3}
action.show.bookmarks=_Show Bookmarks
action.toggle.bookmark=Toggle _Bookmark
action.toggle.bookmark.mnemonic=Toggle Bookmark With Mnemonic
action.set.bookmark=Set _Bookmark
progress.deleting=Deleting
select.in.commander=Commander
errortree.information=Information:
@@ -255,10 +244,7 @@ label.text.project.has.older.format=<html><body>The project ''{0}'' has an older
Old versions of project files will be saved to: ''{1}''</body></html>
message.text.unlock.read.only.files=<html><body>The following files are read only. IDEA will unlock them.<br>{0}</body></html>
error.message.cannot.make.files.writable=Cannot make the following files writable:\n{0}
label.text.project.was.succesfully.converted.old.version.was.saved.to.0=<html><body>Your project was succesfully converted. \
<br>Old versions of project files were saved to: ''{0}''</body></html>
error.cannot.convert.project=Cannot convert project: {0}
error.some.file.is.corrupted.message=<html><body>File ''{0}'' is corrupted: <br> {1} </body></html>
message.files.doesn.t.exists.0.so.the.corresponding.modules.won.t.be.converted.do.you.want.to.continue=<html><body>The following files doesn''t exists: <br>\
{0}The corresponding modules won''t be converted. Do you want to continue?</body></html>
@@ -273,7 +259,6 @@ message.purchase.or.upgrade=To purchase {0}, refer to {1}.<br>To upgrade from a
message.expiration.date=Expiration date: {0}
message.educational.license=1-Year Educational License. {0}
message.open.source.project.license=Open Source Project License. {0}
message.evaluation.expires=Evaluation expires: {0}
message.non.commercial.use.only=Non-commercial use only
message.personal.license=Personal License
aboutbox.build.number=Build #{0}
@@ -281,7 +266,6 @@ aboutbox.build.date=Built on {0}
aboutbox.jdk=JDK: {0}
aboutbox.vm=VM: {0}
aboutbox.vendor=Vendor: {0}
message.license.you.will.need.upgrade=Your license key will expire on {0}.<br>You will need an upgrade to run {1}.<br>To learn more about upgrades, visit {2}
title.warning=Warning
message.upgrade.from.previous.required={0} requires an upgrade from previous versions.<br>You can purchase a license key from the JetBrains website at<br>{1}
title.upgrade.needed=Upgrade Needed
@@ -305,7 +289,6 @@ title.unable.to.save.data=Unable to Save Data
link.click.here.to.license.server.info=More info
link.purchase.commercial.license=To purchase a commercial license, please visit
license.panel.current.license.description=The license will expire on {0,date,MMMM dd, yyyy}
license.panel.autodescovered.license.server.tile=Default license server
license.panel.buildit.evaluation.expires.in=Remains {0} day(s)
editbox.license.user.name=User name:
editbox.license.license.key=License key:
@@ -314,7 +297,6 @@ radio.license.data=Enter license &data
radio.evaluate=&Evaluate for free for 30 days
radio.default.license.server=&Default License Server
action.activate.tool.window=Activate {0} window
action.change.splitter.orientations=Change Splitter O_rientations
error.checkforupdates.connection.failed=Connection failed. Please check your network connection and try again.
title.connection.error=Connection Error
editbox.export.settings.to=Export settings to:
@@ -336,7 +318,6 @@ action.create.annotation.type=Create @interface
prompt.enter.annotation.type.name=Enter a new @interface name:
title.new.annotation.type=New @interface
title.cannot.create.annotation.type=Cannot Create @interface
progress.creating.annotation.type=Creating @interface {0}.{1}
action.create.new.class=Create New Class
action.create.new.filetype=Create New {0}
action.description.create.new.file=Create New {0}
@@ -363,10 +344,8 @@ progress.creating.package=Creating package {0}.{1}
command.create.directory=Create directory
command.create.package=Create package
action.create.new.enum=Create New Enum
prompt.enter.new.enum.name=Enter a new enum name:
title.new.enum=New Enum
title.cannot.create.enum=Cannot Create Enum
progress.creating.enum=Creating enum {0}.{1}
command.create.enum=Create enum
action.create.new.file=Create New File
prompt.enter.new.file.name=Enter a new file name:
@@ -432,7 +411,6 @@ command.find.previous=Find Previous
command.select.all=Select All
message.no.targets.available=No targets available in this context
title.popup.select.target=Select Target
title.popup.select.subtarget=Select in {0}
title.popup.recent.files=Recent Files
action.split.vertically=Split _Vertically
action.split.horizontally=Split Hori_zontally
@@ -452,8 +430,6 @@ action.toolwindow.hierarchy=Hierarch&y
action.toolwindow.todo=TODO
action.toolwindow.inspection=I&nspection
action.toolwindow.favorites=Favorites
action.unsplit=Un_split
action.unsplit.all=U_nsplit All
macro.classpath.entry=Entry in the classpath the element belongs to
macro.project.classpath=Project's classpath
macro.column.number=Column number
@@ -633,7 +609,6 @@ node.todo.found.items={0} (found {1} {1,choice,1#item|2#items})
node.todo.items={0} ({1} {1, choice, 1#item|2#items})
title.appearance=Appearance
group.window.options= Window Options
checkox.show.buttons.for.disabled.tool.windows=Show buttons for disabled tool windows
checkbox.show.memory.indicator=Show memory indicator
checkbox.show.tool.window.bars=Show tool window bars
checkbox.show.tool.window.numbers=Show tool window numbers
@@ -656,10 +631,6 @@ checkbox.use.antialiased.font.in.editor=Use antialiased font
# this string must start with "IDEA"
idea.default.look.and.feel=IDEA (4.5 default)
error.cannot.set.look.and.feel=Cannot set {0} look and feel
action.add.customization.schema=Add customization scheme
customizations.schema.default=default
action.copy.customization.schema=Copy scheme
action.remove.customization.schema=Remove customization scheme
error.adding.action.without.icon.to.toolbar=You are adding an action without icon to the toolbar. The default icon will be added to this action.
title.unable.to.add.action.without.icon.to.toolbar=Unable to add action without icon to the toolbar
error.please.specify.new.name.for.schema=Please, specify new name for scheme ''{0}''.
@@ -670,13 +641,10 @@ action.choose.actions.to.add=Choose Actions To Add
button.set.icon=&Set icon
label.icon.path=Icon Path:
button.edit.action.icon=Edit Action &Icon
editbox.schema.name=Scheme Name:
editbox.schema.description=Description:
button.add.separator=Add &Separator
button.move.up.u=Move &Up
button.move.down.d=Move &Down
button.add.action.after=Add a&fter...
customization.schema.default.description=Default unmodified customization scheme
title.custom.actions.schemas=Custom Actions Schemes
title.customizations=Menus and Toolbars
label.choosebyname.no.matches.found=(no matches found)
@@ -873,21 +841,12 @@ element.of.interface=of interface
element.of.class=of class
prompt.do.you.want.to.action_verb.the.method.from_class=Do you want to {0} the base {1,choice,1#method|2#methods}?
jar.no.java.modules.in.project.error=There are no Java modules found in the project.\nOnly Java modules can be jarred.
jar.no.java.modules.in.project.title=No Modules To Jar Found
jar.build.progress=Building jar {0}...
jar.build.success.message=Jar has been built in {0}
jar.build.cancelled=Jar creation has been cancelled
jar.build.error.title=Error Creating Jar
jar.build.progress.title=Building Jar
jar.build.processing.file.progress=Processing file {0} ...
error.message.jar.build.cannot.create.temporary.file.in.0=Cannot create temporary file in ''{0}''
jar.build.cannot.overwrite.error=Cannot overwrite file ''{0}''. Copy has been saved to ''{1}''.
jar.build.module.presentable.name=Build Jars for module ''{0}''
jar.build.path=Jar file &path:
jar.build.main.class=Main &class:
jar.build.dialog.title=Build Jars
jar.build.save.title=Save Jar File
jar.build.main.class.title=Choose Main Class
jar.build.class.not.found=Class ''{0}'' not found
help.not.found.error=Help not found for {0}
help.not.found.title=Help Not Found
@@ -918,7 +877,6 @@ updates.check.period.on.startup=On every start
updates.check.period.daily=Daily
updates.check.period.weekly=Weekly
updates.check.period.monthly=Monthly
updates.current.build.unknown=N/A
updates.last.check.never=Never
updates.settings.caption.1=<html>$PRODUCT$ can automatically check for new and updated versions of itself, using your internet connection (when active).<html>
updates.settings.check.now.button=Check Now
@@ -942,14 +900,11 @@ jar.build.on.make=Build jars on &make
jar.build.modules.to.jar=Choose Modules to Jar
jar.build.module.0.jar.settings=Module ''{0}'' Jar Settings
jar.build.include.in.jar.file=Include in jar file:
jar.build.button=&Build
search.textfield.title=&Search:
select.in.scope=Scope
scope.view.title=Scope
select.in.title.project.view=Project View
several.plugins.depend.on.0.continue.to.remove=Several plugins depend on {0}. Continue to remove?
project.view.combo.label=View &as:
child.tag.0.should.be.defined=''{0}'' child tag should be defined
attribute.0.should.be.defined=''{0}'' attribute should be defined
value.must.not.be.empty=Value must not be empty
@@ -1060,7 +1015,6 @@ plugin.deleted.status.tooltip=Plugin will be deleted on next startup
plugin.outdated.version.status.tooltip=Plugin has newer version
plugin.download.status.tooltip=Plugin will be activated on next startup
plugin.is.already.installed.status.tooltip=Plugin is installed
update.plugins.shutdown.action=Update and &Shutdown
update.plugins.update.action=&Update
fail.open.project.message=Unable to open project from ''{0}''
disabled.plugins.warning.message=<li>Plugin <b>\"{0}\"</b> won''t be able to load because required {2, choice, 1#plugin|2#plugins} {1} {2, choice, 1#is|2#are} disabled.</li>
@@ -80,7 +80,7 @@ parameter.name.prompt=Pa&rameter name:
no.class.name.specified=No class name specified
no.parameter.name.specified=No parameter name specified
pass.outer.class.instance.as.parameter=Pass &outer class' instance as a parameter
pull.up.members.to=&Pull up members of {0} to:
pull.up.members.to=P&ull up members of {0} to:
members.to.be.pulled.up=Members to be pulled up
make.abstract=Make abstract
javadoc.for.abstracts=JavaDoc for abstracts
@@ -98,6 +98,8 @@ welcome.script.text.not.specified.message=Not specified
file.chooser.default.title=Select Path
file.chooser.save.dialog.default.title=Select File to Save
file.chooser.save.dialog.confirmation={0} is already exists.\nDo you want to replace it?
file.chooser.save.dialog.confirmation.title=Confirm Save as
file.chooser.select.object.title=Select {0}
delete.dialog.title=Delete
file.chooser.could.not.erase.file.or.folder.error.messabe=Could not erase file or folder: {0}
@@ -289,7 +289,7 @@
implementationClass="com.intellij.codeInsight.hint.XmlImplementationTextSelectioner"/>
<basicWordSelectionFilter implementation="com.intellij.codeInsight.editorActions.XmlBasicWordSelectionFilter"/>
<defaultLiveTemplatesProvider implementation="com.intellij.codeInsight.template.XmlDefaultLiveTemplatesProvider"/>
<customLiveTemplate implementation="com.intellij.codeInsight.template.XmlZenCodingTemplate"/>
<customLiveTemplate implementation="com.intellij.codeInsight.template.zencoding.XmlZenCodingTemplate"/>
<productivityFeaturesProvider implementation="com.intellij.featureStatistics.XmlProductivityFeatureProvider"/>
<idIndexer filetype="XML" implementationClass="com.intellij.psi.impl.cache.impl.idCache.XmlIdIndexer"/>
@@ -942,6 +942,8 @@
<action id="Console.Hibernate.Close"><keyboard-shortcut first-keystroke="control alt shift F4"/></action>
<action id="Console.Hibernate.Terminate"><keyboard-shortcut first-keystroke="control alt shift DELETE"/></action>
<action id="Jdbc.RunSqlScript"><keyboard-shortcut first-keystroke="control shift F10"/></action>
<action id="Console.Python.Execute"><keyboard-shortcut first-keystroke="control ENTER"/></action>
</keymap>
</component>
@@ -0,0 +1,147 @@
/*
* Created by IntelliJ IDEA.
* User: user
* Date: Sep 22, 2002
* Time: 2:45:20 PM
* To change template for new class use
* Code Style | Class Templates options (Tools | IDE Options).
*/
package com.intellij;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.testFramework.LightPlatformTestCase;
import com.intellij.util.ArrayUtil;
import junit.framework.TestSuite;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public abstract class FileSetTestCase extends TestSuite {
private final File[] myFiles;
protected Project myProject;
public FileSetTestCase(String path) {
File f = new File(path);
if (f.isDirectory()) {
myFiles = f.listFiles();
}
else if (f.exists()) {
myFiles = new File[] {f};
}
else {
throw new IllegalArgumentException("invalid path: " + path);
}
addAllTests();
}
protected void setUp() {
}
protected void tearDown() {
}
private void addAllTests() {
for (File file : myFiles) {
if (file.isFile()) {
addFileTest(file);
}
}
}
public abstract String transform(String testName, String[] data) throws Exception;
protected FileSetTestCase(File[] files) {
myFiles = files;
addAllTests();
}
public String getName() {
return getClass().getName();
}
private void addFileTest(File file) {
if (!StringUtil.startsWithChar(file.getName(), '_') && !"CVS".equals(file.getName())) {
final ActualTest t = new ActualTest(file);
addTest(t);
}
}
private class ActualTest extends LightPlatformTestCase {
private final File myTestFile;
public ActualTest(File testFile) {
myTestFile = testFile;
}
protected void setUp() throws Exception {
super.setUp();
FileSetTestCase.this.setUp();
}
protected void tearDown() throws Exception {
FileSetTestCase.this.tearDown();
super.tearDown();
}
public int countTestCases() {
return 1;
}
protected void runTest() throws Throwable {
String content = new String(FileUtil.loadFileText(myTestFile));
assertNotNull(content);
List<String> input = new ArrayList<String>();
int separatorIndex;
content = StringUtil.replace(content, "\r", "");
while ((separatorIndex = content.indexOf("---")) >= 0) {
input.add(content.substring(0, separatorIndex));
content = content.substring(separatorIndex);
while (StringUtil.startsWithChar(content, '-') || StringUtil.startsWithChar(content, '\n')) content = content.substring(1);
}
String result = content;
assertTrue("No data found in source file", input.size() > 0);
while (StringUtil.startsWithChar(result, '-') || StringUtil.startsWithChar(result, '\n') || StringUtil.startsWithChar(result, '\r')) {
result = result.substring(1);
}
final String transformed;
FileSetTestCase.this.myProject = getProject();
String testName = myTestFile.getName();
final int dotIdx = testName.indexOf('.');
if (dotIdx >= 0) {
testName = testName.substring(0, dotIdx);
}
transformed = StringUtil.replace(transform(testName, ArrayUtil.toStringArray(input)), "\r", "");
result = StringUtil.replace(result, "\r", "");
assertEquals(result.trim(),transformed.trim());
}
public String toString() {
return myTestFile.getAbsolutePath() + " ";
}
protected void resetAllFields() {
// Do nothing otherwise myTestFile will be nulled out before getName() is called.
}
public String getName() {
return myTestFile.getAbsolutePath();
}
}
}
@@ -0,0 +1,52 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testFramework;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.intellij.openapi.editor.actionSystem.EditorActionManager;
import com.intellij.openapi.editor.actionSystem.TypedAction;
/**
* User: Maxim.Mossienko
* Date: 15.03.2010
* Time: 21:00:49
*/
public class EditorTestUtil {
public static final char BACKSPACE_FAKE_CHAR = '\uFFFF';
public static final char SMART_ENTER_FAKE_CHAR = '\uFFFE';
public static void performTypingAction(Editor editor, char c) {
EditorActionManager actionManager = EditorActionManager.getInstance();
if (c == BACKSPACE_FAKE_CHAR) {
EditorActionHandler actionHandler = actionManager.getActionHandler(IdeActions.ACTION_EDITOR_BACKSPACE);
actionHandler.execute(editor, DataManager.getInstance().getDataContext());
} else if (c == SMART_ENTER_FAKE_CHAR) {
EditorActionHandler actionHandler = actionManager.getActionHandler(IdeActions.ACTION_EDITOR_COMPLETE_STATEMENT);
actionHandler.execute(editor, DataManager.getInstance().getDataContext());
}
else if (c == '\n') {
EditorActionHandler actionHandler = actionManager.getActionHandler(IdeActions.ACTION_EDITOR_ENTER);
actionHandler.execute(editor, DataManager.getInstance().getDataContext());
}
else {
TypedAction action = actionManager.getTypedAction();
action.actionPerformed(editor, c, DataManager.getInstance().getDataContext());
}
}
}
@@ -49,6 +49,7 @@ public class UsageViewSettings implements PersistentStateComponent<UsageViewSett
public boolean GROUP_BY_MODULE = true;
public boolean GROUP_BY_PACKAGE = true;
public boolean GROUP_BY_FILE_STRUCTURE = true;
public boolean GROUP_BY_SCOPE = false;
public static UsageViewSettings getInstance() {
return ServiceManager.getService(UsageViewSettings.class);
@@ -44,6 +44,9 @@ public class UsageGroupingRuleProviderImpl implements UsageGroupingRuleProvider
public UsageGroupingRule[] getActiveRules(Project project) {
List<UsageGroupingRule> rules = new ArrayList<UsageGroupingRule>();
rules.add(new NonCodeUsageGroupingRule());
if (UsageViewSettings.getInstance().GROUP_BY_SCOPE) {
rules.add(new UsageScopeGroupingRule());
}
if (UsageViewSettings.getInstance().GROUP_BY_USAGE_TYPE) {
rules.add(new UsageTypeGroupingRule());
}
@@ -88,6 +91,7 @@ public class UsageGroupingRuleProviderImpl implements UsageGroupingRuleProvider
}
});
final GroupByScopeAction groupByScopeAction = new GroupByScopeAction(impl);
if(view.getPresentation().isCodeUsages()) {
final GroupByUsageTypeAction groupByUsageTypeAction = new GroupByUsageTypeAction(impl);
groupByUsageTypeAction.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_DOWN_MASK)), component);
@@ -104,15 +108,17 @@ public class UsageGroupingRuleProviderImpl implements UsageGroupingRuleProvider
return new AnAction[] {
groupByUsageTypeAction,
groupByScopeAction,
groupByModuleTypeAction,
groupByPackageAction,
groupByFileStructureAction
groupByFileStructureAction,
};
}
else {
return new AnAction[] {
groupByScopeAction,
groupByModuleTypeAction,
groupByFileStructureAction
groupByFileStructureAction,
};
}
}
@@ -129,6 +135,18 @@ public class UsageGroupingRuleProviderImpl implements UsageGroupingRuleProvider
}
}
private static class GroupByScopeAction extends RuleAction {
private GroupByScopeAction(UsageViewImpl view) {
super(view, "Group by test/production", Icons.TEST_SOURCE_FOLDER);
}
protected boolean getOptionValue() {
return UsageViewSettings.getInstance().GROUP_BY_SCOPE;
}
protected void setOptionValue(boolean value) {
UsageViewSettings.getInstance().GROUP_BY_SCOPE = value;
}
}
private static class GroupByModuleTypeAction extends RuleAction {
private GroupByModuleTypeAction(UsageViewImpl view) {
super(view, UsageViewBundle.message("action.group.by.module"), IconLoader.getIcon("/objectBrowser/showModules.png"));
@@ -0,0 +1,101 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.usages.impl.rules;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiUtilBase;
import com.intellij.usages.Usage;
import com.intellij.usages.UsageGroup;
import com.intellij.usages.UsageView;
import com.intellij.usages.rules.PsiElementUsage;
import com.intellij.usages.rules.UsageGroupingRule;
import com.intellij.util.Icons;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
/**
* @author max
*/
public class UsageScopeGroupingRule implements UsageGroupingRule {
public UsageGroup groupUsage(Usage usage) {
if (!(usage instanceof PsiElementUsage)) {
return null;
}
PsiElementUsage elementUsage = (PsiElementUsage)usage;
PsiElement element = elementUsage.getElement();
VirtualFile virtualFile = PsiUtilBase.getVirtualFile(element);
if (virtualFile == null) {
return null;
}
boolean isInTest = ProjectRootManager.getInstance(element.getProject()).getFileIndex().isInTestSourceContent(virtualFile);
return isInTest ? TEST : PRODUCTION;
}
private static final UsageScopeGroup TEST = new UsageScopeGroup(true);
private static final UsageScopeGroup PRODUCTION = new UsageScopeGroup(false);
private static class UsageScopeGroup implements UsageGroup {
private final boolean isTest;
private UsageScopeGroup(boolean isTest) {
this.isTest = isTest;
}
public void update() {
}
public Icon getIcon(boolean isOpen) {
return isTest ? Icons.TEST_SOURCE_FOLDER : Icons.SOURCE_FOLDERS_ICON;
}
@NotNull
public String getText(UsageView view) {
return isTest ? "Test" : "Production";
}
public FileStatus getFileStatus() {
return null;
}
public boolean isValid() { return true; }
public void navigate(boolean focus) { }
public boolean canNavigate() { return false; }
public boolean canNavigateToSource() {
return false;
}
public int compareTo(UsageGroup usageGroup) {
return getText(null).compareTo(usageGroup.getText(null));
}
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof UsageScopeGroup)) return false;
final UsageScopeGroup usageTypeGroup = (UsageScopeGroup)o;
return isTest == usageTypeGroup.isTest;
}
public int hashCode() {
return isTest ? 0 : 1;
}
}
}
@@ -17,7 +17,7 @@ package com.intellij.usages.impl.rules;
import com.intellij.usageView.UsageViewBundle;
public class UsageType {
public final class UsageType {
public static final UsageType CLASS_INSTANCE_OF = new UsageType(UsageViewBundle.message("usage.type.instanceof"));
public static final UsageType CLASS_IMPORT = new UsageType(UsageViewBundle.message("usage.type.import"));
public static final UsageType CLASS_CAST_TO = new UsageType(UsageViewBundle.message("usage.type.cast.target"));
@@ -72,9 +72,6 @@ public class UsageTypeGroupingRule implements UsageGroupingRule {
return null;
}
private class UsageTypeGroup implements UsageGroup {
private final UsageType myUsageType;
@@ -0,0 +1,89 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Created by IntelliJ IDEA.
* User: yole
* Date: 15.11.2006
* Time: 20:20:15
*/
package com.intellij.openapi.diff.impl.patch;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PatchHunk {
private final int myStartLineBefore;
private final int myEndLineBefore;
private final int myStartLineAfter;
private final int myEndLineAfter;
private final List<PatchLine> myLines = new ArrayList<PatchLine>();
public PatchHunk(final int startLineBefore, final int endLineBefore, final int startLineAfter, final int endLineAfter) {
myStartLineBefore = startLineBefore;
myEndLineBefore = endLineBefore;
myStartLineAfter = startLineAfter;
myEndLineAfter = endLineAfter;
}
public int getStartLineBefore() {
return myStartLineBefore;
}
public int getEndLineBefore() {
return myEndLineBefore;
}
public int getStartLineAfter() {
return myStartLineAfter;
}
public int getEndLineAfter() {
return myEndLineAfter;
}
public void addLine(final PatchLine line) {
myLines.add(line);
}
public List<PatchLine> getLines() {
return Collections.unmodifiableList(myLines);
}
public boolean isNewContent() {
return myStartLineBefore == -1 && myEndLineBefore == -1;
}
public boolean isDeletedContent() {
return myStartLineAfter == -1 && myEndLineAfter == -1;
}
public String getText() {
StringBuilder builder = new StringBuilder();
for(PatchLine line: myLines) {
builder.append(line.getText()).append("\n");
}
return builder.toString();
}
public boolean isNoNewLineAtEnd() {
if (myLines.size() == 0) {
return false;
}
return myLines.get(myLines.size()-1).isSuppressNewLine();
}
}
@@ -17,7 +17,6 @@ package com.intellij.openapi.util.text;
import com.intellij.CommonBundle;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.TextRange;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
@@ -35,6 +34,7 @@ import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
//TeamCity inherits StringUtil: do not add private constructors!!!
public class StringUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.util.text.StringUtil");
@NonNls private static final String VOWELS = "aeiouy";
@@ -488,6 +488,40 @@ public class StringUtil {
return s.substring(1, s.length() - 1);
}
/**
* This is just an optimized version of Matcher.quoteReplacement
*/
public static String quoteReplacement(String s) {
boolean needReplacements = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\\' || c == '$') {
needReplacements = true;
break;
}
}
if (!needReplacements) return s;
StringBuilder sb = new StringBuilder(s.length() * 6 / 5);
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\\') {
sb.append('\\');
sb.append('\\');
}
else if (c == '$') {
sb.append('\\');
sb.append('$');
}
else {
sb.append(c);
}
}
return sb.toString();
}
private static void unescapeStringCharacters(int length, @NotNull String s, @NotNull StringBuilder buffer) {
boolean escaped = false;
for (int idx = 0; idx < length; idx++) {
@@ -42,10 +42,8 @@ import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.regex.Pattern;
@@ -1064,5 +1062,28 @@ public class UIUtil {
return g instanceof PrintGraphics;
}
public static int getSelectedButton(ButtonGroup group) {
Enumeration<AbstractButton> enumeration = group.getElements();
int i = 0;
while (enumeration.hasMoreElements()) {
AbstractButton button = enumeration.nextElement();
if (group.isSelected(button.getModel())) {
return i;
}
i++;
}
return -1;
}
public static void setSelectedButton(ButtonGroup group, int index) {
Enumeration<AbstractButton> enumeration = group.getElements();
int i = 0;
while (enumeration.hasMoreElements()) {
AbstractButton button = enumeration.nextElement();
group.setSelected(button.getModel(), index == i);
i++;
}
}
}
@@ -15,10 +15,6 @@
*/
package com.intellij.openapi.diff.impl.patch;
import com.intellij.openapi.vfs.VirtualFile;
import java.io.IOException;
/**
* @author yole
*/
@@ -31,15 +27,6 @@ public class BinaryFilePatch extends FilePatch {
myAfterContent = afterContent;
}
protected void applyCreate(final VirtualFile newFile) throws IOException, ApplyPatchException {
newFile.setBinaryContent(myAfterContent);
}
protected ApplyPatchStatus applyChange(final VirtualFile fileToPatch) throws IOException, ApplyPatchException {
fileToPatch.setBinaryContent(myAfterContent);
return ApplyPatchStatus.SUCCESS;
}
public boolean isNewFile() {
return myBeforeContent == null;
}
@@ -47,4 +34,8 @@ public class BinaryFilePatch extends FilePatch {
public boolean isDeletedFile() {
return myAfterContent == null;
}
public byte[] getAfterContent() {
return myAfterContent;
}
}
@@ -0,0 +1,83 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Created by IntelliJ IDEA.
* User: yole
* Date: 15.11.2006
* Time: 17:53:24
*/
package com.intellij.openapi.diff.impl.patch;
import com.intellij.openapi.util.text.StringUtil;
public abstract class FilePatch {
private String myBeforeName;
private String myAfterName;
private String myBeforeVersionId;
private String myAfterVersionId;
public String getBeforeName() {
return myBeforeName;
}
public String getAfterName() {
return myAfterName;
}
public String getBeforeFileName() {
String[] pathNameComponents = myBeforeName.split("/");
return pathNameComponents [pathNameComponents.length-1];
}
public String getAfterFileName() {
String[] pathNameComponents = myAfterName.split("/");
return pathNameComponents [pathNameComponents.length-1];
}
public void setBeforeName(final String fileName) {
myBeforeName = fileName;
}
public void setAfterName(final String fileName) {
myAfterName = fileName;
}
public String getBeforeVersionId() {
return myBeforeVersionId;
}
public void setBeforeVersionId(final String beforeVersionId) {
myBeforeVersionId = beforeVersionId;
}
public String getAfterVersionId() {
return myAfterVersionId;
}
public void setAfterVersionId(final String afterVersionId) {
myAfterVersionId = afterVersionId;
}
public String getAfterNameRelative(int skipDirs) {
String[] components = myAfterName.split("/");
return StringUtil.join(components, skipDirs, components.length, "/");
}
public abstract boolean isNewFile();
public abstract boolean isDeletedFile();
}
@@ -22,17 +22,14 @@
*/
package com.intellij.openapi.diff.impl.patch;
import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
import com.intellij.openapi.util.text.LineTokenizer;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.List;
import java.util.ArrayList;
public class PatchReader {
@NonNls public static final String NO_NEWLINE_SIGNATURE = "\\ No newline at end of file";
@@ -48,12 +45,6 @@ public class PatchReader {
@NonNls private static final Pattern ourContextBeforeHunkStartPattern = Pattern.compile("\\*\\*\\* (\\d+),(\\d+) \\*\\*\\*\\*");
@NonNls private static final Pattern ourContextAfterHunkStartPattern = Pattern.compile("--- (\\d+),(\\d+) ----");
public PatchReader(VirtualFile virtualFile) throws IOException {
byte[] patchContents = virtualFile.contentsToByteArray();
CharSequence patchText = LoadTextUtil.getTextByBinaryPresentation(patchContents, virtualFile);
myLines = LineTokenizer.tokenize(patchText, false);
}
public PatchReader(CharSequence patchContent) {
myLines = LineTokenizer.tokenize(patchContent, false);
}
@@ -0,0 +1,63 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.diff.impl.patch;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author yole
*/
public class TextFilePatch extends FilePatch {
private final List<PatchHunk> myHunks;
public void addHunk(final PatchHunk hunk) {
myHunks.add(hunk);
}
public List<PatchHunk> getHunks() {
return Collections.unmodifiableList(myHunks);
}
public TextFilePatch() {
myHunks = new ArrayList<PatchHunk>();
}
private TextFilePatch(final TextFilePatch patch) {
setBeforeVersionId(patch.getBeforeVersionId());
setAfterVersionId(patch.getAfterVersionId());
setBeforeName(patch.getBeforeName());
setAfterName(patch.getAfterName());
myHunks = patch.myHunks;
}
public TextFilePatch pathsOnlyCopy() {
return new TextFilePatch(this);
}
public boolean isNewFile() {
return myHunks.size() == 1 && myHunks.get(0).isNewContent();
}
public String getNewFileText() {
return myHunks.get(0).getText();
}
public boolean isDeletedFile() {
return myHunks.size() == 1 && myHunks.get(0).isDeletedContent();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,11 +44,11 @@ import java.util.List;
/**
* @author yole
*/
public class PatchBuilder {
public class TextPatchBuilder {
private static final int CONTEXT_LINES = 3;
@NonNls private static final String REVISION_NAME_TEMPLATE = "(revision {0})";
private PatchBuilder() {
private TextPatchBuilder() {
}
private static void checkCanceled(final ProgressIndicator ind) {
@@ -57,8 +57,7 @@ public class PatchBuilder {
}
}
public static List<FilePatch> buildPatch(final Collection<Change> changes, final String basePath, final boolean allowRename,
final boolean reversePatch) throws VcsException {
public static List<FilePatch> buildPatch(final Collection<Change> changes, final String basePath, final boolean reversePatch) throws VcsException {
final ProgressIndicator ind = ProgressManager.getInstance().getProgressIndicator();
List<FilePatch> result = new ArrayList<FilePatch>();

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