<component name="libraryTable">
<library name="Netty">
<CLASSES>
- <root url="jar://$PROJECT_DIR$/lib/netty-all-5.0.0.Alpha1.jar!/" />
+ <root url="jar://$PROJECT_DIR$/lib/netty-all-5.0.0.Alpha2.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
- <root url="jar://$PROJECT_DIR$/lib/src/netty-all-5.0.0.Alpha1-sources.jar!/" />
+ <root url="jar://$PROJECT_DIR$/lib/src/netty-all-5.0.0.Alpha2-sources.jar!/" />
</SOURCES>
</library>
</component>
\ No newline at end of file
}
FileUtil.createIfDoesntExist(CompilerPaths.getRebuildMarkerFile(project));
--myWatchedProjectsCount;
+ if (ourDebugMode) {
+ System.out.println("After suspend for project:"+projectId + "," + myWatchedProjectsCount);
+ }
// cleanup internal structures to free memory
mySourcesToRecompile.remove(projectId);
myOutputsToDelete.remove(projectId);
public void watchProject(Project project) {
synchronized (myDataLock) {
- mySuspendedProjects.remove(getProjectId(project));
+ int projectId = getProjectId(project);
+ mySuspendedProjects.remove(projectId);
++myWatchedProjectsCount;
+ if (ourDebugMode) {
+ System.out.println("After watch for project:"+projectId + "," + myWatchedProjectsCount);
+ }
}
}
}
private static Trinity<String, String, FileType> parseExternalForm(String s) {
- // when serialized into a tag special symbols are now kept as is
- // so our separator \r may be converted to \n or \r\n
- s = StringUtil.convertLineSeparators(s);
- String[] split = s.split("\n");
+ String[] split = s.split(String.valueOf(DebuggerEditorImpl.SEPARATOR));
return Trinity.create(split[0], split.length > 1 ? split[1] : "", split.length > 2 ? FileTypeManager.getInstance().getStdFileType(split[2]) : null);
}
breakpoint.updateUI();
RequestManagerImpl.createRequests(breakpoint);
myDispatcher.getMulticaster().breakpointsChanged();
+ if (breakpoint instanceof MethodBreakpoint || breakpoint instanceof WildcardMethodBreakpoint) {
+ XDebugSessionImpl.NOTIFICATION_GROUP.createNotification("Method breakpoints may dramatically slow down debugging", MessageType.WARNING).notify(myProject);
+ }
}
private synchronized void onBreakpointAdded(XBreakpoint xBreakpoint) {
private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
public void fireBreakpointChanged(Breakpoint breakpoint) {
breakpoint.reload();
+ breakpoint.updateUI();
RequestManagerImpl.updateRequests(breakpoint);
if (myAllowMulticasting) {
// can be invoked from non-AWT thread
if (myVisible) {
if (isValid()) {
final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(myProject).getBreakpointManager();
- breakpointManager.updateBreakpointPresentation((XLineBreakpoint)myXBreakpoint, getIcon(), getDescription());
+ breakpointManager.updateBreakpointPresentation((XLineBreakpoint)myXBreakpoint, getIcon(), null);
}
//RangeHighlighter highlighter = myHighlighter;
//if (highlighter != null && highlighter.isValid() && isValid()) {
@Override
public String getShortText(XLineBreakpoint<JavaFieldBreakpointProperties> breakpoint) {
- return getDisplayText(breakpoint);
+ return getText(breakpoint);
}
- @Override
- public String getDisplayText(XLineBreakpoint<JavaFieldBreakpointProperties> breakpoint) {
+ public String getText(XLineBreakpoint<JavaFieldBreakpointProperties> breakpoint) {
//if(!isValid()) {
// return DebuggerBundle.message("status.breakpoint.invalid");
//}
*/
package com.intellij.debugger.ui.breakpoints;
+import com.intellij.debugger.DebuggerManagerEx;
import com.intellij.debugger.engine.DebuggerUtils;
+import com.intellij.debugger.ui.JavaDebuggerSupport;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.FileType;
return new JavaDebuggerEditorsProvider();
}
+ @Override
+ public String getDisplayText(XLineBreakpoint<P> breakpoint) {
+ BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(JavaDebuggerSupport.getCurrentProject()).getBreakpointManager();
+ BreakpointWithHighlighter javaBreakpoint = (BreakpointWithHighlighter)breakpointManager.findBreakpoint(breakpoint);
+ if (javaBreakpoint != null) {
+ return javaBreakpoint.getDescription();
+ }
+ else {
+ return super.getDisplayText(breakpoint);
+ }
+ }
+
@Override
public final boolean canPutAt(@NotNull VirtualFile file, final int line, @NotNull Project project) {
PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
@Override
public String getShortText(XLineBreakpoint<JavaMethodBreakpointProperties> breakpoint) {
- return getDisplayText(breakpoint);
- }
-
- @Override
- public String getDisplayText(XLineBreakpoint<JavaMethodBreakpointProperties> breakpoint) {
return getText(breakpoint);
}
myHolder.add(GenericsHighlightUtil.checkParametersAllowed(list, myLanguageLevel,myFile));
if (!myHolder.hasErrorResults()) myHolder.add(GenericsHighlightUtil.checkParametersOnRaw(list));
if (!myHolder.hasErrorResults()) {
- for (PsiType type : list.getTypeArguments()) {
- myHolder.add(HighlightUtil.checkDiamondFeature(type, list, myLanguageLevel,myFile));
+ for (PsiTypeElement typeElement : list.getTypeParameterElements()) {
+ myHolder.add(HighlightUtil.checkDiamondFeature(typeElement.getType(), list, myLanguageLevel,myFile));
}
}
}
/*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-/**
- * Created by IntelliJ IDEA.
- * User: cdr
- * Date: Nov 13, 2002
- * Time: 3:26:50 PM
- * To change this template use Options | File Templates.
- */
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.FileModificationService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
+import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.impl.source.resolve.DefaultParameterTypeInferencePolicy;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.TypeConversionUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
+import static com.intellij.util.ObjectUtils.assertNotNull;
+
+/**
+ * @author cdr
+ * @since Nov 13, 2002
+ */
public class ChangeTypeArgumentsFix implements IntentionAction, HighPriorityAction {
+ private static final Logger LOG = Logger.getInstance("#" + ChangeTypeArgumentsFix.class.getName());
+
private final PsiMethod myTargetMethod;
private final PsiClass myPsiClass;
private final PsiExpression[] myExpressions;
- private static final Logger LOG = Logger.getInstance("#" + ChangeTypeArgumentsFix.class.getName());
private final PsiNewExpression myNewExpression;
ChangeTypeArgumentsFix(@NotNull PsiMethod targetMethod,
LOG.assertTrue(reference != null, myNewExpression);
final PsiReferenceParameterList parameterList = reference.getParameterList();
LOG.assertTrue(parameterList != null, myNewExpression);
+ PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
PsiTypeElement[] elements = parameterList.getTypeParameterElements();
for (int i = elements.length - 1; i >= 0; i--) {
- PsiTypeElement typeElement = elements[i];
- final PsiType typeArg = psiSubstitutor.substitute(typeParameters[i]);
- typeElement.replace(JavaPsiFacade.getElementFactory(project).createTypeElement(typeArg));
+ PsiType typeArg = assertNotNull(psiSubstitutor.substitute(typeParameters[i]));
+ PsiElement replaced = elements[i].replace(factory.createTypeElement(typeArg));
+ JavaCodeStyleManager.getInstance(file.getProject()).shortenClassReferences(replaced);
}
}
}
@Nullable
- public static PsiModifierListOwner getContainer(final PsiElement element) {
- PsiModifierListOwner listOwner = PsiTreeUtil.getParentOfType(element, PsiParameter.class, false);
- if (listOwner == null) {
- final PsiIdentifier psiIdentifier = PsiTreeUtil.getParentOfType(element, PsiIdentifier.class, false);
- if (psiIdentifier != null && psiIdentifier.getParent() instanceof PsiModifierListOwner) {
- listOwner = (PsiModifierListOwner)psiIdentifier.getParent();
+ public static PsiModifierListOwner getContainer(final PsiFile file, int offset) {
+ PsiReference reference = file.findReferenceAt(offset);
+ if (reference != null) {
+ PsiElement target = reference.resolve();
+ if (target instanceof PsiMember) {
+ return (PsiMember)target;
}
}
- return listOwner;
+
+ PsiElement element = file.findElementAt(offset);
+
+ PsiModifierListOwner listOwner = PsiTreeUtil.getParentOfType(element, PsiParameter.class, false);
+ if (listOwner != null) return listOwner;
+
+ final PsiIdentifier psiIdentifier = PsiTreeUtil.getParentOfType(element, PsiIdentifier.class, false);
+ if (psiIdentifier != null && psiIdentifier.getParent() instanceof PsiModifierListOwner) {
+ return (PsiModifierListOwner)psiIdentifier.getParent();
+ }
+ return null;
}
@Override
if (!super.isAvailable(project, file, startElement, endElement)) {
return false;
}
- PsiModifierListOwner owner = getContainer(startElement);
+ PsiModifierListOwner owner = getContainer(file, startElement.getTextRange().getStartOffset());
if (owner == null || AnnotationUtil.isAnnotated(owner, getAnnotationsToRemove()[0], false, false)) {
return false;
}
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
PsiDocumentManager.getInstance(project).commitAllDocuments();
PsiElement element = findElement(file, offset);
- PsiTryStatement tryStatement = (PsiTryStatement) element.getParent();
+ if (element == null) return;
+
+ PsiTryStatement tryStatement = (PsiTryStatement)element.getParent();
List<PsiClassType> unhandledExceptions = new ArrayList<PsiClassType>(ExceptionUtil.collectUnhandledExceptions(element, null));
ExceptionUtil.sortExceptionsByHierarchy(unhandledExceptions);
}
}
- private static PsiCodeBlock addCatchStatement(PsiTryStatement tryStatement, PsiClassType exceptionType, PsiFile file) throws IncorrectOperationException {
+ private static PsiCodeBlock addCatchStatement(PsiTryStatement tryStatement,
+ PsiClassType exceptionType,
+ PsiFile file) throws IncorrectOperationException {
PsiElementFactory factory = JavaPsiFacade.getInstance(tryStatement.getProject()).getElementFactory();
if (tryStatement.getTryBlock() == null) {
}
PsiParameter[] parameters = tryStatement.getCatchBlockParameters();
- parameters[parameters.length - 1].getTypeElement().replace(factory.createTypeElement(exceptionType));
- PsiCodeBlock[] catchBlocks = tryStatement.getCatchBlocks();
+ PsiTypeElement typeElement = parameters[parameters.length - 1].getTypeElement();
+ if (typeElement != null) {
+ JavaCodeStyleManager.getInstance(file.getProject()).shortenClassReferences(typeElement);
+ }
+ PsiCodeBlock[] catchBlocks = tryStatement.getCatchBlocks();
return catchBlocks[catchBlocks.length - 1];
}
//do not show methods from default package
&& !((PsiJavaFile)file).getPackageName().isEmpty()
&& PsiUtil.isAccessible(file.getProject(), method, element, containingClass)) {
- if (method.isDeprecated()) {
+ if (isEffectivelyDeprecated(method)) {
deprecated.put(containingClass, method);
return processCondition();
}
return processCondition();
}
+ private boolean isEffectivelyDeprecated(PsiMethod method) {
+ if (method.isDeprecated()) {
+ return true;
+ }
+ PsiClass aClass = method.getContainingClass();
+ while (aClass != null) {
+ if (aClass.isDeprecated()) {
+ return true;
+ }
+ aClass = aClass.getContainingClass();
+ }
+ return false;
+ }
+
private boolean processCondition() {
return (applicableList.isEmpty() ? list : applicableList).size() + deprecated.size() < 50;
}
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.intention.AddAnnotationFix;
import com.intellij.codeInsight.intention.AddAnnotationPsiFix;
-import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
-import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
// include not in project files
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
- CaretModel caretModel = editor.getCaretModel();
- int position = caretModel.getOffset();
- PsiElement element = file.findElementAt(position);
- return element != null && isAvailable(project, element);
- }
-
- public boolean isAvailable(@NotNull final Project project, @NotNull final PsiElement element) {
- if (!element.isValid()) return false;
- final PsiModifierListOwner owner;
- if (!element.getManager().isInProject(element) || CodeStyleSettingsManager.getSettings(project).USE_EXTERNAL_ANNOTATIONS) {
- owner = AddAnnotationPsiFix.getContainer(element);
- }
- else {
+ final PsiModifierListOwner owner = AddAnnotationPsiFix.getContainer(file, editor.getCaretModel().getOffset());
+ if (owner == null ||
+ owner.getManager().isInProject(owner) && !CodeStyleSettingsManager.getSettings(project).USE_EXTERNAL_ANNOTATIONS) {
return false;
}
- if (owner == null) return false;
Pair<String, String[]> annotations = getAnnotations(project);
String toAdd = annotations.first;
String[] toRemove = annotations.second;
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
- CaretModel caretModel = editor.getCaretModel();
- int position = caretModel.getOffset();
- PsiElement element = file.findElementAt(position);
-
- PsiModifierListOwner owner = AddAnnotationPsiFix.getContainer(element);
+ PsiModifierListOwner owner = AddAnnotationPsiFix.getContainer(file, editor.getCaretModel().getOffset());
if (owner == null || !owner.isValid()) return;
Pair<String, String[]> annotations = getAnnotations(project);
String toAdd = annotations.first;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
-import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
@Nullable
private static PsiMethod getTargetMethod(@NotNull Project project, Editor editor, PsiFile file) {
- PsiElement element = file.findElementAt(editor.getCaretModel().getOffset());
- if (element == null) return null;
- if (!element.getManager().isInProject(element) || CodeStyleSettingsManager.getSettings(project).USE_EXTERNAL_ANNOTATIONS) {
- final PsiModifierListOwner owner = AddAnnotationPsiFix.getContainer(element);
- if (owner instanceof PsiMethod) {
- PsiElement original = owner.getOriginalElement();
- if (original instanceof PsiMethod) {
- return (PsiMethod)original;
- }
- return (PsiMethod)owner;
- }
+ final PsiModifierListOwner owner = AddAnnotationPsiFix.getContainer(file, editor.getCaretModel().getOffset());
+ if (owner instanceof PsiMethod &&
+ (!owner.getManager().isInProject(owner) || CodeStyleSettingsManager.getSettings(project).USE_EXTERNAL_ANNOTATIONS)) {
+ PsiElement original = owner.getOriginalElement();
+ return original instanceof PsiMethod ? (PsiMethod)original : (PsiMethod)owner;
}
return null;
}
-
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
final PsiMethod method = getTargetMethod(project, editor, file);
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.*;
+import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiUtil;
ChangeSignatureUtil.synchronizeList(myClass.getTypeParameterList(), newTypeParameters, TypeParameterList.INSTANCE, toRemoveParms);
}
- private boolean[] detectRemovedParameters(final PsiTypeParameter[] originaltypeParameters) {
- final boolean[] toRemoveParms = new boolean[originaltypeParameters.length];
- Arrays.fill(toRemoveParms, true);
+ private boolean[] detectRemovedParameters(final PsiTypeParameter[] original) {
+ final boolean[] toRemove = new boolean[original.length];
+ Arrays.fill(toRemove, true);
for (final TypeParameterInfo info : myNewSignature) {
int oldParameterIndex = info.getOldParameterIndex();
if (oldParameterIndex >= 0) {
- toRemoveParms[oldParameterIndex] = false;
+ toRemove[oldParameterIndex] = false;
}
}
- return toRemoveParms;
+ return toRemove;
}
- private void processUsage(final UsageInfo usage, final PsiTypeParameter[] originalTypeParameters, final boolean[] toRemoveParms)
- throws IncorrectOperationException {
+ private void processUsage(UsageInfo usage, PsiTypeParameter[] original, boolean[] toRemove) throws IncorrectOperationException {
PsiElementFactory factory = JavaPsiFacade.getInstance(myClass.getProject()).getElementFactory();
PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement)usage.getElement();
+ assert referenceElement != null : usage;
PsiSubstitutor usageSubstitutor = determineUsageSubstitutor(referenceElement);
PsiReferenceParameterList referenceParameterList = referenceElement.getParameterList();
+ assert referenceParameterList != null : referenceElement;
PsiTypeElement[] oldValues = referenceParameterList.getTypeParameterElements();
- if (oldValues.length != originalTypeParameters.length) return;
+ if (oldValues.length != original.length) return;
List<PsiTypeElement> newValues = new ArrayList<PsiTypeElement>();
for (final TypeParameterInfo info : myNewSignature) {
int oldIndex = info.getOldParameterIndex();
newValues.add(newValue);
}
}
- ChangeSignatureUtil.synchronizeList(referenceParameterList, newValues, ReferenceParameterList.INSTANCE, toRemoveParms);
+
+ ChangeSignatureUtil.synchronizeList(referenceParameterList, newValues, ReferenceParameterList.INSTANCE, toRemove);
+ JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(referenceParameterList);
}
private PsiSubstitutor determineUsageSubstitutor(PsiJavaCodeReferenceElement referenceElement) {
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.*;
+import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
new InlineToAnonymousConstructorProcessor(myClass, psiNewExpression, superType).run();
}
else {
- PsiJavaCodeReferenceElement element =
- JavaPsiFacade.getInstance(myClass.getProject()).getElementFactory().createClassReferenceElement(superType.resolve());
- psiNewExpression.getClassReference().replace(element);
+ PsiClass target = superType.resolve();
+ assert target != null : superType;
+ PsiElementFactory factory = JavaPsiFacade.getInstance(myClass.getProject()).getElementFactory();
+ PsiJavaCodeReferenceElement element = factory.createClassReferenceElement(target);
+ PsiJavaCodeReferenceElement reference = psiNewExpression.getClassReference();
+ assert reference != null : psiNewExpression;
+ reference.replace(element);
}
}
catch (IncorrectOperationException e) {
PsiType substType = classResolveResult.getSubstitutor().substitute(superType);
assert classResolveResult.getElement() == myClass;
try {
- typeElement.replace(factory.createTypeElement(substType));
+ PsiElement replaced = typeElement.replace(factory.createTypeElement(substType));
+ JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(replaced);
}
catch(IncorrectOperationException e) {
LOG.error(e);
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-/*
- * User: anna
- * Date: 27-Aug-2008
- */
package com.intellij.refactoring.inlineSuperClass.usageInfo;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
+import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.refactoring.util.FixableUsageInfo;
import com.intellij.util.Function;
import com.intellij.util.IncorrectOperationException;
+/**
+ * @author anna
+ * @since 27-Aug-2008
+ */
public class ReplaceWithSubtypeUsageInfo extends FixableUsageInfo {
public static final Logger LOG = Logger.getInstance("#" + ReplaceWithSubtypeUsageInfo.class.getName());
private final PsiTypeElement myTypeElement;
public void fixUsage() throws IncorrectOperationException {
if (myTypeElement.isValid()) {
- final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myTypeElement.getProject()).getElementFactory();
- myTypeElement.replace(elementFactory.createTypeElement(myTargetClassType));
+ Project project = myTypeElement.getProject();
+ PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
+ PsiElement replaced = myTypeElement.replace(elementFactory.createTypeElement(myTargetClassType));
+ JavaCodeStyleManager.getInstance(project).shortenClassReferences(replaced);
}
}
else if (type instanceof PsiArrayType) {
return checkNotAssignable(bound, type, true);
}
+ else if (type instanceof PsiIntersectionType) {
+ for (PsiType psiType : ((PsiIntersectionType)type).getConjuncts()) {
+ if (!checkNotInBounds(psiType, bound, uncheckedConversionByDefault)) {
+ return false;
+ }
+ }
+ return true;
+ }
return false;
}
for (PsiType existing : array) {
if (type != existing) {
final boolean allowUncheckedConversion = type instanceof PsiClassType && ((PsiClassType)type).isRaw();
- if (TypeConversionUtil.isAssignable(type, existing, allowUncheckedConversion)) {
+ if (TypeConversionUtil.isAssignable(GenericsUtil.eliminateWildcards(type),
+ GenericsUtil.eliminateWildcards(existing), allowUncheckedConversion)) {
iterator.remove();
break;
}
return PsiUtil.captureToplevelWildcards(type, expression);
}
+ final PsiElement parent = toplevel.getParent();
+ if (parent instanceof PsiExpressionList &&
+ PsiUtil.isLanguageLevel8OrHigher(parent) &&
+ parent.getParent() instanceof PsiCallExpression) {
+ return PsiUtil.captureToplevelWildcards(type, expression);
+ }
+
final PsiType normalized = doNormalizeWildcardByPosition(type, expression, toplevel);
LOG.assertTrue(normalized.isValid(), type);
if (normalized instanceof PsiClassType && !PsiUtil.isAccessedForWriting(toplevel)) {
import com.intellij.openapi.util.AtomicNotNullLazyValue;
import com.intellij.openapi.util.NotNullLazyValue;
-import com.intellij.openapi.util.NullableLazyValue;
-import com.intellij.openapi.util.VolatileNullableLazyValue;
+import com.intellij.openapi.util.Ref;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.PsiJavaParserFacadeImpl;
import com.intellij.psi.impl.source.tree.TreeElement;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
public class ClsTypeElementImpl extends ClsElementImpl implements PsiTypeElement {
@NonNls static final char VARIANCE_NONE = '\0';
private final PsiElement myParent;
private final String myTypeText;
private final char myVariance;
- private final NullableLazyValue<ClsElementImpl> myChild;
+ private final NotNullLazyValue<Ref<ClsElementImpl>> myChild;
private final NotNullLazyValue<PsiType> myCachedType;
public ClsTypeElementImpl(@NotNull PsiElement parent, @NotNull String typeText, char variance) {
myParent = parent;
myTypeText = TypeInfo.internFrequentType(typeText);
myVariance = variance;
- myChild = new VolatileNullableLazyValue<ClsElementImpl>() {
- @Nullable
+ myChild = new AtomicNotNullLazyValue<Ref<ClsElementImpl>>() {
+ @NotNull
@Override
- protected ClsElementImpl compute() {
- return calculateChild();
+ protected Ref<ClsElementImpl> compute() {
+ return Ref.create(calculateChild());
}
};
myCachedType = new AtomicNotNullLazyValue<PsiType>() {
@Override
@NotNull
public PsiElement[] getChildren() {
- ClsElementImpl child = myChild.getValue();
+ ClsElementImpl child = myChild.getValue().get();
return child != null ? new PsiElement[]{child} : PsiElement.EMPTY_ARRAY;
}
public void setMirror(@NotNull TreeElement element) throws InvalidMirrorException {
setMirrorCheckingType(element, JavaElementType.TYPE);
- ClsElementImpl child = myChild.getValue();
+ ClsElementImpl child = myChild.getValue().get();
if (child != null) {
child.setMirror(element.getFirstChildNode());
}
PsiType result = PsiJavaParserFacadeImpl.getPrimitiveType(myTypeText);
if (result != null) return result;
- ClsElementImpl childElement = myChild.getValue();
+ ClsElementImpl childElement = myChild.getValue().get();
if (childElement instanceof ClsTypeElementImpl) {
if (isArray()) {
switch (myVariance) {
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.graphInference.constraints.TypeEqualityConstraint;
-import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Nullable;
return null;
}
- if (!TypeConversionUtil.containsWildcards(parameterization)) {
+ if (!TypeConversionUtil.containsWildcards(parameterization) && psiClassType.isAssignableFrom(parameterization)) {
return parameterization;
}
- if (!psiClassType.isAssignableFrom(parameterization)) {
- return null;
- }
-
return getNonWildcardParameterization((PsiClassType)psiClassType);
}
return null;
for (int i = 0; i < parameters.length; i++) {
PsiType paramType = parameters[i];
if (paramType instanceof PsiWildcardType) {
- final PsiClassType[] extendsListTypes = typeParameters[i].getExtendsListTypes();
- final PsiClassType Bi = extendsListTypes.length > 0 ? extendsListTypes[0]
- : PsiType.getJavaLangObject(psiClass.getManager(),
- GlobalSearchScope.allScope(psiClass.getProject()));
- if (PsiPolyExpressionUtil.mentionsTypeParameters(Bi, typeParametersSet)) {
- return null;
+ final PsiType bound = GenericsUtil.eliminateWildcards(((PsiWildcardType)paramType).getBound(), false);
+ if (((PsiWildcardType)paramType).isSuper()) {
+ newParameters[i] = bound;
}
-
- final PsiType bound = ((PsiWildcardType)paramType).getBound();
- if (bound == null) {
- newParameters[i] = Bi;
- } else if (((PsiWildcardType)paramType).isExtends()){
- newParameters[i] = GenericsUtil.getGreatestLowerBound(Bi, GenericsUtil.eliminateWildcards(bound, false));
- } else {
- newParameters[i] = GenericsUtil.eliminateWildcards(bound, false);
+ else {
+ newParameters[i] = bound != null ? bound : PsiType.getJavaLangObject(psiClass.getManager(), psiClassType.getResolveScope());
+ for (PsiClassType paramBound : typeParameters[i].getExtendsListTypes()) {
+ if (!PsiPolyExpressionUtil.mentionsTypeParameters(paramBound, typeParametersSet)) {
+ newParameters[i] = GenericsUtil.getGreatestLowerBound(paramBound, newParameters[i]);
+ }
+ }
}
} else {
newParameters[i] = paramType;
}
}
- return JavaPsiFacade.getElementFactory(psiClass.getProject()).createType(psiClass, newParameters);
+
+ if (!isWellFormed(psiClass, typeParameters, newParameters)) {
+ return null;
+ }
+
+ final PsiClassType parameterization = JavaPsiFacade.getElementFactory(psiClass.getProject()).createType(psiClass, newParameters);
+ if (!psiClassType.isAssignableFrom(parameterization)) {
+ return null;
+ }
+ return parameterization;
}
return null;
}
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.*;
-import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.source.resolve.graphInference.constraints.*;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.search.GlobalSearchScope;
}
return sameMethodCall;
}
-
- public void addCapturedVariable(PsiTypeParameter param) {
- initBounds(param);
- }
private void initReturnTypeConstraint(PsiMethod method, final PsiCallExpression context) {
if (PsiPolyExpressionUtil.isMethodCallPolyExpression(context, method)) {
PsiType returnType = method.getReturnType();
if (!PsiType.VOID.equals(returnType) && returnType != null) {
- returnType = PsiImplUtil.normalizeWildcardTypeByPosition(returnType, context);
PsiType targetType = PsiTypesUtil.getExpectedTypeByParent(context);
if (targetType == null) {
targetType = getTargetType(context);
final PsiParameter[] parameters = method.getParameterList().getParameters();
callSession.initExpressionConstraints(parameters, args, myExpression, method);
}
- callSession.registerConstraints(returnType, myT);
+ final boolean accepted = callSession.repeatInferencePhases(true);
+ if (!accepted) {
+ //todo return false;
+ }
+ callSession.registerConstraints(returnType, substitutor.substitute(returnType));
if (callSession.repeatInferencePhases(true)) {
final Collection<InferenceVariable> inferenceVariables = callSession.getInferenceVariables();
if (sameMethodCall) {
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.CharTable;
import com.intellij.util.IncorrectOperationException;
-import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
return type;
}
+ // collects annotations bound to C-style arrays
private static List<PsiAnnotation[]> collectAnnotations(PsiElement anchor, PsiAnnotation stopAt) {
- List<PsiAnnotation[]> annotations = new SmartList<PsiAnnotation[]>();
+ List<PsiAnnotation[]> annotations = ContainerUtil.newSmartList();
List<PsiAnnotation> current = null;
- boolean stop = false;
+ boolean found = (stopAt == null), stop = false;
for (PsiElement child = anchor.getNextSibling(); child != null; child = child.getNextSibling()) {
if (child instanceof PsiComment || child instanceof PsiWhiteSpace) continue;
if (child instanceof PsiAnnotation) {
- if (current == null) current = new SmartList<PsiAnnotation>();
+ if (current == null) current = ContainerUtil.newSmartList();
current.add((PsiAnnotation)child);
- if (child == stopAt) stop = true;
+ if (child == stopAt) found = stop = true;
continue;
}
}
}
- // stop == true means annotation is misplaced
- return stop ? null : annotations;
+ // annotation is misplaced (either located before the anchor or has no following brackets)
+ return !found || stop ? null : annotations;
}
public static void normalizeBrackets(@NotNull PsiVariable variable) {
for (String s : args) { System.out.println(s); }
List<String> list =
- new ArrayList<>();
+ new ArrayList<error descr="Diamond types are not supported at this language level"><></error>();
for (String s : list) {}
Arrays.asList("");
int @TA [] a @TA [] <error descr="Annotations are not allowed here">@TA</error> = (p != null ? p : mixedArrays);
return a;
}
+ void <error descr="Annotations are not allowed here">@TA</error> misplaced() { }
@TA Outer() { }
}
void bar(List<? extends S1> k) {
- f<error descr="'f(java.util.List<capture<? extends S1>>, capture<? extends S1>)' in 'S1' cannot be applied to '(java.util.List<capture<? extends S1>>, S1)'">(k, k.get(0))</error>;
+ f<error descr="'f(java.util.List<capture<? extends S1>>, capture<? extends S1>)' in 'S1' cannot be applied to '(java.util.List<capture<? extends S1>>, capture<? extends S1>)'">(k, k.get(0))</error>;
}
}
--- /dev/null
+class Test {
+
+ class Foo<K> {}
+
+ void test(Foo<? extends String> p) {
+ foo(bar(p)) ;
+ }
+
+ <T> T bar(Foo<T> p) {
+ return null;
+ }
+
+ <K> K foo(K p) {
+ return null;
+ }
+}
--- /dev/null
+import java.util.function.Function;
+
+class Test {
+
+ <U, V> void foo(Function<U, ? extends V> m) {}
+
+ {
+ foo((String e) -> e.length());
+ }
+}
--- /dev/null
+import java.util.List;
+
+class SimpleDependency {
+
+ interface I<R extends U, U> {
+ R m();
+ }
+
+ {
+ I<? extends String, ? extends String> k = () -> null;
+ I<? extends String, String> k1 = () -> null;
+ I<? extends List<String>, List<String>> k2 = () -> null;
+ I<? extends List<String>, ? extends List<String>> k3 = () -> null;
+ I<? extends List<? extends String>, ? extends List<String>> k4 = <error descr="Cannot infer functional interface type">() -> null</error>;
+ I<? extends List<? extends String>, List<? extends String>> k5 = () -> null;
+ I<? extends List<? extends String>, ? extends List<? extends String>> k6 = () -> null;
+
+ I<? super String, String> s = () -> null;
+ I<? super List<String>, List<? extends String>> s1 = () -> null;
+ }
+}
+
+class NoDependency {
+ interface I<T, U> {
+ T m();
+ }
+
+ {
+ I<? extends String, ? extends String> k = () -> null;
+ }
+}
+
+class ExtendsList {
+ interface I<R extends List<T>, T> {
+ R m();
+ }
+
+ {
+ I<?, ? extends String> n = <error descr="Cannot infer functional interface type">() -> null</error>;
+ I<?, ?> n1 = <error descr="Cannot infer functional interface type">() -> null</error>;
+ I<?, String> n2 = <error descr="Cannot infer functional interface type">() -> null</error>;
+
+
+ I<? extends List<?>, String> e1 = <error descr="Cannot infer functional interface type">() -> null</error>;
+ I<? extends List<?>, ?> e2 = <error descr="Cannot infer functional interface type">() -> null</error>;
+ I<? extends List<String>, ? extends String> e3 = () -> null;
+ I<? extends List<? extends String>, ? extends String> e4 = <error descr="Cannot infer functional interface type">() -> null</error>;
+
+ I<? super List<String>, ? extends String> s1 = () -> null;
+ I<? super List<String>, String> s2 = () -> null;
+ }
+}
+
+class MultipleBounds {
+ interface I<R extends List<T> & Comparable<T>, T> {
+ R m();
+ }
+
+ interface LC<K> extends List<K>, Comparable<K> {}
+
+ {
+ I<?, String> n = <error descr="Cannot infer functional interface type">() -> null</error>;
+
+ I<? extends List<String>, ? extends String> e1 = <error descr="Cannot infer functional interface type">() -> null</error>;
+ I<? extends Comparable<String>, ? extends String> e2 = <error descr="Cannot infer functional interface type">() -> null</error>;
+ I<? extends LC<String>, ? extends String> e3 = () -> null;
+ I<? extends LC<String>, String> e4 = () -> null;
+ I<? extends LC<? extends String>, String> e5 = <error descr="Cannot infer functional interface type">() -> null</error>;
+ }
+}
+
+class FirstIndependentBound {
+ interface I<R extends List<String> & Comparable<T>, T> {
+ R m();
+ }
+
+ interface LC<K> extends List<String>, Comparable<K> {}
+
+ {
+ I<?, String> n = <error descr="Cannot infer functional interface type">() -> null</error>;
+
+ I<? extends List<String>, ? extends String> e1 = <error descr="Cannot infer functional interface type">() -> null</error>;
+ I<? extends Comparable<String>, ? extends String> e2 = () -> null;
+ I<? extends LC<String>, ? extends String> e3 = () -> null;
+ I<? extends LC<String>, String> e4 = () -> null;
+ I<? extends LC<? extends String>, String> e5 = <error descr="Cannot infer functional interface type">() -> null</error>;
+ }
+}
+
+
+class SecondIndependentBound {
+ interface I<R extends List<T> & Comparable<String>, T> {
+ R m();
+ }
+
+ interface LC<K> extends List<String>, Comparable<K> {}
+
+ {
+ I<?, String> n = <error descr="Cannot infer functional interface type">() -> null</error>;
+
+ I<? extends List<String>, ? extends String> e1 = () -> null;
+ I<? extends Comparable<String>, ? extends String> e2 = <error descr="Cannot infer functional interface type">() -> null</error>;
+ I<? extends LC<String>, ? extends String> e3 = () -> null;
+ I<? extends LC<String>, String> e4 = () -> null;
+ I<? extends LC<? extends String>, String> e5 = <error descr="Cannot infer functional interface type">() -> null</error>;
+ I<? extends LC<? extends String>, ? extends String> e6 = <error descr="Cannot infer functional interface type">() -> null</error>;
+ }
+}
\ No newline at end of file
import com.intellij.openapi.application.Result;
import com.intellij.openapi.application.ex.PathManagerEx;
import com.intellij.openapi.command.WriteCommandAction;
-import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.module.Module;
import com.intellij.testFramework.UsefulTestCase;
import com.intellij.testFramework.builders.JavaModuleFixtureBuilder;
import com.intellij.testFramework.fixtures.*;
+import com.intellij.util.ObjectUtils;
import com.intellij.util.messages.MessageBusConnection;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
@NotNull
private PsiModifierListOwner getOwner() {
- CaretModel caretModel = myFixture.getEditor().getCaretModel();
- int position = caretModel.getOffset();
- PsiElement element = myFixture.getFile().findElementAt(position);
- assert element != null;
- PsiModifierListOwner container = AddAnnotationPsiFix.getContainer(element);
- assert container != null;
- return container;
+ return ObjectUtils.assertNotNull(AddAnnotationPsiFix.getContainer(myFixture.getFile(), myFixture.getCaretOffset()));
}
private void startListening(@NotNull final List<Trinity<PsiModifierListOwner, String, Boolean>> expectedSequence) {
public void testInapplicable() { doTest(false); }
public void testDuplicateAttribute() { doTest(false); }
public void testDuplicateTarget() { doTest(false); }
+ public void testPingPongAnnotationTypesDependencies() { doTest(false);}
+ public void testClashMethods() { doTest(false);}
public void testInvalidPackageAnnotationTarget() { doTest(BASE_PATH + "/" + getTestName(true) + "/package-info.java", false, false); }
public void testPackageAnnotationNotInPackageInfo() { doTest(BASE_PATH + "/" + getTestName(true) + "/notPackageInfo.java", false, false); }
public void testTypeAnnotations() { doTest8(false); }
public void testRepeatable() { doTest8(false); }
- public void testPingPongAnnotationTypesDependencies() { doTest(false);}
- public void testClashMethods() { doTest(false);}
-
private void doTest(boolean checkWarnings) {
setLanguageLevel(LanguageLevel.JDK_1_7);
doTest(BASE_PATH + "/" + getTestName(true) + ".java", checkWarnings, false);
--- /dev/null
+/*
+ * Copyright 2000-2014 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.codeInsight.daemon.lambda;
+
+import com.intellij.codeInsight.daemon.LightDaemonAnalyzerTestCase;
+import com.intellij.openapi.projectRoots.JavaSdkVersion;
+import com.intellij.openapi.projectRoots.Sdk;
+import com.intellij.testFramework.IdeaTestUtil;
+import org.jetbrains.annotations.NonNls;
+
+public class FunctionalTypeWildcardParameterizationTest extends LightDaemonAnalyzerTestCase {
+ @NonNls static final String BASE_PATH = "/codeInsight/daemonCodeAnalyzer/lambda/wildcardParametrization";
+
+ public void testNonWildcardParametrization() throws Exception {
+ doTest();
+ }
+
+ public void testLambdaFormalParamTypesParametrization() throws Exception {
+ doTest();
+ }
+
+ private void doTest() {
+ IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_8, getModule(), getTestRootDisposable());
+ doTestNewInference(BASE_PATH + "/" + getTestName(false) + ".java", false, false);
+ }
+
+ @Override
+ protected Sdk getProjectJDK() {
+ return IdeaTestUtil.getMockJdk18();
+ }
+}
doTest();
}
+ public void testLiftedCaptureToOuterCall() throws Exception {
+ doTest();
+ }
+
private void doTest() throws Exception {
doTest(false);
}
PsiDirectory psiDirectory = FindInProjectUtil.getPsiDirectory(findModel, myProject);
List<UsageInfo> result = new ArrayList<UsageInfo>();
final CommonProcessors.CollectProcessor<UsageInfo> collector = new CommonProcessors.CollectProcessor<UsageInfo>(result);
- FindInProjectUtil.findUsages(findModel, psiDirectory, myProject, true, collector, new FindUsagesProcessPresentation(FindInProjectUtil.setupViewPresentation(true, findModel)));
+ FindInProjectUtil.findUsages(findModel, psiDirectory, myProject, collector, new FindUsagesProcessPresentation(FindInProjectUtil.setupViewPresentation(true, findModel)));
return result;
}
myContainsTests = containsTests;
}
+ public String getPresentableShortName() {
+ String name = myModules.iterator().next().getName();
+ if (myModules.size() > 1) {
+ name += " and " + (myModules.size() - 1) + " more";
+ String fullName = getName();
+ if (fullName.length() < name.length()) {
+ name = fullName;
+ }
+ }
+ if (containsTests()) {
+ name = "tests of " + name;
+ }
+ return name;
+ }
+
public String getName() {
if (myModules.size() == 1) return myModules.iterator().next().getName();
return StringUtil.join(myModules, GET_NAME, ",");
final boolean errorsDetected = Utils.errorsDetected(context);
if (!isForcedRecompilationAllJavaModules(context)) {
if (context.shouldDifferentiate(chunk)) {
- context.processMessage(new ProgressMessage("Checking dependencies... [" + chunk.getName() + "]"));
+ context.processMessage(new ProgressMessage("Checking dependencies... [" + chunk.getPresentableShortName() + "]"));
final Set<File> allCompiledFiles = getAllCompiledFilesContainer(context);
final Set<File> allAffectedFiles = getAllAffectedFilesContainer(context);
}
}
else {
- final String messageText = "Marking " + chunk.getName() + " and direct dependants for recompilation";
+ final String messageText = "Marking " + chunk.getPresentableShortName() + " and direct dependants for recompilation";
LOG.info("Non-incremental mode: " + messageText);
context.processMessage(new ProgressMessage(messageText));
return false;
}
- context.processMessage(new ProgressMessage("Updating dependency information... [" + chunk.getName() + "]"));
+ context.processMessage(new ProgressMessage("Updating dependency information... [" + chunk.getPresentableShortName() + "]"));
globalMappings.integrate(delta);
final String progress = getProgressMessage();
final boolean shouldShowProgress = !StringUtil.isEmptyOrSpaces(progress);
if (shouldShowProgress) {
- context.processMessage(new ProgressMessage(progress + " [" + chunk.getName() + "]"));
+ context.processMessage(new ProgressMessage(progress + " [" + chunk.getPresentableShortName() + "]"));
}
ExitCode exitCode = ExitCode.NOTHING_DONE;
// begin compilation round
final Mappings delta = pd.dataManager.getMappings().createDelta();
final Callbacks.Backend mappingsCallback = delta.getCallback();
- final OutputFilesSink outputSink = new OutputFilesSink(context, outputConsumer, mappingsCallback, chunk.getName());
+ final OutputFilesSink outputSink = new OutputFilesSink(context, outputConsumer, mappingsCallback, chunk.getPresentableShortName());
try {
if (hasSourcesToCompile) {
final AtomicReference<String> ref = COMPILER_VERSION_INFO.get(context);
final DiagnosticSink diagnosticSink = new DiagnosticSink(context);
final String chunkName = chunk.getName();
- context.processMessage(new ProgressMessage("Parsing java... [" + chunkName + "]"));
+ context.processMessage(new ProgressMessage("Parsing java... [" + chunk.getPresentableShortName() + "]"));
final int filesCount = files.size();
boolean compiledOk = true;
private final long myLine;
private final long myColumn;
- public CompilerMessage(String compilerName, @NotNull Throwable internalError) {
+ public CompilerMessage(@NotNull String compilerName, @NotNull Throwable internalError) {
this(compilerName, Kind.ERROR, getTextFromThrowable(internalError), null, -1L, -1L, -1L, -1L, -1L);
}
- public CompilerMessage(String compilerName, Kind kind, String messageText) {
+ public CompilerMessage(@NotNull String compilerName, Kind kind, String messageText) {
this(compilerName, kind, messageText, null, -1L, -1L, -1L, -1L, -1L);
}
- public CompilerMessage(String compilerName, Kind kind, String messageText, String sourcePath) {
+ public CompilerMessage(@NotNull String compilerName, Kind kind, String messageText, String sourcePath) {
this(compilerName, kind, messageText, sourcePath, -1L, -1L, -1L, -1L, -1L);
}
- public CompilerMessage(String compilerName, Kind kind, String messageText,
+ public CompilerMessage(@NotNull String compilerName, Kind kind, String messageText,
@Nullable String sourcePath,
long problemBeginOffset,
long problemEndOffset,
myColumn = locationColumn;
}
+ @NotNull
public String getCompilerName() {
return myCompilerName;
}
miglayout-swing.jar
nanoxml-2.2.3.jar
nekohtml-1.9.14.jar
-netty-all-5.0.0.Alpha1.jar
+netty-all-5.0.0.Alpha2.jar
oromatcher.jar
picocontainer.jar
protobuf-2.5.0.jar
TextAttributesKey DEPRECATED_ATTRIBUTES = TextAttributesKey.createTextAttributesKey("DEPRECATED_ATTRIBUTES");
TextAttributesKey LOCAL_VARIABLE_ATTRIBUTES = TextAttributesKey.createTextAttributesKey("LOCAL_VARIABLE_ATTRIBUTES");
- TextAttributesKey REASSIGNED_LOCAL_VARIABLE_ATTRIBUTES = TextAttributesKey.createTextAttributesKey("REASSIGNED_LOCAL_VARIABLE_ATTRIBUTES");
- TextAttributesKey REASSIGNED_PARAMETER_ATTRIBUTES = TextAttributesKey.createTextAttributesKey("REASSIGNED_PARAMETER_ATTRIBUTES");
+ TextAttributesKey PARAMETER_ATTRIBUTES = TextAttributesKey.createTextAttributesKey("PARAMETER_ATTRIBUTES");
+ TextAttributesKey REASSIGNED_LOCAL_VARIABLE_ATTRIBUTES = TextAttributesKey.createTextAttributesKey("REASSIGNED_LOCAL_VARIABLE_ATTRIBUTES", LOCAL_VARIABLE_ATTRIBUTES);
+ TextAttributesKey REASSIGNED_PARAMETER_ATTRIBUTES = TextAttributesKey.createTextAttributesKey("REASSIGNED_PARAMETER_ATTRIBUTES", PARAMETER_ATTRIBUTES);
TextAttributesKey IMPLICIT_ANONYMOUS_CLASS_PARAMETER_ATTRIBUTES = TextAttributesKey.createTextAttributesKey("IMPLICIT_ANONYMOUS_CLASS_PARAMETER_ATTRIBUTES");
TextAttributesKey INSTANCE_FIELD_ATTRIBUTES = TextAttributesKey.createTextAttributesKey("INSTANCE_FIELD_ATTRIBUTES");
TextAttributesKey STATIC_FIELD_ATTRIBUTES = TextAttributesKey.createTextAttributesKey("STATIC_FIELD_ATTRIBUTES");
TextAttributesKey STATIC_FINAL_FIELD_ATTRIBUTES = TextAttributesKey.createTextAttributesKey("STATIC_FINAL_FIELD_ATTRIBUTES", STATIC_FIELD_ATTRIBUTES);
- TextAttributesKey PARAMETER_ATTRIBUTES = TextAttributesKey.createTextAttributesKey("PARAMETER_ATTRIBUTES");
TextAttributesKey CLASS_NAME_ATTRIBUTES = TextAttributesKey.createTextAttributesKey("CLASS_NAME_ATTRIBUTES");
TextAttributesKey ANONYMOUS_CLASS_NAME_ATTRIBUTES = TextAttributesKey.createTextAttributesKey("ANONYMOUS_CLASS_NAME_ATTRIBUTES");
TextAttributesKey TYPE_PARAMETER_NAME_ATTRIBUTES = TextAttributesKey.createTextAttributesKey("TYPE_PARAMETER_NAME_ATTRIBUTES");
public abstract void setEncoding(@Nullable("null means project") VirtualFile virtualFileOrDir, @Nullable("null means remove mapping") Charset charset);
+ @Nullable("null means 'use system-default'")
+ public Charset getDefaultCharsetForPropertiesFiles(@Nullable VirtualFile virtualFile) {
+ return null;
+ }
+
public static EncodingRegistry getInstance() {
if (ourInstanceGetter == null) {
return (EncodingRegistry)ApplicationManager.getApplication().getPicoContainer().getComponentInstance("com.intellij.openapi.vfs.encoding.EncodingManager");
public static final String APPCODE_PREFIX = "AppCode";
public static final String CPP_PREFIX = "CppIde";
public static final String PYCHARM_PREFIX = "Python";
- public static final String PYCHARM_PREFIX2 = "PyCharm";
+ public static final String PYCHARM_PREFIX2 = "PyCharmCore";
public static final String RUBY_PREFIX = "Ruby";
public static final String PHP_PREFIX = "PhpStorm";
public static final String WEB_PREFIX = "WebStorm";
}
assertInsideCommand();
+ getLineSet(); // initialize line set to track changed lines
+
DocumentEvent event = new DocumentEventImpl(this, offset, oldString, newString, myModificationStamp, wholeTextReplaced);
if (!ShutDownTracker.isShutdownHookRunning()) {
try {
if (LOG.isDebugEnabled()) LOG.debug(event.toString());
- synchronized (myLineSetLock) {
- LineSet lineSet = myLineSet;
- if (lineSet != null) {
- lineSet.changedUpdate(event);
- }
- }
+ getLineSet().changedUpdate(event);
setModificationStamp(newModificationStamp);
if (!ShutDownTracker.isShutdownHookRunning()) {
}
@Override
- public RangeHighlighter addPersistentLineHighlighter(final int line, final int layer, final TextAttributes textAttributes) {
+ public RangeHighlighterEx addPersistentLineHighlighter(final int line, final int layer, final TextAttributes textAttributes) {
int hostLine = myDocument.injectedToHostLine(line);
return myHostModel.addPersistentLineHighlighter(hostLine, layer, textAttributes);
}
void dispose();
@Nullable
- RangeHighlighter addPersistentLineHighlighter(int lineNumber, int layer, TextAttributes textAttributes);
+ RangeHighlighterEx addPersistentLineHighlighter(int lineNumber, int layer, TextAttributes textAttributes);
void fireAttributesChanged(@NotNull RangeHighlighterEx segmentHighlighter, boolean renderersChanged);
}
@Override
- public RangeHighlighter addPersistentLineHighlighter(int lineNumber, int layer, TextAttributes textAttributes) {
+ public RangeHighlighterEx addPersistentLineHighlighter(int lineNumber, int layer, TextAttributes textAttributes) {
return null;
}
@Override
@Nullable
- public RangeHighlighter addPersistentLineHighlighter(int lineNumber, int layer, TextAttributes textAttributes) {
+ public RangeHighlighterEx addPersistentLineHighlighter(int lineNumber, int layer, TextAttributes textAttributes) {
if (isNotValidLine(lineNumber)) {
return null;
}
*/
public class StopProcessAction extends DumbAwareAction implements AnAction.TransparentUpdate {
- private final ProcessHandler myProcessHandler;
+ private ProcessHandler myProcessHandler;
- public StopProcessAction(@NotNull String text, @Nullable String description, @NotNull ProcessHandler processHandler) {
+ public StopProcessAction(@NotNull String text, @Nullable String description, @Nullable ProcessHandler processHandler) {
super(text, description, AllIcons.Actions.Suspend);
myProcessHandler = processHandler;
}
+ public void setProcessHandler(@Nullable ProcessHandler processHandler) {
+ myProcessHandler = processHandler;
+ }
+
@Override
public void update(final AnActionEvent e) {
update(e.getPresentation(), getTemplatePresentation(), myProcessHandler);
stopProcess(myProcessHandler);
}
- public static void stopProcess(@NotNull ProcessHandler processHandler) {
+ public static void stopProcess(@Nullable ProcessHandler processHandler) {
if (processHandler instanceof KillableProcess && processHandler.isProcessTerminating()) {
// process termination was requested, but it's still alive
// in this case 'force quit' will be performed
return;
}
- if (processHandler.detachIsDefault()) {
- processHandler.detachProcess();
- }
- else {
- processHandler.destroyProcess();
+ if (processHandler != null) {
+ if (processHandler.detachIsDefault()) {
+ processHandler.detachProcess();
+ }
+ else {
+ processHandler.destroyProcess();
+ }
}
}
return processor.process(usage);
}
};
- FindInProjectUtil.findUsages(findModelCopy, psiDirectory, myProject, true, consumer, processPresentation);
+ FindInProjectUtil.findUsages(findModelCopy, psiDirectory, myProject, consumer, processPresentation);
}
finally {
myIsFindInProgress = false;
--- /dev/null
+/*
+ * Copyright 2000-2014 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.find.impl;
+
+import com.intellij.find.FindBundle;
+import com.intellij.find.FindModel;
+import com.intellij.find.ngrams.TrigramIndex;
+import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.application.ApplicationNamesInfo;
+import com.intellij.openapi.fileTypes.FileTypeManager;
+import com.intellij.openapi.module.Module;
+import com.intellij.openapi.module.ModuleManager;
+import com.intellij.openapi.progress.EmptyProgressIndicator;
+import com.intellij.openapi.progress.ProcessCanceledException;
+import com.intellij.openapi.progress.ProgressIndicator;
+import com.intellij.openapi.progress.ProgressManager;
+import com.intellij.openapi.project.DumbService;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.project.ProjectCoreUtil;
+import com.intellij.openapi.roots.*;
+import com.intellij.openapi.util.Computable;
+import com.intellij.openapi.util.Condition;
+import com.intellij.openapi.util.registry.Registry;
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.openapi.util.text.TrigramBuilder;
+import com.intellij.openapi.vfs.VfsUtilCore;
+import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.openapi.vfs.VirtualFileFilter;
+import com.intellij.psi.*;
+import com.intellij.psi.impl.cache.CacheManager;
+import com.intellij.psi.impl.cache.impl.id.IdIndex;
+import com.intellij.psi.impl.search.PsiSearchHelperImpl;
+import com.intellij.psi.search.*;
+import com.intellij.usageView.UsageInfo;
+import com.intellij.usages.FindUsagesProcessPresentation;
+import com.intellij.usages.UsageLimitUtil;
+import com.intellij.usages.impl.UsageViewManagerImpl;
+import com.intellij.util.CommonProcessors;
+import com.intellij.util.Processor;
+import com.intellij.util.containers.ContainerUtil;
+import com.intellij.util.indexing.FileBasedIndex;
+import com.intellij.util.indexing.FileBasedIndexImpl;
+import gnu.trove.TIntHashSet;
+import gnu.trove.TIntIterator;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.*;
+import java.util.regex.Pattern;
+
+/**
+ * @author peter
+ */
+class FindInProjectTask {
+ private static final int FILES_SIZE_LIMIT = 70 * 1024 * 1024; // megabytes.
+ private static final int SINGLE_FILE_SIZE_LIMIT = 5 * 1024 * 1024; // megabytes.
+ private final FindModel myFindModel;
+ private final Project myProject;
+ private final PsiManager myPsiManager;
+ @Nullable private final PsiDirectory myPsiDirectory;
+ private final FileIndex myFileIndex;
+ private final Condition<VirtualFile> myFileMask;
+ private final ProgressIndicator myProgress;
+ @Nullable private final Module myModule;
+ private final Set<PsiFile> myLargeFiles = ContainerUtil.newTroveSet();
+ private boolean myWarningShown;
+
+ FindInProjectTask(@NotNull final FindModel findModel,
+ @NotNull final Project project,
+ @Nullable final PsiDirectory psiDirectory) {
+ myFindModel = findModel;
+ myProject = project;
+ myPsiDirectory = psiDirectory;
+ myPsiManager = PsiManager.getInstance(project);
+
+ final String moduleName = findModel.getModuleName();
+ myModule = moduleName == null ? null : ApplicationManager.getApplication().runReadAction(new Computable<Module>() {
+ @Override
+ public Module compute() {
+ return ModuleManager.getInstance(project).findModuleByName(moduleName);
+ }
+ });
+ myFileIndex = myModule == null ?
+ ProjectRootManager.getInstance(project).getFileIndex() :
+ ModuleRootManager.getInstance(myModule).getFileIndex();
+
+ final String filter = findModel.getFileFilter();
+ final Pattern pattern = FindInProjectUtil.createFileMaskRegExp(filter);
+
+ //noinspection unchecked
+ myFileMask = pattern == null ? Condition.TRUE : new Condition<VirtualFile>() {
+ @Override
+ public boolean value(VirtualFile file) {
+ return file != null && pattern.matcher(file.getName()).matches();
+ }
+ };
+
+ final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
+ myProgress = progress != null ? progress : new EmptyProgressIndicator();
+ }
+
+ public void findUsages(@NotNull final Processor<UsageInfo> consumer, @NotNull FindUsagesProcessPresentation processPresentation) {
+ try {
+ myProgress.setIndeterminate(true);
+ myProgress.setText("Scanning indexed files...");
+ final Set<PsiFile> filesForFastWordSearch = getFilesForFastWordSearch();
+ myProgress.setIndeterminate(false);
+
+ searchInFiles(consumer, processPresentation, filesForFastWordSearch);
+
+ myProgress.setIndeterminate(true);
+ myProgress.setText("Scanning non-indexed files...");
+ final Collection<PsiFile> otherFiles = collectFilesInScope(filesForFastWordSearch);
+ myProgress.setIndeterminate(false);
+
+ searchInFiles(consumer, processPresentation, otherFiles);
+ }
+ catch (ProcessCanceledException e) {
+ // fine
+ }
+
+ if (!myLargeFiles.isEmpty()) {
+ processPresentation.setLargeFilesWereNotScanned(myLargeFiles);
+ }
+
+ if (!myProgress.isCanceled()) {
+ myProgress.setText(FindBundle.message("find.progress.search.completed"));
+ }
+ }
+
+ private void searchInFiles(Processor<UsageInfo> consumer, FindUsagesProcessPresentation processPresentation, Collection<PsiFile> psiFiles) {
+ int i = 0;
+ long totalFilesSize = 0;
+ int count = 0;
+
+ for (final PsiFile psiFile : psiFiles) {
+ final VirtualFile virtualFile = psiFile.getVirtualFile();
+ final int index = i++;
+ if (virtualFile == null) continue;
+
+ long fileLength = UsageViewManagerImpl.getFileLength(virtualFile);
+ if (fileLength == -1) continue; // Binary or invalid
+
+ if (ProjectCoreUtil.isProjectOrWorkspaceFile(virtualFile) && !Registry.is("find.search.in.project.files")) continue;
+
+ if (fileLength > SINGLE_FILE_SIZE_LIMIT) {
+ myLargeFiles.add(psiFile);
+ continue;
+ }
+
+ myProgress.checkCanceled();
+ myProgress.setFraction((double)index / psiFiles.size());
+ String text = FindBundle.message("find.searching.for.string.in.file.progress",
+ myFindModel.getStringToFind(), virtualFile.getPresentableUrl());
+ myProgress.setText(text);
+ myProgress.setText2(FindBundle.message("find.searching.for.string.in.file.occurrences.progress", count));
+
+ int countInFile = FindInProjectUtil.processUsagesInFile(psiFile, myFindModel, consumer);
+
+ count += countInFile;
+ if (countInFile > 0) {
+ totalFilesSize += fileLength;
+ if (totalFilesSize > FILES_SIZE_LIMIT && !myWarningShown) {
+ myWarningShown = true;
+ String message = FindBundle.message("find.excessive.total.size.prompt",
+ UsageViewManagerImpl.presentableSize(totalFilesSize),
+ ApplicationNamesInfo.getInstance().getProductName());
+ UsageLimitUtil.showAndCancelIfAborted(myProject, message, processPresentation.getUsageViewPresentation());
+ }
+ }
+ }
+ }
+
+ @NotNull
+ private Collection<PsiFile> collectFilesInScope(@NotNull final Set<PsiFile> alreadySearched) {
+ SearchScope customScope = myFindModel.getCustomScope();
+ final GlobalSearchScope globalCustomScope = toGlobal(customScope);
+
+ final boolean skipIndexed = canRelyOnIndices();
+
+ class EnumContentIterator implements ContentIterator {
+ final Set<PsiFile> myFiles = new LinkedHashSet<PsiFile>();
+
+ @Override
+ public boolean processFile(@NotNull final VirtualFile virtualFile) {
+ ApplicationManager.getApplication().runReadAction(new Runnable() {
+ public void run() {
+ ProgressManager.checkCanceled();
+ if (virtualFile.isDirectory() || !virtualFile.isValid() ||
+ !myFileMask.value(virtualFile) ||
+ (globalCustomScope != null && !globalCustomScope.contains(virtualFile))) {
+ return;
+ }
+
+ if (skipIndexed && isCoveredByIdIndex(virtualFile)) {
+ return;
+ }
+
+ PsiFile psiFile = myPsiManager.findFile(virtualFile);
+ if (psiFile != null && !(psiFile instanceof PsiBinaryFile) && !alreadySearched.contains(psiFile)) {
+ PsiFile sourceFile = (PsiFile)psiFile.getNavigationElement();
+ if (sourceFile != null) psiFile = sourceFile;
+ myFiles.add(psiFile);
+ }
+ }
+ });
+ return true;
+ }
+
+ @NotNull
+ private Collection<PsiFile> getFiles() {
+ return myFiles;
+ }
+ }
+
+ EnumContentIterator iterator = new EnumContentIterator();
+
+ if (customScope instanceof LocalSearchScope) {
+ for (VirtualFile file : getLocalScopeFiles((LocalSearchScope)customScope)) {
+ iterator.processFile(file);
+ }
+ }
+ else if (myPsiDirectory != null) {
+ myFileIndex.iterateContentUnderDirectory(myPsiDirectory.getVirtualFile(), iterator);
+ }
+ else {
+ boolean success = myFileIndex.iterateContent(iterator);
+ if (success && globalCustomScope != null && globalCustomScope.isSearchInLibraries()) {
+ final VirtualFile[] librarySources = ApplicationManager.getApplication().runReadAction(new Computable<VirtualFile[]>() {
+ @Override
+ public VirtualFile[] compute() {
+ OrderEnumerator enumerator = myModule == null ? OrderEnumerator.orderEntries(myProject) : OrderEnumerator.orderEntries(myModule);
+ return enumerator.withoutModuleSourceEntries().withoutDepModules().getSourceRoots();
+ }
+ });
+ iterateAll(librarySources, globalCustomScope, iterator);
+ }
+ }
+ return iterator.getFiles();
+ }
+
+ private static boolean isCoveredByIdIndex(VirtualFile file) {
+ return IdIndex.isIndexable(FileBasedIndexImpl.getFileType(file)) &&
+ ((FileBasedIndexImpl)FileBasedIndex.getInstance()).isIndexingCandidate(file, IdIndex.NAME);
+ }
+
+ private static boolean iterateAll(@NotNull VirtualFile[] files, @NotNull final GlobalSearchScope searchScope, @NotNull final ContentIterator iterator) {
+ final FileTypeManager fileTypeManager = FileTypeManager.getInstance();
+ final VirtualFileFilter contentFilter = new VirtualFileFilter() {
+ @Override
+ public boolean accept(@NotNull final VirtualFile file) {
+ return file.isDirectory() ||
+ !fileTypeManager.isFileIgnored(file) && !file.getFileType().isBinary() && searchScope.contains(file);
+ }
+ };
+ for (VirtualFile file : files) {
+ if (!VfsUtilCore.iterateChildrenRecursively(file, contentFilter, iterator)) return false;
+ }
+ return true;
+ }
+
+ @Nullable
+ private GlobalSearchScope toGlobal(@Nullable final SearchScope scope) {
+ if (scope instanceof GlobalSearchScope || scope == null) {
+ return (GlobalSearchScope)scope;
+ }
+ return ApplicationManager.getApplication().runReadAction(new Computable<GlobalSearchScope>() {
+ @Override
+ public GlobalSearchScope compute() {
+ return GlobalSearchScope.filesScope(myProject, getLocalScopeFiles((LocalSearchScope)scope));
+ }
+ });
+ }
+
+ @NotNull
+ private static Set<VirtualFile> getLocalScopeFiles(@NotNull LocalSearchScope scope) {
+ Set<VirtualFile> files = new LinkedHashSet<VirtualFile>();
+ for (PsiElement element : scope.getScope()) {
+ PsiFile file = element.getContainingFile();
+ if (file != null) {
+ ContainerUtil.addIfNotNull(files, file.getVirtualFile());
+ }
+ }
+ return files;
+ }
+
+ private boolean canRelyOnIndices() {
+ if (DumbService.isDumb(myProject)) return false;
+
+ if (myFindModel.isRegularExpressions()) return false;
+
+ // a local scope may be over a non-indexed file
+ if (myFindModel.getCustomScope() instanceof LocalSearchScope) return false;
+
+ String text = myFindModel.getStringToFind();
+ if (StringUtil.isEmptyOrSpaces(text)) return false;
+
+ if (TrigramIndex.ENABLED) return !TrigramBuilder.buildTrigram(text).isEmpty();
+
+ // $ is used to separate words when indexing plain-text files but not when indexing
+ // Java identifiers, so we can't consistently break a string containing $ characters into words
+
+ return myFindModel.isWholeWordsOnly() && text.indexOf('$') < 0;
+ }
+
+
+ @NotNull
+ private Set<PsiFile> getFilesForFastWordSearch() {
+ String stringToFind = myFindModel.getStringToFind();
+ if (stringToFind.isEmpty() || DumbService.getInstance(myProject).isDumb()) {
+ return Collections.emptySet();
+ }
+
+ SearchScope customScope = myFindModel.getCustomScope();
+ GlobalSearchScope scope = myPsiDirectory != null
+ ? GlobalSearchScopesCore.directoryScope(myPsiDirectory, true)
+ : myModule != null
+ ? myModule.getModuleContentScope()
+ : customScope instanceof GlobalSearchScope
+ ? (GlobalSearchScope)customScope
+ : toGlobal(customScope);
+ if (scope == null) {
+ scope = ProjectScope.getContentScope(myProject);
+ }
+
+ final Set<PsiFile> resultFiles = new LinkedHashSet<PsiFile>();
+
+ if (TrigramIndex.ENABLED) {
+ Set<Integer> keys = ContainerUtil.newTroveSet();
+ TIntHashSet trigrams = TrigramBuilder.buildTrigram(stringToFind);
+ TIntIterator it = trigrams.iterator();
+ while (it.hasNext()) {
+ keys.add(it.next());
+ }
+
+ if (!keys.isEmpty()) {
+ List<VirtualFile> hits = new ArrayList<VirtualFile>();
+ FileBasedIndex.getInstance().getFilesWithKey(TrigramIndex.INDEX_ID, keys, new CommonProcessors.CollectProcessor<VirtualFile>(hits), scope);
+
+ for (VirtualFile hit : hits) {
+ if (myFileMask.value(hit)) {
+ resultFiles.add(findFile(hit));
+ }
+ }
+
+ return resultFiles;
+ }
+ }
+
+ PsiSearchHelperImpl helper = (PsiSearchHelperImpl)PsiSearchHelper.SERVICE.getInstance(myProject);
+ helper.processFilesWithText(scope, UsageSearchContext.ANY, myFindModel.isCaseSensitive(), stringToFind, new Processor<VirtualFile>() {
+ @Override
+ public boolean process(VirtualFile file) {
+ if (myFileMask.value(file)) {
+ ContainerUtil.addIfNotNull(resultFiles, findFile(file));
+ }
+ return true;
+ }
+ });
+
+ // in case our word splitting is incorrect
+ for (PsiFile file : CacheManager.SERVICE.getInstance(myProject)
+ .getFilesWithWord(stringToFind, UsageSearchContext.ANY, scope, myFindModel.isCaseSensitive())) {
+ if (myFileMask.value(file.getVirtualFile())) {
+ resultFiles.add(file);
+ }
+ }
+
+ return resultFiles;
+ }
+
+ private PsiFile findFile(@NotNull final VirtualFile virtualFile) {
+ return ApplicationManager.getApplication().runReadAction(new Computable<PsiFile>() {
+ @Override
+ public PsiFile compute() {
+ return myPsiManager.findFile(virtualFile);
+ }
+ });
+ }
+
+}
import com.intellij.BundleBase;
import com.intellij.find.*;
import com.intellij.find.findInProject.FindInProjectManager;
-import com.intellij.find.ngrams.TrigramIndex;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.navigation.ItemPresentation;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditor;
-import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.module.Module;
-import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.util.ProgressWrapper;
import com.intellij.openapi.progress.util.TooManyUsagesStatus;
-import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
-import com.intellij.openapi.project.ProjectCoreUtil;
-import com.intellij.openapi.roots.*;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Factory;
-import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
-import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.openapi.util.text.TrigramBuilder;
-import com.intellij.openapi.vfs.*;
+import com.intellij.openapi.vfs.LocalFileProvider;
+import com.intellij.openapi.vfs.LocalFileSystem;
+import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.ex.VirtualFileManagerEx;
import com.intellij.psi.*;
-import com.intellij.psi.impl.cache.CacheManager;
-import com.intellij.psi.impl.cache.impl.id.IdIndex;
-import com.intellij.psi.search.*;
+import com.intellij.psi.search.LocalSearchScope;
+import com.intellij.psi.search.SearchScope;
import com.intellij.ui.content.Content;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageViewManager;
import com.intellij.usages.ConfigurableUsageTarget;
import com.intellij.usages.FindUsagesProcessPresentation;
-import com.intellij.usages.UsageLimitUtil;
import com.intellij.usages.UsageViewPresentation;
-import com.intellij.usages.impl.UsageViewManagerImpl;
-import com.intellij.util.CommonProcessors;
import com.intellij.util.Function;
import com.intellij.util.PatternUtil;
import com.intellij.util.Processor;
-import com.intellij.util.containers.ContainerUtil;
-import com.intellij.util.indexing.FileBasedIndex;
-import com.intellij.util.indexing.FileBasedIndexImpl;
-import gnu.trove.THashSet;
-import gnu.trove.TIntHashSet;
-import gnu.trove.TIntIterator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
-import java.util.*;
+import java.util.List;
import java.util.regex.Pattern;
public class FindInProjectUtil {
private static final int USAGES_PER_READ_ACTION = 100;
- private static final int FILES_SIZE_LIMIT = 70 * 1024 * 1024; // megabytes.
- private static final int SINGLE_FILE_SIZE_LIMIT = 5 * 1024 * 1024; // megabytes.
private FindInProjectUtil() {}
return virtualFile == null ? null : psiManager.findDirectory(virtualFile);
}
- private static void addFilesUnderDirectory(@NotNull PsiDirectory directory,
- @NotNull Collection<PsiFile> fileList,
- boolean isRecursive,
- @Nullable Pattern fileMaskRegExp) {
- final PsiElement[] children = directory.getChildren();
-
- for (PsiElement child : children) {
- if (child instanceof PsiFile &&
- (fileMaskRegExp == null ||
- fileMaskRegExp.matcher(((PsiFile)child).getName()).matches()
- )
- ) {
- PsiFile file = (PsiFile)child;
- PsiFile sourceFile = (PsiFile)file.getNavigationElement();
- if (sourceFile != null) file = sourceFile;
- fileList.add(file);
- }
- else if (isRecursive && child instanceof PsiDirectory) {
- addFilesUnderDirectory((PsiDirectory)child, fileList, isRecursive, fileMaskRegExp);
- }
- }
- }
-
- @Nullable
- private static Pattern createFileMaskRegExp(@NotNull FindModel findModel) {
- final String filter = findModel.getFileFilter();
- return createFileMaskRegExp(filter);
- }
@Nullable
public static Pattern createFileMaskRegExp(@Nullable String filter) {
public static void findUsages(@NotNull FindModel findModel,
final PsiDirectory psiDirectory,
@NotNull final Project project,
- boolean showWarnings,
@NotNull final Processor<UsageInfo> consumer,
@NotNull FindUsagesProcessPresentation processPresentation) {
- final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
-
- final Collection<PsiFile> psiFiles = getFilesToSearchIn(findModel, project, psiDirectory);
- try {
- final Set<PsiFile> largeFiles = new THashSet<PsiFile>();
-
- int i = 0;
- long totalFilesSize = 0;
- int count = 0;
- final boolean[] warningShown = {false};
-
- for (final PsiFile psiFile : psiFiles) {
- final VirtualFile virtualFile = psiFile.getVirtualFile();
- final int index = i++;
- if (virtualFile == null) continue;
-
- long fileLength = UsageViewManagerImpl.getFileLength(virtualFile);
- if (fileLength == -1) continue; // Binary or invalid
-
- if (ProjectCoreUtil.isProjectOrWorkspaceFile(virtualFile) && !Registry.is("find.search.in.project.files")) continue;
-
- if (fileLength > SINGLE_FILE_SIZE_LIMIT) {
- largeFiles.add(psiFile);
- continue;
- }
-
- if (progress != null) {
- progress.checkCanceled();
- progress.setFraction((double)index / psiFiles.size());
- String text = FindBundle.message("find.searching.for.string.in.file.progress",
- findModel.getStringToFind(), virtualFile.getPresentableUrl());
- progress.setText(text);
- progress.setText2(FindBundle.message("find.searching.for.string.in.file.occurrences.progress", count));
- }
-
- int countInFile = processUsagesInFile(psiFile, findModel, consumer);
-
- count += countInFile;
- if (countInFile > 0) {
- totalFilesSize += fileLength;
- if (totalFilesSize > FILES_SIZE_LIMIT && !warningShown[0]) {
- warningShown[0] = true;
- String message = FindBundle.message("find.excessive.total.size.prompt",
- UsageViewManagerImpl.presentableSize(totalFilesSize),
- ApplicationNamesInfo.getInstance().getProductName());
- UsageLimitUtil.showAndCancelIfAborted(project, message, processPresentation.getUsageViewPresentation());
- }
- }
- }
-
-
- if (!largeFiles.isEmpty()) {
- processPresentation.setLargeFilesWereNotScanned(largeFiles);
- }
- }
- catch (ProcessCanceledException e) {
- // fine
- }
-
- if (progress != null && !progress.isCanceled()) {
- progress.setText(FindBundle.message("find.progress.search.completed"));
- }
+ new FindInProjectTask(findModel, project, psiDirectory).findUsages(consumer, processPresentation);
}
- private static int processUsagesInFile(@NotNull final PsiFile psiFile,
+ static int processUsagesInFile(@NotNull final PsiFile psiFile,
@NotNull final FindModel findModel,
@NotNull final Processor<UsageInfo> consumer) {
if (findModel.getStringToFind().isEmpty()) {
return count;
}
- private static PsiFile findFile(@NotNull final PsiManager psiManager, @NotNull final VirtualFile virtualFile) {
- return ApplicationManager.getApplication().runReadAction(new Computable<PsiFile>() {
- @Override
- public PsiFile compute() {
- return psiManager.findFile(virtualFile);
- }
- });
- }
-
- @NotNull
- private static Collection<PsiFile> getFilesToSearchIn(@NotNull final FindModel findModel,
- @NotNull final Project project,
- final PsiDirectory psiDirectory) {
- final String moduleName = findModel.getModuleName();
- final Module module = moduleName == null ? null : ApplicationManager.getApplication().runReadAction(new Computable<Module>() {
- @Override
- public Module compute() {
- return ModuleManager.getInstance(project).findModuleByName(moduleName);
- }
- });
- final FileIndex fileIndex = module == null ?
- ProjectRootManager.getInstance(project).getFileIndex() :
- ModuleRootManager.getInstance(module).getFileIndex();
-
- if (psiDirectory == null || findModel.isWithSubdirectories() && fileIndex.isInContent(psiDirectory.getVirtualFile())) {
- final Pattern fileMaskRegExp = createFileMaskRegExp(findModel);
- // optimization
- Pair<Boolean, Collection<PsiFile>> fastWords = getFilesForFastWordSearch(findModel, project, psiDirectory, fileMaskRegExp, module, fileIndex);
- final Collection<PsiFile> filesForFastWordSearch = fastWords.getSecond();
-
- final boolean useIdIndex = fastWords.getFirst() && canOptimizeForFastWordSearch(findModel);
-
- SearchScope customScope = findModel.getCustomScope();
- final GlobalSearchScope globalCustomScope = toGlobal(project, customScope);
-
- class EnumContentIterator implements ContentIterator {
- final Set<PsiFile> myFiles = new LinkedHashSet<PsiFile>(filesForFastWordSearch);
- final PsiManager psiManager = PsiManager.getInstance(project);
-
- @Override
- public boolean processFile(@NotNull VirtualFile virtualFile) {
- ProgressManager.checkCanceled();
- if (virtualFile.isDirectory() ||
- (fileMaskRegExp != null && !fileMaskRegExp.matcher(virtualFile.getName()).matches()) ||
- (globalCustomScope != null && !globalCustomScope.contains(virtualFile))) {
- return true;
- }
-
- if (useIdIndex && isCoveredByIdIndex(virtualFile)) {
- return true;
- }
-
- PsiFile psiFile = findFile(psiManager, virtualFile);
- if (psiFile != null && !(psiFile instanceof PsiBinaryFile)) {
- myFiles.add(psiFile);
- }
- return true;
- }
-
- @NotNull
- private Collection<PsiFile> getFiles() {
- return myFiles;
- }
- }
-
- EnumContentIterator iterator = new EnumContentIterator();
-
- if (customScope instanceof LocalSearchScope) {
- for (VirtualFile file : getLocalScopeFiles((LocalSearchScope)customScope)) {
- iterator.processFile(file);
- }
- }
-
- if (psiDirectory == null) {
- boolean success = fileIndex.iterateContent(iterator);
- if (success && globalCustomScope != null && globalCustomScope.isSearchInLibraries()) {
- final VirtualFile[] librarySources = ApplicationManager.getApplication().runReadAction(new Computable<VirtualFile[]>() {
- @Override
- public VirtualFile[] compute() {
- OrderEnumerator enumerator = module == null ? OrderEnumerator.orderEntries(project) : OrderEnumerator.orderEntries(module);
- return enumerator.withoutModuleSourceEntries().withoutDepModules().getSourceRoots();
- }
- });
- iterateAll(librarySources, globalCustomScope, iterator);
- }
- }
- else {
- fileIndex.iterateContentUnderDirectory(psiDirectory.getVirtualFile(), iterator);
- }
- return iterator.getFiles();
- }
- if (psiDirectory.isValid()) {
- final Collection<PsiFile> fileList = new THashSet<PsiFile>();
- ApplicationManager.getApplication().runReadAction(new Runnable() {
- @Override
- public void run() {
- addFilesUnderDirectory(psiDirectory, fileList, findModel.isWithSubdirectories(), createFileMaskRegExp(findModel));
- }
- });
-
- return fileList;
- }
- return Collections.emptyList();
- }
-
- private static boolean isCoveredByIdIndex(VirtualFile file) {
- return IdIndex.isIndexable(FileBasedIndexImpl.getFileType(file)) &&
- ((FileBasedIndexImpl)FileBasedIndex.getInstance()).isIndexingCandidate(file, IdIndex.NAME);
- }
-
- private static boolean iterateAll(@NotNull VirtualFile[] files, @NotNull final GlobalSearchScope searchScope, @NotNull final ContentIterator iterator) {
- final FileTypeManager fileTypeManager = FileTypeManager.getInstance();
- final VirtualFileFilter contentFilter = new VirtualFileFilter() {
- @Override
- public boolean accept(@NotNull final VirtualFile file) {
- return file.isDirectory() ||
- !fileTypeManager.isFileIgnored(file) && !file.getFileType().isBinary() && searchScope.contains(file);
- }
- };
- for (VirtualFile file : files) {
- if (!VfsUtilCore.iterateChildrenRecursively(file, contentFilter, iterator)) return false;
- }
- return true;
- }
-
- @Nullable
- private static GlobalSearchScope toGlobal(@NotNull final Project project, @Nullable final SearchScope scope) {
- if (scope instanceof GlobalSearchScope || scope == null) {
- return (GlobalSearchScope)scope;
- }
- return ApplicationManager.getApplication().runReadAction(new Computable<GlobalSearchScope>() {
- @Override
- public GlobalSearchScope compute() {
- return GlobalSearchScope.filesScope(project, getLocalScopeFiles((LocalSearchScope)scope));
- }
- });
- }
-
- @NotNull
- private static Set<VirtualFile> getLocalScopeFiles(@NotNull LocalSearchScope scope) {
- Set<VirtualFile> files = new LinkedHashSet<VirtualFile>();
- for (PsiElement element : scope.getScope()) {
- PsiFile file = element.getContainingFile();
- if (file != null) {
- ContainerUtil.addIfNotNull(files, file.getVirtualFile());
- }
- }
- return files;
- }
-
- @NotNull
- private static Pair<Boolean, Collection<PsiFile>> getFilesForFastWordSearch(@NotNull final FindModel findModel,
- @NotNull final Project project,
- @Nullable final PsiDirectory psiDirectory,
- final Pattern fileMaskRegExp,
- @Nullable final Module module,
- @NotNull FileIndex fileIndex) {
- if (DumbService.getInstance(project).isDumb()) {
- return new Pair<Boolean, Collection<PsiFile>>(false, Collections.<PsiFile>emptyList());
- }
-
- final PsiManager pm = PsiManager.getInstance(project);
- CacheManager cacheManager = CacheManager.SERVICE.getInstance(project);
- SearchScope customScope = findModel.getCustomScope();
- GlobalSearchScope scope = psiDirectory != null
- ? GlobalSearchScopesCore.directoryScope(psiDirectory, true)
- : module != null
- ? module.getModuleContentScope()
- : customScope instanceof GlobalSearchScope
- ? (GlobalSearchScope)customScope
- : toGlobal(project, customScope);
- if (scope == null) {
- scope = ProjectScope.getContentScope(project);
- }
-
- Set<Integer> keys = new THashSet<Integer>(30);
- final Set<PsiFile> resultFiles = new THashSet<PsiFile>();
- boolean fast = false;
-
- String stringToFind = findModel.getStringToFind();
- if (TrigramIndex.ENABLED) {
- TIntHashSet trigrams = TrigramBuilder.buildTrigram(stringToFind);
- TIntIterator it = trigrams.iterator();
- while (it.hasNext()) {
- keys.add(it.next());
- }
-
- if (!keys.isEmpty()) {
- fast = true;
- List<VirtualFile> hits = new ArrayList<VirtualFile>();
- FileBasedIndex.getInstance().getFilesWithKey(TrigramIndex.INDEX_ID, keys, new CommonProcessors.CollectProcessor<VirtualFile>(hits), scope);
-
- for (VirtualFile hit : hits) {
- resultFiles.add(findFile(pm, hit));
- }
-
- filterMaskedFiles(resultFiles, fileMaskRegExp);
- if (resultFiles.isEmpty()) return new Pair<Boolean, Collection<PsiFile>>(true, resultFiles);
- }
- }
-
-
- // $ is used to separate words when indexing plain-text files but not when indexing
- // Java identifiers, so we can't consistently break a string containing $ characters into words
-
- fast |= findModel.isWholeWordsOnly() && stringToFind.indexOf('$') < 0;
-
- List<String> words = StringUtil.getWordsInStringLongestFirst(stringToFind);
-
- for (int i = 0; i < words.size(); i++) {
- String word = words.get(i);
-
- PsiFile[] files = cacheManager.getFilesWithWord(word, UsageSearchContext.ANY, scope, findModel.isCaseSensitive());
- if (files.length == 0) {
- resultFiles.clear();
- break;
- }
-
- final List<PsiFile> psiFiles = Arrays.asList(files);
-
- if (i == 0 && keys.isEmpty()) {
- resultFiles.addAll(psiFiles);
- }
- else {
- resultFiles.retainAll(psiFiles);
- }
-
- filterMaskedFiles(resultFiles, fileMaskRegExp);
- if (resultFiles.isEmpty()) break;
- }
-
- if (stringToFind.isEmpty()) {
- fileIndex.iterateContent(new ContentIterator() {
- @Override
- public boolean processFile(VirtualFile file) {
- if (!file.isDirectory() && fileMaskRegExp.matcher(file.getName()).matches()) {
- PsiFile psiFile = findFile(pm, file);
- if (psiFile != null) {
- resultFiles.add(psiFile);
- }
- }
- return true;
- }
- });
- }
- else {
- // in case our word splitting is incorrect
- PsiFile[] allWordsFiles =
- cacheManager.getFilesWithWord(stringToFind, UsageSearchContext.ANY, scope, findModel.isCaseSensitive());
- ContainerUtil.addAll(resultFiles, allWordsFiles);
-
- filterMaskedFiles(resultFiles, fileMaskRegExp);
- }
-
- return new Pair<Boolean, Collection<PsiFile>>(fast, resultFiles);
- }
-
- private static void filterMaskedFiles(@NotNull final Set<PsiFile> resultFiles, @Nullable final Pattern fileMaskRegExp) {
- if (fileMaskRegExp != null) {
- for (Iterator<PsiFile> iterator = resultFiles.iterator(); iterator.hasNext();) {
- PsiFile file = iterator.next();
- if (!fileMaskRegExp.matcher(file.getName()).matches()) {
- iterator.remove();
- }
- }
- }
- }
-
- private static boolean canOptimizeForFastWordSearch(@NotNull final FindModel findModel) {
- return !findModel.isRegularExpressions()
- && (findModel.getCustomScope() == null || findModel.getCustomScope() instanceof GlobalSearchScope);
- }
-
private static int addToUsages(@NotNull Document document, @NotNull Processor<UsageInfo> consumer, @NotNull FindModel findModel,
@NotNull final PsiFile psiFile, @NotNull int[] offsetRef, int maxUsages) {
int count = 0;
myIsFindInProgress = true;
FindInProjectUtil.findUsages(myFindModelCopy, myPsiDirectory, myProject,
- true, new AdapterProcessor<UsageInfo, Usage>(processor, UsageInfo2UsageAdapter.CONVERTER),
+ new AdapterProcessor<UsageInfo, Usage>(processor, UsageInfo2UsageAdapter.CONVERTER),
myProcessPresentation);
}
finally {
import com.intellij.find.FindManager;
import com.intellij.find.FindModel;
import com.intellij.find.FindResult;
-import com.intellij.openapi.editor.EditorLastActionTracker;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.editor.EditorLastActionTracker;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.editor.actionSystem.EditorAction;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
private static boolean isRepeatedActionInvocation() {
String lastActionId = EditorLastActionTracker.getInstance().getLastActionId();
- return IdeActions.ACTION_SELECT_NEXT_OCCURENCE.equals(lastActionId) || IdeActions.ACTION_UNSELECT_LAST_OCCURENCE.equals(lastActionId);
+ return IdeActions.ACTION_SELECT_NEXT_OCCURENCE.equals(lastActionId) || IdeActions.ACTION_UNSELECT_PREVIOUS_OCCURENCE.equals(lastActionId);
}
}
}
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import org.jetbrains.annotations.Nullable;
-public class UnselectLastOccurrenceAction extends EditorAction {
- protected UnselectLastOccurrenceAction() {
+public class UnselectPreviousOccurrenceAction extends EditorAction {
+ protected UnselectPreviousOccurrenceAction() {
super(new Handler());
}
public class EnforcedPlainTextFileTypeFactory extends FileTypeFactory {
public static final LayeredIcon ENFORCED_PLAIN_TEXT_ICON = new LayeredIcon(2);
+ public static final String ENFORCED_PLAIN_TEXT = "Enforced Plain Text";
static {
ENFORCED_PLAIN_TEXT_ICON.setIcon(AllIcons.FileTypes.Text, 0);
@NotNull
@Override
public String getName() {
- return "Enforced Plain Text";
+ return ENFORCED_PLAIN_TEXT;
}
@NotNull
@Override
public String getDescription() {
- return "Enforced Plain Text";
+ return ENFORCED_PLAIN_TEXT;
}
@NotNull
import com.intellij.openapi.project.ProjectManagerListener;
import com.intellij.openapi.roots.ex.ProjectRootManagerEx;
import com.intellij.openapi.util.EmptyRunnable;
-import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vfs.VirtualFile;
-import com.intellij.openapi.vfs.newvfs.impl.StubVirtualFile;
+import com.intellij.openapi.vfs.VirtualFileWithId;
import com.intellij.util.containers.ConcurrentHashMap;
import com.intellij.util.indexing.FileBasedIndex;
import org.jetbrains.annotations.NotNull;
*/
public class EnforcedPlainTextFileTypeManager implements ProjectManagerListener {
private final Map<Project, Collection<VirtualFile>> myPlainTextFileSets = new ConcurrentHashMap<Project, Collection<VirtualFile>>();
- private final Ref<Boolean> mySetsInitialized = new Ref<Boolean>(false);
+ private volatile boolean mySetsInitialized = false;
+ private static final Object LOCK = new Object();
public EnforcedPlainTextFileTypeManager() {
ProjectManager.getInstance().addProjectManagerListener(this);
}
public boolean isMarkedAsPlainText(VirtualFile file) {
- if (file instanceof StubVirtualFile || file.isDirectory()) return false;
- synchronized (mySetsInitialized) {
- if (!mySetsInitialized.get()) {
- initPlainTextFileSets();
- mySetsInitialized.set(true);
+ if (!(file instanceof VirtualFileWithId) || file.isDirectory()) return false;
+ if (!mySetsInitialized) {
+ synchronized (LOCK) {
+ if (!mySetsInitialized) {
+ initPlainTextFileSets();
+ mySetsInitialized = true;
+ }
}
}
for (Project project : myPlainTextFileSets.keySet()) {
}
public static boolean isApplicableFor(@NotNull VirtualFile file) {
- if (file instanceof StubVirtualFile || file.isDirectory()) return false;
+ if (!(file instanceof VirtualFileWithId) || file.isDirectory()) return false;
FileType originalType = FileTypeManager.getInstance().getFileTypeByFileName(file.getName());
return !originalType.isBinary() && originalType != FileTypes.PLAIN_TEXT && originalType != StdFileTypes.JAVA;
}
fireRootsChanged(filesToSync, isPlainText);
}
- private static void fireRootsChanged(final Collection<VirtualFile> files, final boolean isAdded) {
+ private void fireRootsChanged(final Collection<VirtualFile> files, final boolean isAdded) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
ProjectPlainTextFileTypeManager projectPlainTextFileTypeManager = ProjectPlainTextFileTypeManager.getInstance(project);
for (VirtualFile file : files) {
if (projectPlainTextFileTypeManager.hasProjectContaining(file)) {
+ ensureProjectFileSetAdded(project, projectPlainTextFileTypeManager);
if (isAdded) {
projectPlainTextFileTypeManager.addFile(file);
}
});
}
+ private void ensureProjectFileSetAdded(@NotNull Project project,
+ @NotNull ProjectPlainTextFileTypeManager projectPlainTextFileTypeManager) {
+ if (!myPlainTextFileSets.containsKey(project)) {
+ myPlainTextFileSets.put(project, projectPlainTextFileTypeManager.getFiles());
+ }
+ }
+
private static class EnforcedPlainTextFileTypeManagerHolder {
private static final EnforcedPlainTextFileTypeManager ourInstance = ServiceManager.getService(EnforcedPlainTextFileTypeManager.class);
}
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
-import com.intellij.openapi.vfs.newvfs.impl.StubVirtualFile;
+import com.intellij.openapi.vfs.VirtualFileWithId;
import com.intellij.util.containers.HashSet;
import org.jdom.Attribute;
import org.jdom.Element;
private final Set<VirtualFile> myFiles = new HashSet<VirtualFile>();
protected boolean addFile(VirtualFile file) {
- if (file instanceof StubVirtualFile || file.isDirectory()) return false;
+ if (!(file instanceof VirtualFileWithId) || file.isDirectory()) return false;
myFiles.add(file);
return true;
}
import com.intellij.ide.todo.TodoFilter;
import com.intellij.ide.todo.TodoIndexPatternProvider;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.diff.impl.string.DiffString;
import com.intellij.openapi.diff.ex.DiffFragment;
import com.intellij.openapi.diff.impl.ComparisonPolicy;
import com.intellij.openapi.diff.impl.fragments.LineFragment;
private static ArrayList<LineFragment> getLineFragments(final String fileName, String beforeContent, String afterContent) throws VcsException {
try {
- DiffFragment[] woFormattingBlocks = DiffPolicy.LINES_WO_FORMATTING.buildFragments(beforeContent, afterContent);
+ DiffFragment[] woFormattingBlocks =
+ DiffPolicy.LINES_WO_FORMATTING.buildFragments(DiffString.create(beforeContent), DiffString.create(afterContent));
DiffFragment[] step1lineFragments =
new DiffCorrection.TrueLineBlocks(ComparisonPolicy.IGNORE_SPACE).correctAndNormalize(woFormattingBlocks);
return new DiffFragmentsProcessor().process(step1lineFragments);
commands = CommandLineUtil.toCommandLine(myExePath, myProgramParams.getList());
}
catch (ExecutionException e) {
- LOG.warn(e);
+ LOG.info(e);
throw e;
}
return startProcess(commands);
}
catch (IOException e) {
- LOG.warn(e);
+ LOG.info(e);
throw new ProcessNotCreatedException(e.getMessage(), e, this);
}
}
@NonNls String ACTION_FIND_NEXT = "FindNext";
@NonNls String ACTION_FIND_PREVIOUS = "FindPrevious";
@NonNls String ACTION_SELECT_NEXT_OCCURENCE = "SelectNextOccurrence";
- @NonNls String ACTION_UNSELECT_LAST_OCCURENCE = "UnselectLastOccurrence";
+ @NonNls String ACTION_UNSELECT_PREVIOUS_OCCURENCE = "UnselectPreviousOccurrence";
@NonNls String ACTION_COMPILE = "Compile";
@NonNls String ACTION_COMPILE_PROJECT = "CompileProject";
@NonNls String ACTION_MAKE_MODULE = "MakeModule";
package com.intellij.openapi.diff;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.diff.impl.string.DiffString;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import org.jetbrains.annotations.Nullable;
import java.io.*;
-import java.nio.charset.Charset;
import java.nio.ByteBuffer;
+import java.nio.charset.Charset;
/**
* Allows to compare some text not associated with file or document.
private static class LineSeparators {
private String mySeparator;
- public String correctText(String text) {
- LineTokenizer lineTokenizer = new LineTokenizer(text);
- String[] lines = lineTokenizer.execute();
+ @NotNull
+ public String correctText(@NotNull String text) {
+ DiffString.LineTokenizer lineTokenizer = new DiffString.LineTokenizer(DiffString.create(text));
+ DiffString[] lines = lineTokenizer.execute();
mySeparator = lineTokenizer.getLineSeparator();
LOG.assertTrue(mySeparator == null || !mySeparator.isEmpty());
if (mySeparator == null) mySeparator = SystemProperties.getLineSeparator();
- return LineTokenizer.concatLines(lines);
+ return DiffString.concatenate(lines).toString();
}
- public String restoreText(String text) {
+ @NotNull
+ public String restoreText(@NotNull String text) {
if (mySeparator == null) throw new NullPointerException();
return text.replaceAll("\n", mySeparator);
}
Button.darcula.selectedButtonForeground=bbbbbb
Button.darcula.disabledText.shadow=00000000
+ToggleButton.border=com.intellij.ide.ui.laf.darcula.ui.DarculaButtonPainter
+ToggleButtonUI=com.intellij.ide.ui.laf.darcula.ui.DarculaButtonUI
+
MenuItem.acceleratorForeground=eeeeee
PopupMenu.translucentBackground=3c3f41
final Insets ins = border.getBorderInsets(c);
final int yOff = (ins.top + ins.bottom) / 4;
if (!square) {
- if (((JButton)c).isDefaultButton()) {
+ if (c instanceof JButton && ((JButton)c).isDefaultButton()) {
((Graphics2D)g).setPaint(UIUtil.getGradientPaint(0, 0, getSelectedButtonColor1(), 0, c.getHeight(), getSelectedButtonColor2()));
}
else {
@Override
public void update(Graphics g, JComponent c) {
super.update(g, c);
- if (((JButton)c).isDefaultButton() && !SystemInfo.isMac) {
+ if (c instanceof JButton && ((JButton)c).isDefaultButton() && !SystemInfo.isMac) {
if (!c.getFont().isBold()) {
c.setFont(c.getFont().deriveFont(Font.BOLD));
}
--- /dev/null
+/*
+ * Copyright 2000-2014 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.ide.ui.laf.darcula.ui;
+
+import javax.swing.*;
+import javax.swing.plaf.ComponentUI;
+
+public class DarculaToggleButtonUI extends DarculaButtonUI {
+ @SuppressWarnings("MethodOverridesStaticMethodOfSuperclass")
+ public static ComponentUI createUI(JComponent c) {
+ return new DarculaToggleButtonUI();
+ }
+}
Button.darcula.selectedButtonForeground=f0f0f0
Button.darcula.disabledText.shadow=ffffff
+ToggleButton.border=com.intellij.ide.ui.laf.darcula.ui.DarculaButtonPainter
+ToggleButtonUI=com.intellij.ide.ui.laf.darcula.ui.DarculaButtonUI
+
MenuItem.acceleratorForeground=505050
PopupMenu.translucentBackground=e8e8e8
--- /dev/null
+package com.intellij.openapi.diff.actions;
+
+import com.intellij.openapi.actionSystem.*;
+import com.intellij.openapi.actionSystem.ex.ComboBoxAction;
+import com.intellij.openapi.diff.DiffBundle;
+import com.intellij.openapi.diff.ex.DiffPanelEx;
+import com.intellij.openapi.diff.impl.DiffPanelImpl;
+import com.intellij.openapi.project.DumbAware;
+import com.intellij.openapi.project.DumbAwareAction;
+import com.intellij.util.containers.HashMap;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import javax.swing.*;
+import java.awt.*;
+import java.util.Map;
+
+public abstract class DiffPanelComboBoxAction<T> extends ComboBoxAction implements DumbAware {
+ @NotNull private final Map<T, AnAction> myActions = new HashMap<T, AnAction>();
+ @NotNull private final T[] myActionOrder;
+
+ protected DiffPanelComboBoxAction(@NotNull T[] actionOrder) {
+ myActionOrder = actionOrder;
+ }
+
+ @NotNull
+ protected abstract String getActionName();
+
+ @NotNull
+ protected abstract T getCurrentOption(@NotNull DiffPanelEx diffPanel);
+
+ @Nullable
+ private static DiffPanelEx getDiffPanel(@NotNull DataContext context) {
+ return DiffPanelImpl.fromDataContext(context);
+ }
+
+ protected void addAction(T key, @NotNull AnAction action) {
+ myActions.put(key, action);
+ }
+
+ @Override
+ public JComponent createCustomComponent(final Presentation presentation) {
+ JPanel panel = new JPanel(new BorderLayout());
+ final JLabel label = new JLabel(getActionName());
+ label.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 4));
+ panel.add(label, BorderLayout.WEST);
+ panel.add(super.createCustomComponent(presentation), BorderLayout.CENTER);
+ return panel;
+ }
+
+ @NotNull
+ @Override
+ protected DefaultActionGroup createPopupActionGroup(JComponent button) {
+ DefaultActionGroup actionGroup = new DefaultActionGroup();
+ for (T option : myActionOrder) {
+ actionGroup.add(myActions.get(option));
+ }
+ return actionGroup;
+ }
+
+ @Override
+ public void update(AnActionEvent e) {
+ super.update(e);
+ Presentation presentation = e.getPresentation();
+ DiffPanelEx diffPanel = getDiffPanel(e.getDataContext());
+ if (diffPanel != null && diffPanel.getComponent().isDisplayable()) {
+ AnAction action = myActions.get(getCurrentOption(diffPanel));
+ Presentation templatePresentation = action.getTemplatePresentation();
+ presentation.setIcon(templatePresentation.getIcon());
+ presentation.setText(templatePresentation.getText());
+ presentation.setEnabled(true);
+ }
+ else {
+ presentation.setIcon(null);
+ presentation.setText(DiffBundle.message("diff.panel.combo.box.action.not.available.action.name"));
+ presentation.setEnabled(false);
+ }
+ }
+
+ protected static abstract class DiffPanelAction extends DumbAwareAction {
+ public DiffPanelAction(@NotNull String text) {
+ super(text);
+ }
+
+ public void actionPerformed(AnActionEvent e) {
+ final DiffPanelEx diffPanel = getDiffPanel(e.getDataContext());
+ if (diffPanel != null) {
+ perform(diffPanel);
+ }
+ }
+
+ protected abstract void perform(@NotNull DiffPanelEx diffPanel);
+ }
+}
*/
package com.intellij.openapi.diff.actions;
-import com.intellij.openapi.actionSystem.AnAction;
-import com.intellij.openapi.actionSystem.AnActionEvent;
-import com.intellij.openapi.actionSystem.DefaultActionGroup;
-import com.intellij.openapi.actionSystem.Presentation;
-import com.intellij.openapi.actionSystem.ex.ComboBoxAction;
import com.intellij.openapi.diff.DiffBundle;
import com.intellij.openapi.diff.ex.DiffPanelEx;
-import com.intellij.openapi.diff.impl.DiffPanelImpl;
import com.intellij.openapi.diff.impl.processing.HighlightMode;
-import com.intellij.openapi.project.DumbAware;
-import com.intellij.openapi.project.DumbAwareAction;
-import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NotNull;
-import javax.swing.*;
-import java.awt.*;
-import java.util.Map;
-
-public class HighlightModeAction extends ComboBoxAction implements DumbAware {
- private final Map<HighlightMode, AnAction> myActions = new HashMap<HighlightMode, AnAction>();
- private static final HighlightMode[] ourActionOrder =
- new HighlightMode[]{HighlightMode.BY_WORD, HighlightMode.BY_LINE, HighlightMode.NO_HIGHLIGHTING};
+public class HighlightModeAction extends DiffPanelComboBoxAction<HighlightMode> {
+ private static final HighlightMode[] ourActionOrder = new HighlightMode[]{
+ HighlightMode.BY_WORD,
+ HighlightMode.BY_LINE,
+ HighlightMode.NO_HIGHLIGHTING
+ };
public HighlightModeAction() {
- myActions.put(HighlightMode.BY_WORD,
- new SetHighlightModeAction(DiffBundle.message("diff.acton.highlight.mode.action.by.word"), HighlightMode.BY_WORD));
- myActions.put(HighlightMode.BY_LINE,
- new SetHighlightModeAction(DiffBundle.message("diff.acton.highlight.mode.action.by.line"), HighlightMode.BY_LINE));
- myActions.put(HighlightMode.NO_HIGHLIGHTING,
- new SetHighlightModeAction(DiffBundle.message("diff.acton.highlight.mode.action.no.highlighting"),
- HighlightMode.NO_HIGHLIGHTING));
+ super(ourActionOrder);
+ addAction(HighlightMode.BY_WORD, new HighlightingModeAction(DiffBundle.message("diff.acton.highlight.mode.action.by.word"), HighlightMode.BY_WORD));
+ addAction(HighlightMode.BY_LINE, new HighlightingModeAction(DiffBundle.message("diff.acton.highlight.mode.action.by.line"), HighlightMode.BY_LINE));
+ addAction(HighlightMode.NO_HIGHLIGHTING, new HighlightingModeAction(DiffBundle.message("diff.acton.highlight.mode.action.no.highlighting"), HighlightMode.NO_HIGHLIGHTING));
}
+ @NotNull
@Override
- public JComponent createCustomComponent(final Presentation presentation) {
- JPanel panel = new JPanel(new BorderLayout());
- final JLabel label = new JLabel(DiffBundle.message("diff.acton.highlight.mode.action.name"));
- label.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 4));
- panel.add(label, BorderLayout.WEST);
- panel.add(super.createCustomComponent(presentation), BorderLayout.CENTER);
- return panel;
+ protected String getActionName() {
+ return DiffBundle.message("diff.acton.highlight.mode.action.name");
}
@NotNull
- protected DefaultActionGroup createPopupActionGroup(JComponent button) {
- DefaultActionGroup actionGroup = new DefaultActionGroup();
- for (HighlightMode comparisonPolicy : ourActionOrder) {
- actionGroup.add(myActions.get(comparisonPolicy));
- }
- return actionGroup;
- }
-
- public void update(AnActionEvent e) {
- super.update(e);
- Presentation presentation = e.getPresentation();
- DiffPanelEx diffPanel = DiffPanelImpl.fromDataContext(e.getDataContext());
- if (diffPanel != null && diffPanel.getComponent().isDisplayable()) {
- AnAction action = myActions.get(diffPanel.getHighlightMode());
- Presentation templatePresentation = action.getTemplatePresentation();
- presentation.setIcon(templatePresentation.getIcon());
- presentation.setText(templatePresentation.getText());
- presentation.setEnabled(true);
- }
- else {
- presentation.setIcon(null);
- presentation.setText(DiffBundle.message("diff.acton.highlight.mode.not.available.action.name"));
- presentation.setEnabled(false);
- }
+ @Override
+ protected HighlightMode getCurrentOption(@NotNull DiffPanelEx diffPanel) {
+ return diffPanel.getHighlightMode();
}
- private static class SetHighlightModeAction extends DumbAwareAction {
+ private static class HighlightingModeAction extends DiffPanelAction {
private final HighlightMode myHighlightMode;
- public SetHighlightModeAction(String text, HighlightMode mode) {
+ public HighlightingModeAction(String text, HighlightMode highlightMode) {
super(text);
- myHighlightMode = mode;
+ myHighlightMode = highlightMode;
}
- public void actionPerformed(AnActionEvent e) {
- final DiffPanelImpl diffPanel = DiffPanelImpl.fromDataContext(e.getDataContext());
- if (diffPanel != null) {
- diffPanel.setHighlightMode(myHighlightMode);
- }
+ @Override
+ protected void perform(@NotNull DiffPanelEx diffPanel) {
+ diffPanel.setHighlightMode(myHighlightMode);
}
}
}
*/
package com.intellij.openapi.diff.actions;
-import com.intellij.openapi.actionSystem.AnAction;
-import com.intellij.openapi.actionSystem.AnActionEvent;
-import com.intellij.openapi.actionSystem.DefaultActionGroup;
-import com.intellij.openapi.actionSystem.Presentation;
-import com.intellij.openapi.actionSystem.ex.ComboBoxAction;
import com.intellij.openapi.diff.DiffBundle;
import com.intellij.openapi.diff.ex.DiffPanelEx;
import com.intellij.openapi.diff.impl.ComparisonPolicy;
-import com.intellij.openapi.diff.impl.DiffPanelImpl;
-import com.intellij.openapi.project.DumbAware;
-import com.intellij.openapi.project.DumbAwareAction;
-import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NotNull;
-import javax.swing.*;
-import java.awt.*;
-import java.util.Map;
-
-public class IgnoreWhiteSpacesAction extends ComboBoxAction implements DumbAware {
- private final Map<ComparisonPolicy, AnAction> myActions = new HashMap<ComparisonPolicy, AnAction>();
+public class IgnoreWhiteSpacesAction extends DiffPanelComboBoxAction<ComparisonPolicy> {
private static final ComparisonPolicy[] ourActionOrder = new ComparisonPolicy[]{
ComparisonPolicy.DEFAULT,
ComparisonPolicy.TRIM_SPACE,
- ComparisonPolicy.IGNORE_SPACE};
+ ComparisonPolicy.IGNORE_SPACE
+ };
public IgnoreWhiteSpacesAction() {
- myActions.put(ComparisonPolicy.DEFAULT, new IgnoringPolicyAction(DiffBundle.message("diff.acton.ignore.whitespace.policy.do.not.ignore"), ComparisonPolicy.DEFAULT));
- myActions.put(ComparisonPolicy.TRIM_SPACE, new IgnoringPolicyAction(DiffBundle.message("diff.acton.ignore.whitespace.policy.leading.and.trailing"), ComparisonPolicy.TRIM_SPACE));
- myActions.put(ComparisonPolicy.IGNORE_SPACE, new IgnoringPolicyAction(DiffBundle.message("diff.acton.ignore.whitespace.policy.all"), ComparisonPolicy.IGNORE_SPACE));
+ super(ourActionOrder);
+ addAction(ComparisonPolicy.DEFAULT, new IgnoringPolicyAction(DiffBundle.message("diff.acton.ignore.whitespace.policy.do.not.ignore"), ComparisonPolicy.DEFAULT));
+ addAction(ComparisonPolicy.TRIM_SPACE, new IgnoringPolicyAction(DiffBundle.message("diff.acton.ignore.whitespace.policy.leading.and.trailing"), ComparisonPolicy.TRIM_SPACE));
+ addAction(ComparisonPolicy.IGNORE_SPACE, new IgnoringPolicyAction(DiffBundle.message("diff.acton.ignore.whitespace.policy.all"), ComparisonPolicy.IGNORE_SPACE));
}
+ @NotNull
@Override
- public JComponent createCustomComponent(final Presentation presentation) {
- JPanel panel = new JPanel(new BorderLayout());
- final JLabel label = new JLabel(DiffBundle.message("ignore.whitespace.acton.name"));
- label.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 4));
- panel.add(label, BorderLayout.WEST);
- panel.add(super.createCustomComponent(presentation), BorderLayout.CENTER);
- return panel;
+ protected String getActionName() {
+ return DiffBundle.message("ignore.whitespace.acton.name");
}
@NotNull
- protected DefaultActionGroup createPopupActionGroup(JComponent button) {
- DefaultActionGroup actionGroup = new DefaultActionGroup();
- for (ComparisonPolicy comparisonPolicy : ourActionOrder) {
- actionGroup.add(myActions.get(comparisonPolicy));
- }
- return actionGroup;
- }
-
- public void update(AnActionEvent e) {
- super.update(e);
- Presentation presentation = e.getPresentation();
- DiffPanelEx diffPanel = DiffPanelImpl.fromDataContext(e.getDataContext());
- if (diffPanel != null && diffPanel.getComponent().isDisplayable()) {
- AnAction action = myActions.get(diffPanel.getComparisonPolicy());
- Presentation templatePresentation = action.getTemplatePresentation();
- presentation.setIcon(templatePresentation.getIcon());
- presentation.setText(templatePresentation.getText());
- presentation.setEnabled(true);
- } else {
- presentation.setIcon(null);
- presentation.setText(DiffBundle.message("ignore.whitespace.action.not.available.action.name"));
- presentation.setEnabled(false);
- }
+ @Override
+ protected ComparisonPolicy getCurrentOption(@NotNull DiffPanelEx diffPanel) {
+ return diffPanel.getComparisonPolicy();
}
- private static class IgnoringPolicyAction extends DumbAwareAction {
+ private static class IgnoringPolicyAction extends DiffPanelAction {
private final ComparisonPolicy myPolicy;
public IgnoringPolicyAction(String text, ComparisonPolicy policy) {
myPolicy = policy;
}
- public void actionPerformed(AnActionEvent e) {
- final DiffPanelImpl diffPanel = DiffPanelImpl.fromDataContext(e.getDataContext());
- if (diffPanel != null) {
- diffPanel.setComparisonPolicy(myPolicy);
- }
+ @Override
+ protected void perform(@NotNull DiffPanelEx diffPanel) {
+ diffPanel.setComparisonPolicy(myPolicy);
}
}
}
import com.intellij.openapi.diff.DiffContent;
import com.intellij.openapi.diff.DiffContentUtil;
import com.intellij.openapi.diff.DiffViewer;
-import com.intellij.openapi.diff.LineTokenizer;
-import com.intellij.openapi.diff.ex.DiffFragment;
import com.intellij.openapi.diff.impl.external.DiffManagerImpl;
import com.intellij.openapi.diff.impl.fragments.Fragment;
import com.intellij.openapi.diff.impl.fragments.LineFragment;
+import com.intellij.openapi.diff.impl.string.DiffString;
import com.intellij.openapi.diff.impl.util.FocusDiffSide;
import com.intellij.openapi.diff.impl.util.TextDiffType;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.FrameWrapper;
-import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ImageLoader;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
private DiffUtil() {
}
- public static void initDiffFrame(Project project, FrameWrapper frameWrapper, final DiffViewer diffPanel, final JComponent mainComponent) {
+ public static void initDiffFrame(Project project, @NotNull FrameWrapper frameWrapper, @NotNull final DiffViewer diffPanel, final JComponent mainComponent) {
frameWrapper.setComponent(mainComponent);
frameWrapper.setProject(project);
frameWrapper.setImage(ImageLoader.loadFromResource("/diff/Diff.png"));
}
@Nullable
- public static FocusDiffSide getFocusDiffSide(DataContext dataContext) {
+ public static FocusDiffSide getFocusDiffSide(@NotNull DataContext dataContext) {
return FocusDiffSide.DATA_KEY.getData(dataContext);
}
- public static String[] convertToLines(@NotNull String text) {
- return new LineTokenizer(text).execute();
+ @NotNull
+ public static DiffString[] convertToLines(@NotNull String text) {
+ return DiffString.create(text).tokenize();
}
- public static FileType[] chooseContentTypes(DiffContent[] contents) {
+ @NotNull
+ public static FileType[] chooseContentTypes(@NotNull DiffContent[] contents) {
FileType commonType = FileTypes.PLAIN_TEXT;
for (DiffContent content : contents) {
FileType contentType = content.getContentType();
return result;
}
- public static boolean isWritable(DiffContent content) {
+ public static boolean isWritable(@NotNull DiffContent content) {
Document document = content.getDocument();
return document != null && document.isWritable();
}
return editor;
}
- public static void drawBoldDottedFramingLines(Graphics2D g, int startX, int endX, int startY, int bottomY, Color color) {
+ public static void drawBoldDottedFramingLines(@NotNull Graphics2D g, int startX, int endX, int startY, int bottomY, @NotNull Color color) {
UIUtil.drawBoldDottedLine(g, startX, endX, startY, null, color, false);
UIUtil.drawBoldDottedLine(g, startX, endX, bottomY, null, color, false);
}
UIUtil.drawLine(g, startX, y + 1, endX, y + 1, null, color);
}
- public static Color getFramingColor(@NotNull Color backgroundColor) {
- return backgroundColor.darker();
+ @Nullable
+ public static Color getFramingColor(@Nullable Color backgroundColor) {
+ return backgroundColor != null ? backgroundColor.darker() : null;
}
@NotNull
//setDiffPolicy(diffPolicy);
diffPolicy.setRanges(ranges);
- return addMarkup(new TextCompareProcessor(myComparisonPolicy, diffPolicy).process(myAppender1.getText(), myAppender2.getText()));
+ return addMarkup(
+ new TextCompareProcessor(myComparisonPolicy, diffPolicy, myHighlightMode).process(myAppender1.getText(), myAppender2.getText()));
}
private BeforeAfter<Integer> lineStarts(int i) {
*/
package com.intellij.openapi.diff.impl.highlighting;
+import com.intellij.openapi.diff.impl.string.DiffString;
import com.intellij.openapi.diff.ex.DiffFragment;
import com.intellij.openapi.diff.impl.processing.DiffPolicy;
import com.intellij.openapi.util.TextRange;
import com.intellij.util.BeforeAfter;
import com.intellij.util.diff.FilesTooBigForDiffException;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.TestOnly;
import java.util.ArrayList;
import java.util.Arrays;
myDelegate = delegate;
}
+ @TestOnly
+ @NotNull
@Override
- public DiffFragment[] buildFragments(String text1, String text2) throws FilesTooBigForDiffException {
+ public DiffFragment[] buildFragments(@NotNull String text1, @NotNull String text2) throws FilesTooBigForDiffException {
+ return buildFragments(DiffString.create(text1), DiffString.create(text2));
+ }
+
+ @NotNull
+ @Override
+ public DiffFragment[] buildFragments(@NotNull DiffString text1, @NotNull DiffString text2) throws FilesTooBigForDiffException {
final List<DiffFragment> fragments = new ArrayList<DiffFragment>();
for (int i = 0; i < myRanges.size(); i++) {
final BeforeAfter<TextRange> range = myRanges.get(i);
- fragments.addAll(Arrays.asList(myDelegate.buildFragments(new String(text1.substring(range.getBefore().getStartOffset(), range.getBefore().getEndOffset())),
- new String(text2.substring(range.getAfter().getStartOffset(), range.getAfter().getEndOffset())))));
+ fragments.addAll(Arrays.asList(myDelegate.buildFragments(
+ text1.substring(range.getBefore().getStartOffset(), range.getBefore().getEndOffset()).copy(),
+ text2.substring(range.getAfter().getStartOffset(), range.getAfter().getEndOffset()).copy())));
}
return fragments.toArray(new DiffFragment[fragments.size()]);
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.Iterator;
+import java.util.List;
public abstract class SimpleDiffPanelState implements Disposable {
protected ComparisonPolicy myComparisonPolicy = ComparisonPolicy.DEFAULT;
public void dispose() {
}
- private LineBlocks addMarkup(final ArrayList<LineFragment> lines) {
+ private LineBlocks addMarkup(final List<LineFragment> lines) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
final FragmentHighlighterImpl fragmentHighlighter = new FragmentHighlighterImpl(myAppender1, myAppender2);
return LineBlocks.EMPTY;
}
- if (myHighlightMode == HighlightMode.NO_HIGHLIGHTING) {
- return LineBlocks.fromLineFragments(Collections.<LineFragment>emptyList());
- }
-
- return addMarkup(new TextCompareProcessor(myComparisonPolicy, myDiffPolicy, myHighlightMode == HighlightMode.BY_WORD)
- .process(myAppender1.getText(), myAppender2.getText()));
+ return addMarkup(
+ new TextCompareProcessor(myComparisonPolicy, myDiffPolicy, myHighlightMode).process(myAppender1.getText(), myAppender2.getText()));
}
public Project getProject() { return myProject; }
package com.intellij.openapi.diff.impl.incrementalMerge;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.diff.impl.string.DiffString;
import com.intellij.openapi.diff.ex.DiffFragment;
import com.intellij.openapi.diff.impl.ComparisonPolicy;
import com.intellij.openapi.diff.impl.DiffUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashSet;
import com.intellij.util.diff.FilesTooBigForDiffException;
+import org.jetbrains.annotations.Nullable;
import java.util.*;
private ArrayList<Change> buildChanges() throws FilesTooBigForDiffException {
Document base = getDocument(FragmentSide.SIDE1);
- String[] baseLines = DiffUtil.convertToLines(base.getText());
+ DiffString[] baseLines = DiffUtil.convertToLines(base.getText());
Document version = getDocument(FragmentSide.SIDE2);
- String[] versionLines = DiffUtil.convertToLines(version.getText());
+ DiffString[] versionLines = DiffUtil.convertToLines(version.getText());
DiffFragment[] fragments = ComparisonPolicy.DEFAULT.buildDiffFragmentsFromLines(baseLines, versionLines);
final ArrayList<Change> result = new ArrayList<Change>();
- new DiffFragmemntsEnumerator(fragments) {
+ new DiffFragmentsEnumerator(fragments) {
protected void process(DiffFragment fragment) {
if (fragment.isEqual()) return;
Context context = getContext();
return myChanges.get(index);
}
- private abstract static class DiffFragmemntsEnumerator {
+ private abstract static class DiffFragmentsEnumerator {
private final DiffFragment[] myFragments;
private final Context myContext;
- private DiffFragmemntsEnumerator(DiffFragment[] fragments) {
+ private DiffFragmentsEnumerator(DiffFragment[] fragments) {
myContext = new Context();
myFragments = fragments;
}
for (DiffFragment fragment : myFragments) {
myContext.myFragment = fragment;
process(fragment);
- String text1 = fragment.getText1();
- String text2 = fragment.getText2();
+ DiffString text1 = fragment.getText1();
+ DiffString text2 = fragment.getText2();
myContext.myStarts[0] += StringUtil.length(text1);
myContext.myStarts[1] += StringUtil.length(text2);
myContext.myLines[0] += countLines(text1);
}
}
- private static int countLines(String text) {
+ private static int countLines(@Nullable DiffString text) {
if (text == null) return 0;
return StringUtil.countNewLines(text);
}
import com.intellij.openapi.diff.DiffBundle;
import com.intellij.openapi.diff.DiffContent;
import com.intellij.openapi.diff.DiffRequest;
+import com.intellij.openapi.diff.impl.string.DiffString;
import com.intellij.openapi.diff.ex.DiffFragment;
import com.intellij.openapi.diff.impl.highlighting.FragmentSide;
import com.intellij.openapi.diff.impl.incrementalMerge.ui.MergePanel2;
@NotNull String baseText,
@NotNull String rightText,
@NotNull ContextLogger logger) throws FilesTooBigForDiffException {
- DiffFragment[] leftFragments = DiffPolicy.DEFAULT_LINES.buildFragments(baseText, leftText);
- DiffFragment[] rightFragments = DiffPolicy.DEFAULT_LINES.buildFragments(baseText, rightText);
+ DiffFragment[] leftFragments = DiffPolicy.DEFAULT_LINES.buildFragments(DiffString.create(baseText), DiffString.create(leftText));
+ DiffFragment[] rightFragments = DiffPolicy.DEFAULT_LINES.buildFragments(DiffString.create(baseText), DiffString.create(rightText));
int[] leftOffsets = {0, 0};
int[] rightOffsets = {0, 0};
int leftIndex = 0;
leftOffsets[1] += versionLength;
}
- private static int getTextLength(@Nullable String text1) {
+ private static int getTextLength(@Nullable DiffString text1) {
return text1 != null ? text1.length() : 0;
}
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.diff.ex.DiffFragment;
import com.intellij.openapi.diff.impl.highlighting.FragmentSide;
+import com.intellij.openapi.diff.impl.string.DiffString;
import com.intellij.openapi.util.text.StringUtil;
class PreferWholeLines implements DiffCorrection {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.diff.impl.processing.PreferWholeLines");
public static final DiffCorrection INSTANCE = new PreferWholeLines();
+
public DiffFragment[] correct(DiffFragment[] fragments) {
for (int i = 1; i < fragments.length - 1; i++) {
DiffFragment fragment = fragments[i];
if (!fragment.isOneSide()) continue;
DiffFragment nextFragment = fragments[i + 1];
FragmentSide side = FragmentSide.chooseSide(fragment);
+
+ DiffString fragmentText = side.getText(fragment);
+ DiffString otherNextFragmentText = side.getOtherText(nextFragment);
+ DiffString nextFragmentText = side.getText(nextFragment);
+
if (nextFragment.isOneSide()) {
- LOG.error("<" + side.getText(fragment) + "> <" + side.getOtherText(nextFragment) + ">");
+ LOG.error("<" + fragmentText + "> <" + otherNextFragmentText + ">");
}
- if (StringUtil.startsWithChar(side.getText(fragment), '\n') &&
- StringUtil.startsWithChar(side.getText(nextFragment), '\n') &&
- StringUtil.startsWithChar(side.getOtherText(nextFragment), '\n')) {
+ if (StringUtil.startsWithChar(fragmentText, '\n') &&
+ StringUtil.startsWithChar(nextFragmentText, '\n') &&
+ StringUtil.startsWithChar(otherNextFragmentText, '\n')) {
+
DiffFragment previous = fragments[i - 1];
- previous = side.createFragment(side.getText(previous) + "\n",
- side.getOtherText(previous) + "\n",
- previous.isModified());
+ DiffString previousText = side.getText(previous);
+ DiffString otherPreciousText = side.getOtherText(previous);
+
+ assert previous != null;
+ assert previousText != null;
+ assert otherPreciousText != null;
+ assert fragmentText != null;
+ assert nextFragmentText != null;
+ assert otherNextFragmentText != null;
+
+ previous = side.createFragment(previousText.append('\n'), otherPreciousText.append('\n'), previous.isModified());
fragments[i - 1] = previous;
- fragment = side.createFragment(side.getText(fragment).substring(1) + "\n",
- side.getOtherText(fragment),
- fragment.isModified());
+ fragment = side.createFragment(fragmentText.substring(1).append('\n'), side.getOtherText(fragment), fragment.isModified());
fragments[i] = fragment;
- nextFragment = side.createFragment(side.getText(nextFragment).substring(1),
- side.getOtherText(nextFragment).substring(1),
- nextFragment.isModified());
+ nextFragment = side.createFragment(nextFragmentText.substring(1), otherNextFragmentText.substring(1), nextFragment.isModified());
fragments[i + 1] = nextFragment;
}
}
import com.intellij.openapi.diff.impl.highlighting.FragmentSide;
import com.intellij.openapi.diff.impl.highlighting.LineBlockDivider;
import com.intellij.openapi.diff.impl.highlighting.Util;
+import com.intellij.openapi.diff.impl.string.DiffString;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.diff.FilesTooBigForDiffException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
public class TextCompareProcessor {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.diff.impl.processing.Processor");
private final DiffPolicy myDiffPolicy;
@NotNull private final ComparisonPolicy myComparisonPolicy;
- private final boolean mySearchForSubFragments;
+ @NotNull private final HighlightMode myHighlightMode;
public TextCompareProcessor(@NotNull ComparisonPolicy comparisonPolicy,
- final DiffPolicy diffPolicy,
- boolean searchForSubFragments) {
+ @NotNull DiffPolicy diffPolicy,
+ @NotNull HighlightMode highlightMode) {
myComparisonPolicy = comparisonPolicy;
myDiffPolicy = diffPolicy;
- mySearchForSubFragments = searchForSubFragments;
- }
-
- public TextCompareProcessor(@NotNull ComparisonPolicy comparisonPolicy, final DiffPolicy diffPolicy) {
- this(comparisonPolicy, diffPolicy, true);
+ myHighlightMode = highlightMode;
}
public TextCompareProcessor(@NotNull ComparisonPolicy comparisonPolicy) {
- this(comparisonPolicy, DiffPolicy.LINES_WO_FORMATTING);
+ this(comparisonPolicy, DiffPolicy.LINES_WO_FORMATTING, HighlightMode.BY_WORD);
}
- public ArrayList<LineFragment> process(@Nullable String text1, @Nullable String text2) throws FilesTooBigForDiffException {
+ public List<LineFragment> process(@Nullable String text1, @Nullable String text2) throws FilesTooBigForDiffException {
+ if (myHighlightMode == HighlightMode.NO_HIGHLIGHTING) {
+ return Collections.emptyList();
+ }
+
text1 = StringUtil.notNullize(text1);
text2 = StringUtil.notNullize(text2);
if (text1.isEmpty() || text2.isEmpty()) {
return new DummyDiffFragmentsProcessor().process(text1, text2);
}
- DiffFragment[] woFormattingBlocks = myDiffPolicy.buildFragments(text1, text2);
+ DiffString diffText1 = DiffString.create(text1);
+ DiffString diffText2 = DiffString.create(text2);
+
+ DiffFragment[] woFormattingBlocks = myDiffPolicy.buildFragments(diffText1, diffText2);
DiffFragment[] step1lineFragments = new DiffCorrection.TrueLineBlocks(myComparisonPolicy).correctAndNormalize(woFormattingBlocks);
ArrayList<LineFragment> lineBlocks = new DiffFragmentsProcessor().process(step1lineFragments);
int badLinesCount = 0;
- if (mySearchForSubFragments) {
+ if (myHighlightMode == HighlightMode.BY_WORD) {
for (LineFragment lineBlock : lineBlocks) {
if (lineBlock.isOneSide() || lineBlock.isEqual()) continue;
try {
- String subText1 = lineBlock.getText(text1, FragmentSide.SIDE1);
- String subText2 = lineBlock.getText(text2, FragmentSide.SIDE2);
+ DiffString subText1 = lineBlock.getText(diffText1, FragmentSide.SIDE1);
+ DiffString subText2 = lineBlock.getText(diffText2, FragmentSide.SIDE2);
ArrayList<LineFragment> subFragments = findSubFragments(subText1, subText2);
lineBlock.setChildren(new ArrayList<Fragment>(subFragments));
lineBlock.adjustTypeFromChildrenTypes();
return lineBlocks;
}
- private ArrayList<LineFragment> findSubFragments(String text1, String text2) throws FilesTooBigForDiffException {
+ private ArrayList<LineFragment> findSubFragments(@NotNull DiffString text1, @NotNull DiffString text2) throws FilesTooBigForDiffException {
DiffFragment[] fragments = new ByWord(myComparisonPolicy).buildFragments(text1, text2);
fragments = DiffCorrection.ConnectSingleSideToChange.INSTANCE.correct(fragments);
fragments = UniteSameType.INSTANCE.correct(fragments);
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.util.Comparing;
import com.intellij.util.ui.GraphicsUtil;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.awt.geom.CubicCurve2D;
*/
public class DividerPolygon {
- private final Color myColor;
+ @Nullable private final Color myColor;
private final int myStart1;
private final int myStart2;
private final int myEnd1;
public static final double CTRL_PROXIMITY_X = 0.3;
- public DividerPolygon(int start1, int start2, int end1, int end2, Color color, boolean applied) {
+ public DividerPolygon(int start1, int start2, int end1, int end2, @Nullable Color color, boolean applied) {
myApplied = applied;
myStart1 = advance(start1);
myStart2 = advance(start2);
//g.setComposite(composite);
}
- public static ArrayList<DividerPolygon> createVisiblePolygons(EditingSides sides, FragmentSide left, int diffDividerPolygonsOffset) {
+ public static ArrayList<DividerPolygon> createVisiblePolygons(@NotNull EditingSides sides,
+ @NotNull FragmentSide left,
+ int diffDividerPolygonsOffset) {
Editor editor1 = sides.getEditor(left);
Editor editor2 = sides.getEditor(left.otherSide());
LineBlocks lineBlocks = sides.getLineBlocks();
return new FoldingTransformation(editor);
}
- private static DividerPolygon createPolygon(Transformation[] transformations, Trapezium trapezium, Color color, FragmentSide left,
+ private static DividerPolygon createPolygon(@NotNull Transformation[] transformations,
+ @NotNull Trapezium trapezium,
+ @Nullable Color color,
+ @NotNull FragmentSide left,
int diffDividerPolygonsOffset, boolean applied) {
Interval base1 = trapezium.getBase(left);
Interval base2 = trapezium.getBase(left.otherSide());
if (project.isDisposed()) return;
if (extensions == null) {
loadSupportedExtensions(myAllPlugins);
+ if (project.isDisposed()) return;
EditorNotifications.getInstance(project).updateAllNotifications();
}
final Map<String, Plugin> ids = new HashMap<String, Plugin>();
import com.intellij.openapi.util.PasswordUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.xmlb.annotations.Transient;
+import org.jdom.Element;
import org.jetbrains.annotations.Nullable;
/**
}
}
- public void copyTo(RemoteSdkCredentials to) {
+ public void copyRemoteCredentialsTo(RemoteSdkCredentials to) {
to.setHost(getHost());
to.setPort(getPort());
to.setAnonymous(isAnonymous());
to.setStorePassword(isStorePassword());
to.setStorePassphrase(isStorePassphrase());
}
+
+ public void load(Element element) {
+ setHost(element.getAttributeValue(HOST));
+ setPort(StringUtil.parseInt(element.getAttributeValue(PORT), 22));
+ setAnonymous(StringUtil.parseBoolean(element.getAttributeValue(ANONYMOUS), false));
+ setSerializedUserName(element.getAttributeValue(USERNAME));
+ setSerializedPassword(element.getAttributeValue(PASSWORD));
+ setPrivateKeyFile(StringUtil.nullize(element.getAttributeValue(PRIVATE_KEY_FILE)));
+ setKnownHostsFile(StringUtil.nullize(element.getAttributeValue(KNOWN_HOSTS_FILE)));
+ setSerializedPassphrase(element.getAttributeValue(PASSPHRASE));
+ setUseKeyPair(StringUtil.parseBoolean(element.getAttributeValue(USE_KEY_PAIR), false));
+ }
+
+ public void save(Element rootElement) {
+ rootElement.setAttribute(HOST, StringUtil.notNullize(getHost()));
+ rootElement.setAttribute(PORT, Integer.toString(getPort()));
+ rootElement.setAttribute(ANONYMOUS, Boolean.toString(isAnonymous()));
+ rootElement.setAttribute(USERNAME, getSerializedUserName());
+ rootElement.setAttribute(PASSWORD, getSerializedPassword());
+ rootElement.setAttribute(PRIVATE_KEY_FILE, StringUtil.notNullize(getPrivateKeyFile()));
+ rootElement.setAttribute(KNOWN_HOSTS_FILE, StringUtil.notNullize(getKnownHostsFile()));
+ rootElement.setAttribute(PASSPHRASE, getSerializedPassphrase());
+ rootElement.setAttribute(USE_KEY_PAIR, Boolean.toString(isUseKeyPair()));
+ }
+
+ public void copyFrom(RemoteCredentials from) {
+ setHost(from.getHost());
+ setPort(from.getPort());
+ setAnonymous(from.isAnonymous());
+ setUserName(from.getUserName());
+ setPassword(from.getPassword());
+ setUseKeyPair(from.isUseKeyPair());
+ setPrivateKeyFile(from.getPrivateKeyFile());
+ setKnownHostsFile(from.getKnownHostsFile());
+ setStorePassword(from.isStorePassword());
+ setStorePassphrase(from.isStorePassphrase());
+ }
}
* @author traff
*/
public interface RemoteSdkCredentials extends MutableRemoteCredentials, RemoteSdkProperties {
+ String getFullInterpreterPath();
}
package com.intellij.remotesdk;
-import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.remotesdk2.RemoteConnectionCredentialsWrapper;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import java.util.LinkedList;
import java.util.List;
/**
*/
public class RemoteSdkCredentialsHolder extends RemoteCredentialsHolder implements RemoteSdkCredentials {
public static final String SSH_PREFIX = "ssh://";
- private static final String INTERPRETER_PATH = "INTERPRETER_PATH";
- private static final String HELPERS_PATH = "HELPERS_PATH";
- private static final String REMOTE_ROOTS = "REMOTE_ROOTS";
- private static final String REMOTE_PATH = "REMOTE_PATH";
- private static final String INITIALIZED = "INITIALIZED";
@NotNull
private final RemoteSdkPropertiesHolder myRemoteSdkProperties;
return SSH_PREFIX + cred.getUserName() + "@" + cred.getHost() + ":" + cred.getPort() + cred.getInterpreterPath();
}
-
/**
* Extracts interpreter path from full path generated by method getFullInterpreterPath
* Returns fullPath as fallback
@Override
public String getFullInterpreterPath() {
- return myRemoteSdkProperties.getFullInterpreterPath();
+ return constructSshCredentialsSdkFullPath(this);
}
@Override
myRemoteSdkProperties.setSdkId(sdkId);
}
+ @Override
+ public String getSdkId() {
+ return myRemoteSdkProperties.getSdkId();
+ }
+
@Override
public boolean isInitialized() {
return myRemoteSdkProperties.isInitialized();
public static boolean isRemoteSdk(@Nullable String path) {
if (path != null) {
- return path.startsWith(SSH_PREFIX);
+ return path.startsWith(SSH_PREFIX) || path.startsWith(RemoteConnectionCredentialsWrapper.VAGRANT_PREFIX) ||
+ path.startsWith(RemoteConnectionCredentialsWrapper.SFTP_DEPLOYMENT_PREFIX);
}
else {
return false;
}
}
- public void loadRemoteSdkCredentials(Element element) {
- setHost(element.getAttributeValue(HOST));
- setPort(StringUtil.parseInt(element.getAttributeValue(PORT), 22));
- setAnonymous(StringUtil.parseBoolean(element.getAttributeValue(ANONYMOUS), false));
- setSerializedUserName(element.getAttributeValue(USERNAME));
- setSerializedPassword(element.getAttributeValue(PASSWORD));
- setPrivateKeyFile(StringUtil.nullize(element.getAttributeValue(PRIVATE_KEY_FILE)));
- setKnownHostsFile(StringUtil.nullize(element.getAttributeValue(KNOWN_HOSTS_FILE)));
- setSerializedPassphrase(element.getAttributeValue(PASSPHRASE));
- setUseKeyPair(StringUtil.parseBoolean(element.getAttributeValue(USE_KEY_PAIR), false));
-
- setInterpreterPath(StringUtil.nullize(element.getAttributeValue(INTERPRETER_PATH)));
- setHelpersPath(StringUtil.nullize(element.getAttributeValue(HELPERS_PATH)));
- setRemoteRoots(loadStringsList(element, REMOTE_ROOTS, REMOTE_PATH));
+ @Override
+ public void load(Element element) {
+ super.load(element);
- setInitialized(StringUtil.parseBoolean(element.getAttributeValue(INITIALIZED), true));
+ myRemoteSdkProperties.load(element);
}
- protected static List<String> loadStringsList(Element element, String rootName, String attrName) {
- final List<String> paths = new LinkedList<String>();
- if (element != null) {
- @NotNull final List list = element.getChildren(rootName);
- for (Object o : list) {
- paths.add(((Element)o).getAttribute(attrName).getValue());
- }
- }
- return paths;
- }
+ @Override
+ public void save(Element rootElement) {
+ super.save(rootElement);
- public void saveRemoteSdkData(Element rootElement) {
- rootElement.setAttribute(HOST, StringUtil.notNullize(getHost()));
- rootElement.setAttribute(PORT, Integer.toString(getPort()));
- rootElement.setAttribute(ANONYMOUS, Boolean.toString(isAnonymous()));
- rootElement.setAttribute(USERNAME, getSerializedUserName());
- rootElement.setAttribute(PASSWORD, getSerializedPassword());
- rootElement.setAttribute(PRIVATE_KEY_FILE, StringUtil.notNullize(getPrivateKeyFile()));
- rootElement.setAttribute(KNOWN_HOSTS_FILE, StringUtil.notNullize(getKnownHostsFile()));
- rootElement.setAttribute(PASSPHRASE, getSerializedPassphrase());
- rootElement.setAttribute(USE_KEY_PAIR, Boolean.toString(isUseKeyPair()));
-
- rootElement.setAttribute(INTERPRETER_PATH, StringUtil.notNullize(getInterpreterPath()));
- rootElement.setAttribute(HELPERS_PATH, StringUtil.notNullize(getHelpersPath()));
-
- rootElement.setAttribute(INITIALIZED, Boolean.toString(isInitialized()));
-
- for (String remoteRoot : getRemoteRoots()) {
- final Element child = new Element(REMOTE_ROOTS);
- child.setAttribute(REMOTE_PATH, remoteRoot);
- rootElement.addContent(child);
- }
+ myRemoteSdkProperties.save(rootElement);
}
'}';
}
- public void copyTo(RemoteSdkCredentialsHolder to) {
- super.copyTo(to);
+ public void copyRemoteSdkCredentialsTo(RemoteSdkCredentialsHolder to) {
+ super.copyRemoteCredentialsTo(to);
myRemoteSdkProperties.copyTo(to.getRemoteSdkProperties());
}
}
void setHelpersVersionChecked(boolean helpersVersionChecked);
- String getFullInterpreterPath();
-
void setSdkId(String sdkId);
+ String getSdkId();
+
@Deprecated
boolean isInitialized();
*/
package com.intellij.remotesdk;
+import com.intellij.openapi.util.JDOMExternalizer;
+import com.intellij.openapi.util.text.StringUtil;
+import org.jdom.Element;
+
import java.util.ArrayList;
import java.util.List;
* @author traff
*/
public class RemoteSdkPropertiesHolder implements RemoteSdkProperties {
+ private static final String INTERPRETER_PATH = "INTERPRETER_PATH";
+ private static final String HELPERS_PATH = "HELPERS_PATH";
+ private static final String REMOTE_ROOTS = "REMOTE_ROOTS";
+ private static final String REMOTE_PATH = "REMOTE_PATH";
+ private static final String INITIALIZED = "INITIALIZED";
+
private String mySdkId;
private String myInterpreterPath;
myHelpersVersionChecked = helpersVersionChecked;
}
- @Override
- public String getFullInterpreterPath() {
- return mySdkId;
- }
-
public void setSdkId(String sdkId) {
mySdkId = sdkId;
}
+ public String getSdkId() {
+ return mySdkId;
+ }
+
@Override
public boolean isInitialized() {
return myInitialized;
}
- public void copyTo(RemoteSdkPropertiesHolder copy) {
+ public void copyTo(RemoteSdkProperties copy) {
copy.setInterpreterPath(getInterpreterPath());
copy.setHelpersPath(getHelpersPath());
copy.setHelpersVersionChecked(isHelpersVersionChecked());
copy.setInitialized(isInitialized());
}
+
+ public void save(Element rootElement) {
+ rootElement.setAttribute(INTERPRETER_PATH, StringUtil.notNullize(getInterpreterPath()));
+ rootElement.setAttribute(HELPERS_PATH, StringUtil.notNullize(getHelpersPath()));
+
+ rootElement.setAttribute(INITIALIZED, Boolean.toString(isInitialized()));
+
+ for (String remoteRoot : getRemoteRoots()) {
+ final Element child = new Element(REMOTE_ROOTS);
+ child.setAttribute(REMOTE_PATH, remoteRoot);
+ rootElement.addContent(child);
+ }
+ }
+
+ public void load(Element element) {
+ setInterpreterPath(StringUtil.nullize(element.getAttributeValue(INTERPRETER_PATH)));
+ setHelpersPath(StringUtil.nullize(element.getAttributeValue(HELPERS_PATH)));
+
+ setRemoteRoots(JDOMExternalizer.loadStringsList(element, REMOTE_ROOTS, REMOTE_PATH));
+
+ setInitialized(StringUtil.parseBoolean(element.getAttributeValue(INITIALIZED), true));
+ }
}
--- /dev/null
+/*
+ * Copyright 2000-2014 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.remotesdk2;
+
+import com.intellij.openapi.util.Key;
+import com.intellij.openapi.util.UserDataHolderBase;
+import com.intellij.remotesdk.RemoteCredentials;
+import com.intellij.remotesdk.RemoteCredentialsHolder;
+import com.intellij.remotesdk.RemoteSdkCredentialsHolder;
+import org.jdom.Element;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * @author traff
+ */
+public class RemoteConnectionCredentialsWrapper {
+ public static final String VAGRANT_PREFIX = "vagrant://";
+ public static final String SFTP_DEPLOYMENT_PREFIX = "sftp://";
+
+ public final Key<VagrantBasedCredentialsHolder> VAGRANT_BASED_CREDENTIALS = Key.create("VAGRANT_BASED_CREDENTIALS");
+ public final Key<WebDeploymentCredentialsHolder> WEB_DEPLOYMENT_BASED_CREDENTIALS = Key.create("WEB_DEPLOYMENT_BASED_CREDENTIALS");
+
+ public final Key<RemoteCredentialsHolder> PLAIN_SSH_CREDENTIALS = Key.create("PLAIN_SSH_CREDENTIALS");
+
+ private UserDataHolderBase myCredentialsTypeHolder = new UserDataHolderBase();
+
+ public void setVagrantConnectionType(VagrantBasedCredentialsHolder vagrantBasedCredentials) {
+ myCredentialsTypeHolder.putUserData(VAGRANT_BASED_CREDENTIALS, vagrantBasedCredentials);
+ }
+
+
+ private VagrantBasedCredentialsHolder getVagrantCredentials() {
+ return myCredentialsTypeHolder.getUserData(VAGRANT_BASED_CREDENTIALS);
+ }
+
+ public void setPlainSshCredentials(RemoteCredentialsHolder credentials) {
+ myCredentialsTypeHolder.putUserData(PLAIN_SSH_CREDENTIALS, credentials);
+ }
+
+ private RemoteCredentialsHolder getPlainSshCredentials() {
+ return myCredentialsTypeHolder.getUserData(PLAIN_SSH_CREDENTIALS);
+ }
+
+
+ public void setWebDeploymentCredentials(WebDeploymentCredentialsHolder webDeploymentCredentials) {
+ myCredentialsTypeHolder.putUserData(WEB_DEPLOYMENT_BASED_CREDENTIALS, webDeploymentCredentials);
+ }
+
+ private WebDeploymentCredentialsHolder getWebDeploymentCredentials() {
+ return myCredentialsTypeHolder.getUserData(WEB_DEPLOYMENT_BASED_CREDENTIALS);
+ }
+
+ private boolean isVagrantConnection() {
+ return getVagrantCredentials() != null;
+ }
+
+ private boolean isPlainSshConnection() {
+ return getPlainSshCredentials() != null;
+ }
+
+ private boolean isWebDeploymentConnection() {
+ return getWebDeploymentCredentials() != null;
+ }
+
+
+ public Object getConnectionKey() {
+ if (isVagrantConnection()) {
+ return getVagrantCredentials();
+ }
+ else if (isPlainSshConnection()) {
+ return getPlainSshCredentials();
+ }
+ else if (isWebDeploymentConnection()) {
+ return getWebDeploymentCredentials();
+ }
+ else {
+ throw unknownConnectionType();
+ }
+ }
+
+ public void save(final Element rootElement) {
+ switchType(new RemoteSdkConnectionAcceptor() {
+ @Override
+ public void ssh(RemoteCredentialsHolder cred) {
+ cred.save(rootElement);
+ }
+
+ @Override
+ public void vagrant(VagrantBasedCredentialsHolder cred) {
+ cred.save(rootElement);
+ }
+
+ @Override
+ public void deployment(WebDeploymentCredentialsHolder cred) {
+ cred.save(rootElement);
+ }
+ });
+ }
+
+ public static IllegalStateException unknownConnectionType() {
+ return new IllegalStateException("Unknown connection type"); //TODO
+ }
+
+ public void copyTo(RemoteConnectionCredentialsWrapper copy) {
+ copy.myCredentialsTypeHolder = new UserDataHolderBase();
+ copy.setPlainSshCredentials(getPlainSshCredentials());
+ copy.setVagrantConnectionType(getVagrantCredentials());
+ copy.setWebDeploymentCredentials(getWebDeploymentCredentials());
+ }
+
+ public String getId() {
+ if (isVagrantConnection()) {
+ @NotNull VagrantBasedCredentialsHolder cred = getVagrantCredentials();
+
+ return VAGRANT_PREFIX + cred.getVagrantFolder();
+ }
+ else if (isPlainSshConnection()) {
+ RemoteCredentials cred = getPlainSshCredentials();
+
+ return constructSshCredentialsFullPath(cred);
+ }
+ else if (isWebDeploymentConnection()) {
+ WebDeploymentCredentialsHolder cred = getWebDeploymentCredentials();
+ return constructSftpCredentialsFullPath(cred.getSshCredentials());
+ }
+ else {
+ throw unknownConnectionType();
+ }
+ }
+
+ private static String constructSftpCredentialsFullPath(RemoteCredentials cred) {
+ return SFTP_DEPLOYMENT_PREFIX + cred.getUserName() + "@" + cred.getHost() + ":" + cred.getPort();
+ }
+
+
+ public static String constructSshCredentialsFullPath(RemoteCredentials cred) {
+ return RemoteSdkCredentialsHolder.SSH_PREFIX + cred.getUserName() + "@" + cred.getHost() + ":" + cred.getPort();
+ }
+
+ public void switchType(RemoteSdkConnectionAcceptor acceptor) {
+ if (isVagrantConnection()) {
+ acceptor.vagrant(getVagrantCredentials());
+ }
+ else if (isPlainSshConnection()) {
+ acceptor.ssh(getPlainSshCredentials());
+ }
+ else if (isWebDeploymentConnection()) {
+ acceptor.deployment(getWebDeploymentCredentials());
+ }
+ else {
+ throw unknownConnectionType();
+ }
+ }
+
+ public interface RemoteSdkConnectionAcceptor {
+ void ssh(RemoteCredentialsHolder cred);
+ void vagrant(VagrantBasedCredentialsHolder cred);
+ void deployment(WebDeploymentCredentialsHolder cred);
+ }
+}
import com.intellij.remotesdk.RemoteSdkCredentials;
import com.intellij.remotesdk.RemoteSdkCredentialsHolder;
import com.intellij.remotesdk.RemoteSdkProperties;
+import org.jetbrains.annotations.NotNull;
/**
* @author traff
String getFullInterpreterPath();
+ void setVagrantConnectionType(@NotNull VagrantBasedCredentialsHolder vagrantBasedCredentials);
+
/**
* This method switches to use of ssh-credentials based data
* @param credentials credentials that specify connection
*/
- void setSshCredentials(RemoteSdkCredentialsHolder credentials);
+ void setSshCredentials(@NotNull RemoteSdkCredentialsHolder credentials);
+
+ void setDeploymentConnectionType(@NotNull WebDeploymentCredentialsHolder credentials);
}
public interface RemoteSdkProducer<T extends RemoteSdkCredentials> {
T getRemoteSdkCredentials() throws InterruptedException;
- void produceRemoteSdkCredentials(Consumer<T> remoteSdkConsumer);
+ void produceRemoteSdkCredentials(Consumer<T> remoteSdkCredentialsConsumer);
Object getRemoteSdkDataKey();
}
--- /dev/null
+/*
+ * Copyright 2000-2014 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.remotesdk2;
+
+import com.intellij.openapi.util.text.StringUtil;
+import org.jdom.Element;
+import org.jetbrains.annotations.NotNull;
+
+/**
+* @author traff
+*/
+public class VagrantBasedCredentialsHolder {
+ private static final String VAGRANT_FOLDER = "VAGRANT_FOLDER";
+ private String myVagrantFolder;
+
+ public VagrantBasedCredentialsHolder() {
+ }
+
+ public VagrantBasedCredentialsHolder(@NotNull String folder) {
+ myVagrantFolder = folder;
+ }
+
+ public void setVagrantFolder(String vagrantFolder) {
+ myVagrantFolder = vagrantFolder;
+ }
+
+ @NotNull
+ public String getVagrantFolder() {
+ return myVagrantFolder;
+ }
+
+ public void load(Element element) {
+ setVagrantFolder(element.getAttributeValue(VAGRANT_FOLDER));
+ }
+
+ public void save(Element element) {
+ element.setAttribute(VAGRANT_FOLDER, getVagrantFolder());
+ }
+}
--- /dev/null
+/*
+ * Copyright 2000-2014 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.remotesdk2;
+
+import com.intellij.remotesdk.RemoteCredentials;
+import com.intellij.remotesdk.RemoteCredentialsHolder;
+import org.jdom.Element;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * @author traff
+ */
+public class WebDeploymentCredentialsHolder {
+ public static final String WEB_SERVER_CONFIG_ID = "WEB_SERVER_CONFIG_ID";
+
+ private String myWebServerConfigId;
+ private final RemoteCredentialsHolder myRemoteCredentials = new RemoteCredentialsHolder();
+
+
+ public WebDeploymentCredentialsHolder() {
+ }
+
+ public WebDeploymentCredentialsHolder(@NotNull String webServerConfigId, @NotNull RemoteCredentials remoteCredentials) {
+ myWebServerConfigId = webServerConfigId;
+ myRemoteCredentials.copyFrom(remoteCredentials);
+ }
+
+ @NotNull
+ public String getWebServerConfigId() {
+ return myWebServerConfigId;
+ }
+
+ public void setWebServerConfigId(@NotNull String webServerConfigId) {
+ myWebServerConfigId = webServerConfigId;
+ }
+
+ public void load(Element element) {
+ myRemoteCredentials.load(element);
+ setWebServerConfigId(element.getAttributeValue(WEB_SERVER_CONFIG_ID));
+ }
+
+ public void save(Element element) {
+ element.setAttribute(WEB_SERVER_CONFIG_ID, getWebServerConfigId());
+
+ myRemoteCredentials.save(element);
+ }
+
+ public RemoteCredentials getSshCredentials() {
+ return myRemoteCredentials;
+ }
+}
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.io.BuiltInServer;
+import java.util.Random;
+import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
private BuiltInServer server;
private boolean enabledInUnitTestMode = true;
- //static {
- // // IDEA-120811
- // System.setProperty("io.netty.machineId", Integer.toHexString(new Random().nextInt()));
- // System.setProperty("io.netty.processId", "1");
- //}
+ static {
+ // IDEA-120811
+ String id = UUID.randomUUID().toString();
+ System.setProperty("io.netty.machineId", id.substring(id.length() - 8));
+ System.setProperty("io.netty.processId", Integer.toString(new Random().nextInt(65535)));
+ }
@Override
public int getPort() {
action.EditorCloneCaretBelow.text=Clone Caret Below
action.EditorCloneCaretAbove.text=Clone Caret Above
action.SelectNextOccurrence.text=Select Next Occurrence
-action.UnselectLastOccurrence.text=Unselect Last Occurrence
+action.UnselectPreviousOccurrence.text=Unselect Occurrence
action.EditorToggleStickySelection.text=Toggle Sticky Selection
action.EditorSwapSelectionBoundaries.text=Swap selection boundaries
action.EditorLineStart.text=Move Caret to Line Start
diff.acton.ignore.whitespace.policy.leading.and.trailing=Leading and trailing
diff.acton.ignore.whitespace.policy.all=All
ignore.whitespace.acton.name=Ignore whitespace:
-ignore.whitespace.action.not.available.action.name=<Not available>
+diff.panel.combo.box.action.not.available.action.name=<Not available>
diff.dialog.select.change.action.name=Select Change
diff.dialog.select.change.action.description=Select changed text in this version and corresponding in other
merge.files.dialog.title=Merge
diff.acton.highlight.mode.action.by.word=By Word
diff.acton.highlight.mode.action.by.line=By Line
diff.acton.highlight.mode.action.no.highlighting=No Highlighting
-diff.acton.highlight.mode.not.available.action.name=<Not available>
diff.acton.highlight.mode.action.name=Highlighting Mode:
<option name="EFFECT_COLOR"/>
</value>
</option>
- <option name="REASSIGNED_LOCAL_VARIABLE_ATTRIBUTES">
- <value>
- <option name="FOREGROUND"/>
- <option name="BACKGROUND"/>
- <option name="EFFECT_COLOR"/>
- </value>
- </option>
- <option name="REASSIGNED_PARAMETER_ATTRIBUTES">
- <value>
- <option name="FOREGROUND"/>
- <option name="BACKGROUND"/>
- <option name="EFFECT_COLOR"/>
- </value>
- </option>
<option name="IMPLICIT_ANONYMOUS_CLASS_PARAMETER_ATTRIBUTES">
<value>
<option name="FOREGROUND" value="660e7a"/>
<action id="SelectNextOccurrence">
<keyboard-shortcut first-keystroke="alt J"/>
</action>
- <action id="UnselectLastOccurrence">
+ <action id="UnselectPreviousOccurrence">
<keyboard-shortcut first-keystroke="alt shift J"/>
</action>
<action id="GotoDeclaration">
<action id="SelectNextOccurrence">
<keyboard-shortcut first-keystroke="alt Y"/>
</action>
- <action id="UnselectLastOccurrence">
+ <action id="UnselectPreviousOccurrence">
<keyboard-shortcut first-keystroke="alt shift Y"/>
</action>
<action id="FindUsages">
<action id="SelectNextOccurrence">
<keyboard-shortcut first-keystroke="control G"/>
</action>
- <action id="UnselectLastOccurrence">
+ <action id="UnselectPreviousOccurrence">
<keyboard-shortcut first-keystroke="control shift G"/>
</action>
<action id="SelectNextOccurrence">
<keyboard-shortcut first-keystroke="control G"/>
</action>
- <action id="UnselectLastOccurrence">
+ <action id="UnselectPreviousOccurrence">
<keyboard-shortcut first-keystroke="control shift G"/>
</action>
<action id="FindPrevious" class="com.intellij.ide.actions.SearchBackAction"/>
<action id="FindWordAtCaret" class="com.intellij.openapi.editor.actions.FindWordAtCaretAction"/>
<action id="SelectNextOccurrence" class="com.intellij.openapi.editor.actions.SelectNextOccurrenceAction"/>
- <action id="UnselectLastOccurrence" class="com.intellij.openapi.editor.actions.UnselectLastOccurrenceAction"/>
+ <action id="UnselectPreviousOccurrence" class="com.intellij.openapi.editor.actions.UnselectPreviousOccurrenceAction"/>
<separator/>
<action id="FindInPath" class="com.intellij.find.actions.FindInPathAction"/>
<action id="ReplaceInPath" class="com.intellij.find.actions.ReplaceInPathAction"/>
assertEquals(keys[1], keys[2]);
assertFalse(keys[2].equals(keys[3]));
}
+
+ public static void assertEquals(Object obj1, Object obj2) {
+ if (obj1 instanceof CharSequence && obj2 instanceof CharSequence) {
+ assertEquals(obj1.toString(), obj2.toString());
+ return;
+ }
+
+ assertEquals(obj1, obj2);
+ }
}
import com.intellij.openapi.diff.ex.DiffFragment;
import com.intellij.openapi.diff.impl.MultiCheck;
+import com.intellij.openapi.diff.impl.string.DiffString;
import com.intellij.util.Assertion;
import com.intellij.util.diff.Diff;
import com.intellij.util.diff.FilesTooBigForDiffException;
last};
lines = Util.uniteFormattingOnly(lines);
CHECK.compareAll(new DiffFragment[][]{
- first,
- new DiffFragment[]{inline1, inline2, inline3, inline4},
- last},
- lines);
+ first,
+ new DiffFragment[]{inline1, inline2, inline3, inline4},
+ last},
+ lines
+ );
}
public void testConcatenateEquals() {
CHECK.singleElement(Util.cutFirst(new DiffFragment[]{
DiffFragment.unchanged("ab", "ac")
}),
- DiffFragment.unchanged("b", "c"));
+ DiffFragment.unchanged("b", "c")
+ );
CHECK.compareAll(new DiffFragment[]{
new DiffFragment(null, "c")
Util.cutFirst(new DiffFragment[]{
new DiffFragment(null, "ab"),
new DiffFragment("c", "d")
- }));
+ })
+ );
}
public void testCutFirst2() {
}));
}
+
+ public static void assertEquals(CharSequence obj1, CharSequence obj2) {
+ assertEquals(obj1.toString(), obj2.toString());
+ }
}
import com.intellij.openapi.diff.impl.highlighting.FragmentSide;
import com.intellij.openapi.diff.impl.highlighting.Util;
import com.intellij.util.diff.FilesTooBigForDiffException;
-import junit.framework.Assert;
import junit.framework.TestCase;
public class LineBlocksDiffPolicyTest extends TestCase{
checkPolicy(diffPolicy, "abc\n123\n", "ABC\nXYZ");
}
- private void checkPolicy(DiffPolicy.LineBlocks diffPolicy, String text1, String text2) throws FilesTooBigForDiffException {
+ private static void checkPolicy(DiffPolicy.LineBlocks diffPolicy, String text1, String text2) throws FilesTooBigForDiffException {
DiffFragment[] fragments = diffPolicy.buildFragments(text1, text2);
- Assert.assertEquals(text1, Util.getText(fragments, FragmentSide.SIDE1));
- assertEquals(text2, Util.getText(fragments, FragmentSide.SIDE2));
+ assertEquals(text1, Util.getText(fragments, FragmentSide.SIDE1).toString());
+ assertEquals(text2, Util.getText(fragments, FragmentSide.SIDE2).toString());
}
}
import com.intellij.util.diff.FilesTooBigForDiffException;
import junit.framework.TestCase;
-import java.util.ArrayList;
+import java.util.List;
public class TextCompareProcessorTest extends TestCase {
public void testIgnoreWrappingEqualText() throws FilesTooBigForDiffException {
TextCompareProcessor processor = new TextCompareProcessor(ComparisonPolicy.IGNORE_SPACE);
- ArrayList<LineFragment> lineFragments = processor.process("f(a, b)\n", "f(a,\nb)\n");
+ List<LineFragment> lineFragments = processor.process("f(a, b)\n", "f(a,\nb)\n");
assertTrue(lineFragments.size() == 1);
assertNull(lineFragments.get(0).getType());
}
}
private void executeReverseAction() {
- myFixture.performEditorAction(IdeActions.ACTION_UNSELECT_LAST_OCCURENCE);
+ myFixture.performEditorAction(IdeActions.ACTION_UNSELECT_PREVIOUS_OCCURENCE);
}
}
--- /dev/null
+/*
+ * Copyright 2000-2014 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.fileTypes;
+
+import com.intellij.openapi.file.exclude.EnforcedPlainTextFileTypeFactory;
+import com.intellij.openapi.file.exclude.EnforcedPlainTextFileTypeManager;
+import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
+
+/**
+ * @author Rustam Vishnyakov
+ */
+public class EnforcedPlaintTextFileTypeManagerTest extends LightPlatformCodeInsightFixtureTestCase {
+ public void testMarkAsPlainText() {
+ EnforcedPlainTextFileTypeManager manager = EnforcedPlainTextFileTypeManager.getInstance();
+ VirtualFile file = myFixture.getTempDirFixture().createFile("test.java");
+ FileType originalType = file.getFileType();
+ assertEquals("JAVA", originalType.getName());
+ manager.markAsPlainText(file);
+ FileType changedType = file.getFileType();
+ assertEquals(EnforcedPlainTextFileTypeFactory.ENFORCED_PLAIN_TEXT, changedType.getName());
+ manager.resetOriginalFileType(file);
+ FileType revertedType = file.getFileType();
+ assertEquals(originalType, revertedType);
+ }
+}
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
-public class LineTokenizer {
+public class LineTokenizer extends LineTokenizerBase<String> {
private final char[] myChars;
private final String myText;
- private int myIndex = 0;
- @Nullable private String myLineSeparator = null;
-
public LineTokenizer(@NotNull String text) {
myChars = text.toCharArray();
myText = text;
@NotNull
public String[] execute() {
- List<String> lines = new ArrayList<String>();
- while (notAtEnd()) {
- int begin = myIndex;
- skipToEOL();
- int endIndex = myIndex;
- boolean appendNewLine = false;
-
- if (notAtEnd() && isAtEOL()) {
- if (myChars[endIndex] == '\n') {
- endIndex++;
- }
- else {
- appendNewLine = true;
- }
- skipEOL();
- }
-
- String line = myText.substring(begin, endIndex);
- if (appendNewLine) {
- line += "\n";
- }
- lines.add(line);
- }
+ ArrayList<String> lines = new ArrayList<String>();
+ doExecute(lines);
return ArrayUtil.toStringArray(lines);
}
- private void skipEOL() {
- int eolStart = myIndex;
- boolean nFound = false;
- boolean rFound = false;
- while (notAtEnd()) {
- boolean n = myChars[myIndex] == '\n';
- boolean r = myChars[myIndex] == '\r';
- if (!n && !r) {
- break;
- }
- if ((nFound && n) || (rFound && r)) {
- break;
- }
- nFound |= n;
- rFound |= r;
- myIndex++;
+ @Override
+ protected void addLine(List<String> lines, int start, int end, boolean appendNewLine) {
+ if (appendNewLine) {
+ lines.add(myText.substring(start, end) + "\n");
}
- if (myLineSeparator == null) {
- myLineSeparator = new String(myChars, eolStart, myIndex - eolStart);
+ else {
+ lines.add(myText.substring(start, end));
}
}
- @Nullable
- public String getLineSeparator() {
- return myLineSeparator;
+ @Override
+ protected char charAt(int index) {
+ return myChars[index];
}
- private void skipToEOL() {
- while (notAtEnd() && !isAtEOL()) {
- myIndex++;
- }
- }
-
- private boolean notAtEnd() {
- return myIndex < myChars.length;
+ @Override
+ protected int length() {
+ return myChars.length;
}
- private boolean isAtEOL() {
- return myChars[myIndex] == '\r' || myChars[myIndex] == '\n';
+ @NotNull
+ @Override
+ protected String substring(int start, int end) {
+ return myText.substring(start, end);
}
@NotNull
--- /dev/null
+/*
+ * Copyright 2000-2014 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;
+
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.List;
+
+public abstract class LineTokenizerBase<T> {
+ private int myIndex = 0;
+ private int myLineSeparatorStart = -1;
+ private int myLineSeparatorEnd = -1;
+
+ protected abstract void addLine(List<T> lines, int start, int end, boolean appendNewLine);
+
+ protected abstract char charAt(int index);
+
+ protected abstract int length();
+
+ @NotNull
+ protected abstract String substring(int start, int end);
+
+ public void doExecute(List<T> lines) {
+ while (notAtEnd()) {
+ int begin = myIndex;
+ skipToEOL();
+ int endIndex = myIndex;
+ boolean appendNewLine = false;
+
+ if (notAtEnd() && isAtEOL()) {
+ if (charAt(endIndex) == '\n') {
+ endIndex++;
+ }
+ else {
+ appendNewLine = true;
+ }
+ skipEOL();
+ }
+
+ addLine(lines, begin, endIndex, appendNewLine);
+ }
+ }
+
+ private void skipEOL() {
+ int eolStart = myIndex;
+ boolean nFound = false;
+ boolean rFound = false;
+ while (notAtEnd()) {
+ boolean n = charAt(myIndex) == '\n';
+ boolean r = charAt(myIndex) == '\r';
+ if (!n && !r) {
+ break;
+ }
+ if ((nFound && n) || (rFound && r)) {
+ break;
+ }
+ nFound |= n;
+ rFound |= r;
+ myIndex++;
+ }
+ if (myLineSeparatorStart == -1) {
+ myLineSeparatorStart = eolStart;
+ myLineSeparatorEnd = myIndex;
+ }
+ }
+
+ @Nullable
+ public String getLineSeparator() {
+ if (myLineSeparatorStart == -1) return null;
+ return substring(myLineSeparatorStart, myLineSeparatorEnd);
+ }
+
+ private void skipToEOL() {
+ while (notAtEnd() && !isAtEOL()) {
+ myIndex++;
+ }
+ }
+
+ private boolean notAtEnd() {
+ return myIndex < length();
+ }
+
+ private boolean isAtEOL() {
+ return charAt(myIndex) == '\r' || charAt(myIndex) == '\n';
+ }
+}
\ No newline at end of file
*/
package com.intellij.openapi.diff.ex;
+import com.intellij.openapi.diff.impl.string.DiffString;
+import com.intellij.openapi.diff.impl.string.DiffStringBuilder;
import com.intellij.openapi.util.text.StringUtil;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.annotations.TestOnly;
public class DiffFragment {
public static DiffFragment[] EMPTY_ARRAY = new DiffFragment[0];
- private final String myText1;
- private final String myText2;
+ @Nullable private CharSequence myText1;
+ @Nullable private CharSequence myText2;
private boolean myIsModified;
- private StringBuilder myText1Builder;
- private StringBuilder myText2Builder;
+ @TestOnly
+ public DiffFragment(@Nullable String text1, @Nullable String text2) {
+ this(DiffString.createNullable(text1), DiffString.createNullable(text2));
+ }
- public DiffFragment(String text1, String text2) {
+ public DiffFragment(@Nullable DiffString text1, @Nullable DiffString text2) {
myText1 = text1;
myText2 = text2;
myIsModified = (text1 == null || text2 == null || !text1.equals(text2));
}
- public static boolean isEmpty(DiffFragment fragment) {
+ public static boolean isEmpty(@NotNull DiffFragment fragment) {
return StringUtil.length(fragment.getText1()) == 0 &&
StringUtil.length(fragment.getText2()) == 0;
}
myIsModified = modified;
}
- public void appendText1(String str) {
- assert myText1 != null;
- if (myText1Builder == null) {
- myText1Builder = new StringBuilder(myText1);
+ public void appendText1(@Nullable DiffString str) {
+ if (str == null) return;
+ if (myText1 instanceof DiffStringBuilder) {
+ ((DiffStringBuilder)myText1).append(str);
+ return;
+ }
+
+ if (myText1 instanceof DiffString) {
+ DiffString text1 = (DiffString)myText1;
+ if (DiffString.canInplaceConcatenate(text1, str)) {
+ myText1 = DiffString.concatenate(text1, str);
+ }
+ else {
+ DiffStringBuilder builder = new DiffStringBuilder(text1.length() + str.length());
+ builder.append(text1);
+ builder.append(str);
+ myText1 = builder;
+ }
+ return;
}
- myText1Builder.append(str);
+
+ throw new IllegalStateException("Bad DiffFragment: " + (myText1 != null ? myText1.getClass() : "null"));
}
- public void appendText2(String str) {
- assert myText2 != null;
- if (myText2Builder == null) {
- myText2Builder = new StringBuilder(myText2);
+ public void appendText2(@Nullable DiffString str) {
+ if (str == null) return;
+ if (myText2 instanceof DiffStringBuilder) {
+ ((DiffStringBuilder)myText2).append(str);
+ return;
}
- myText2Builder.append(str);
+
+ if (myText2 instanceof DiffString) {
+ DiffString text2 = (DiffString)myText2;
+ if (DiffString.canInplaceConcatenate(text2, str)) {
+ myText2 = DiffString.concatenate(text2, str);
+ }
+ else {
+ DiffStringBuilder builder = new DiffStringBuilder(text2.length() + str.length());
+ builder.append(text2);
+ builder.append(str);
+ myText2 = builder;
+ }
+ return;
+ }
+
+ throw new IllegalStateException("Bad DiffFragment: " + (myText2 != null ? myText2.getClass() : "null"));
}
- /**
- * null if absent
- */
- public String getText1() {
- return myText1Builder != null ? myText1Builder.toString() : myText1;
+ @Nullable
+ public DiffString getText1() {
+ if (myText1 == null) return null;
+ if (myText1 instanceof DiffString) return (DiffString)myText1;
+ if (myText1 instanceof DiffStringBuilder) return ((DiffStringBuilder)myText1).toDiffString();
+
+ throw new IllegalStateException("Bad DiffFragment: " + myText1.getClass());
}
-
- /**
- * null if absent
- */
- public String getText2() {
- return myText2Builder != null ? myText2Builder.toString() : myText2;
+
+ @Nullable
+ public DiffString getText2() {
+ if (myText2 == null) return null;
+ if (myText2 instanceof DiffString) return (DiffString)myText2;
+ if (myText2 instanceof DiffStringBuilder) return ((DiffStringBuilder)myText2).toDiffString();
+
+ throw new IllegalStateException("Bad DiffFragment: " + myText2.getClass());
}
/**
* @return true iff both texts are present and {@link #isModified()}
*/
public boolean isChange() {
- return myText1 != null && myText2 != null && isModified();
+ return (myText1 != null) && (myText2 != null) && isModified();
}
/**
* @return true iff both texts are present and not {@link #isModified()}
*/
public boolean isEqual() {
- return myText1 != null && myText2 != null && !isModified();
+ return (myText1 != null) && (myText2 != null) && !isModified();
+ }
+
+ @TestOnly
+ public static DiffFragment unchanged(@Nullable String text1, @Nullable String text2) {
+ return unchanged(DiffString.createNullable(text1), DiffString.createNullable(text2));
}
- public static DiffFragment unchanged(String text1, String text2) {
+ public static DiffFragment unchanged(@Nullable DiffString text1, @Nullable DiffString text2) {
DiffFragment result = new DiffFragment(text1, text2);
result.setModified(false);
return result;
}
public boolean isOneSide() {
- return myText1 == null || myText2 == null;
+ return (myText1 == null) || (myText2 == null);
}
}
package com.intellij.openapi.diff.impl;
import com.intellij.CommonBundle;
+import com.intellij.openapi.diff.impl.string.DiffString;
import com.intellij.openapi.diff.ex.DiffFragment;
import com.intellij.openapi.diff.impl.highlighting.FragmentSide;
import com.intellij.openapi.diff.impl.highlighting.Util;
import com.intellij.openapi.diff.impl.processing.Word;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.TextRange;
-import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.diff.Diff;
import com.intellij.util.diff.FilesTooBigForDiffException;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.annotations.TestOnly;
public abstract class ComparisonPolicy {
+ public static final ComparisonPolicy DEFAULT = new DefaultPolicy();
+ public static final ComparisonPolicy TRIM_SPACE = new TrimSpacePolicy();
+ public static final ComparisonPolicy IGNORE_SPACE = new IgnoreSpacePolicy();
+ public static final ComparisonPolicy[] COMPARISON_POLICIES = new ComparisonPolicy[]{DEFAULT, IGNORE_SPACE, TRIM_SPACE};
+
private final String myName;
protected ComparisonPolicy(final String name) {
myName = name;
}
- public DiffFragment[] buildFragments(String[] strings1, String[] strings2) throws FilesTooBigForDiffException {
+ public String getName() {
+ return myName;
+ }
+
+ @NotNull
+ public DiffFragment[] buildFragments(@NotNull DiffString[] strings1, @NotNull DiffString[] strings2) throws FilesTooBigForDiffException {
DiffFragmentBuilder builder = new DiffFragmentBuilder(strings1, strings2);
Object[] wrappers1 = getWrappers(strings1);
Object[] wrappers2 = getWrappers(strings2);
return builder.buildFragments(Util.concatEquals(change, wrappers1, wrappers2));
}
- public DiffFragment[] buildDiffFragmentsFromLines(String[] lines1, String[] lines2) throws FilesTooBigForDiffException {
+ @NotNull
+ public DiffFragment[] buildDiffFragmentsFromLines(@NotNull DiffString[] lines1, @NotNull DiffString[] lines2)
+ throws FilesTooBigForDiffException {
DiffFragmentBuilder builder = new DiffFragmentBuilder(lines1, lines2);
Object[] wrappers1 = getLineWrappers(lines1);
Object[] wrappers2 = getLineWrappers(lines2);
return builder.buildFragments(change);
}
- public static final ComparisonPolicy DEFAULT = new ComparisonPolicy(CommonBundle.message("comparison.policy.default.name")) {
+ @NotNull
+ public DiffFragment createFragment(@Nullable DiffString text1, @Nullable DiffString text2) {
+ text1 = toNull(text1);
+ text2 = toNull(text2);
+ if (text1 == null && text2 == null) return new DiffFragment(DiffString.EMPTY, DiffString.EMPTY);
+ DiffFragment result = new DiffFragment(text1, text2);
+ if (text1 != null && text2 != null) {
+ result.setModified(!getWrapper(text1).equals(getWrapper(text2)));
+ }
+ return result;
+ }
+
+ @NotNull
+ public abstract DiffFragment createFragment(@NotNull Word word1, @NotNull Word word2);
+
+ @NotNull
+ protected abstract Object[] getWrappers(@NotNull DiffString[] strings);
+
+ @NotNull
+ protected abstract Object[] getLineWrappers(@NotNull DiffString[] lines);
+
+ @NotNull
+ private Object getWrapper(@NotNull DiffString text) {
+ return getWrappers(new DiffString[]{text})[0];
+ }
+
+ private static class DefaultPolicy extends ComparisonPolicy {
+ public DefaultPolicy() {
+ super(CommonBundle.message("comparison.policy.default.name"));
+ }
+
+ @NotNull
@Override
- protected Object[] getWrappers(String[] strings) {
+ protected Object[] getWrappers(@NotNull DiffString[] strings) {
return strings;
}
+ @NotNull
@Override
- protected Object[] getLineWrappers(String[] lines) {
+ protected Object[] getLineWrappers(@NotNull DiffString[] lines) {
return lines;
}
+ @NotNull
@Override
- public DiffFragment createFragment(Word word1, Word word2) {
+ public DiffFragment createFragment(@NotNull Word word1, @NotNull Word word2) {
return createFragment(word1.getText(), word2.getText());
}
public String toString() {
return "DEFAULT";
}
- };
+ }
+
+ private static class TrimSpacePolicy extends ComparisonPolicy {
+ public TrimSpacePolicy() {
+ super(CommonBundle.message("comparison.policy.trim.space.name"));
+ }
- public static final ComparisonPolicy TRIM_SPACE = new ComparisonPolicy(CommonBundle.message("comparison.policy.trim.space.name")) {
+ @NotNull
@Override
- protected Object[] getLineWrappers(String[] lines) {
+ protected Object[] getLineWrappers(@NotNull DiffString[] lines) {
return trimStrings(lines);
}
+ @NotNull
@Override
- public DiffFragment createFragment(Word word1, Word word2) {
- String text1 = word1.getText();
- String text2 = word2.getText();
+ public DiffFragment createFragment(@NotNull Word word1, @NotNull Word word2) {
+ DiffString text1 = word1.getText();
+ DiffString text2 = word2.getText();
if (word1.isWhitespace() && word2.isWhitespace() &&
word1.atEndOfLine() && word2.atEndOfLine()) {
return DiffFragment.unchanged(text1, text2);
return createFragment(text1, text2);
}
+ @NotNull
@Override
- protected Object[] getWrappers(String[] strings) {
+ protected Object[] getWrappers(@NotNull DiffString[] strings) {
Object[] result = new Object[strings.length];
boolean atBeginning = true;
for (int i = 0; i < strings.length; i++) {
- String string = strings[i];
- String wrapper = atBeginning ? StringUtil.trimLeading(string) : string;
- if (StringUtil.endsWithChar(wrapper, '\n')) {
+ DiffString string = strings[i];
+ DiffString wrapper = atBeginning ? string.trimLeading() : string;
+ if (wrapper.endsWith('\n')) {
atBeginning = true;
- wrapper = StringUtil.trimTrailing(wrapper);
+ wrapper = wrapper.trimTrailing();
}
else {
atBeginning = false;
return result;
}
-
-
@SuppressWarnings({"HardCodedStringLiteral"})
public String toString() {
return "TRIM";
}
- };
-
- public static final ComparisonPolicy IGNORE_SPACE = new IgnoreSpacePolicy();
-
- private static String toNotNull(String text) {
- return text == null ? "" : text;
}
- protected abstract Object[] getWrappers(String[] strings);
-
- protected abstract Object[] getLineWrappers(String[] lines);
-
- protected Object[] trimStrings(String[] strings) {
- Object[] result = new Object[strings.length];
- for (int i = 0; i < strings.length; i++) {
- String string = strings[i];
- result[i] = string.trim();
- }
- return result;
- }
-
- public DiffFragment createFragment(String text1, String text2) {
- text1 = toNull(text1);
- text2 = toNull(text2);
- if (text1 == null && text2 == null) return new DiffFragment("", "");
- DiffFragment result = new DiffFragment(text1, text2);
- if (text1 != null && text2 != null) {
- result.setModified(!getWrapper(text1).equals(getWrapper(text2)));
- }
- return result;
- }
-
- private String toNull(String text1) {
- return text1 == null || text1.isEmpty() ? null : text1;
- }
-
- private Object getWrapper(String text) {
- return getWrappers(new String[]{text})[0];
- }
-
- public boolean isEqual(DiffFragment fragment) {
- if (fragment.isOneSide()) return false;
- Object[] wrappers = getLineWrappers(new String[]{fragment.getText1(), fragment.getText2()});
- return Comparing.equal(wrappers[0], wrappers[1]);
- }
-
- public Word createFormatting(String text, TextRange textRange) {
- return new Formatting(text, textRange);
- }
-
- public abstract DiffFragment createFragment(Word word1, Word word2);
-
- public String getName() {
- return myName;
- }
-
- public static final ComparisonPolicy[] COMPARISON_POLICIES = new ComparisonPolicy[]{DEFAULT, IGNORE_SPACE, TRIM_SPACE};
-
- public static ComparisonPolicy[] getAllInstances() {
- return COMPARISON_POLICIES;
- }
-
- private static class IgnoreSpacePolicy extends ComparisonPolicy implements DiffCorrection.FragmentProcessor<DiffCorrection.FragmentsCollector> {
+ private static class IgnoreSpacePolicy extends ComparisonPolicy
+ implements DiffCorrection.FragmentProcessor<DiffCorrection.FragmentsCollector> {
public IgnoreSpacePolicy() {
super(CommonBundle.message("comparison.policy.ignore.spaces.name"));
}
+ @NotNull
@Override
- protected Object[] getLineWrappers(String[] lines) {
+ protected Object[] getLineWrappers(@NotNull DiffString[] lines) {
Object[] result = new Object[lines.length];
for (int i = 0; i < lines.length; i++) {
- String line = lines[i];
+ DiffString line = lines[i];
result[i] = getWrapper(line);
}
return result;
}
+ @NotNull
@Override
- public DiffFragment[] buildFragments(String[] strings1, String[] strings2) throws FilesTooBigForDiffException {
+ public DiffFragment[] buildFragments(@NotNull DiffString[] strings1, @NotNull DiffString[] strings2)
+ throws FilesTooBigForDiffException {
DiffFragment[] fragments = super.buildFragments(strings1, strings2);
DiffCorrection.FragmentsCollector collector = new DiffCorrection.FragmentsCollector();
collector.processAll(fragments, this);
return collector.toArray();
}
- private Object getWrapper(String line) {
- StringBuilder builder = new StringBuilder(line.length());
- for (int i = 0; i < line.length(); i++) {
- char aChar = line.charAt(i);
- if (StringUtil.isWhiteSpace(aChar)) continue;
- builder.append(aChar);
- }
- return builder.toString();
+ @NotNull
+ private static Object getWrapper(@NotNull DiffString line) {
+ return line.skipSpaces();
}
+ @NotNull
@Override
- public DiffFragment createFragment(Word word1, Word word2) {
- String text1 = word1.getText();
- String text2 = word2.getText();
- return word1.isWhitespace() && word2.isWhitespace() ?
- DiffFragment.unchanged(text1, text2) :
- createFragment(text1, text2);
+ public DiffFragment createFragment(@NotNull Word word1, @NotNull Word word2) {
+ DiffString text1 = word1.getText();
+ DiffString text2 = word2.getText();
+ return word1.isWhitespace() && word2.isWhitespace() ? DiffFragment.unchanged(text1, text2) : createFragment(text1, text2);
}
+ @NotNull
@Override
- public DiffFragment createFragment(String text1, String text2) {
- String toCompare1 = toNotNull(text1);
- String toCompare2 = toNotNull(text2);
+ public DiffFragment createFragment(DiffString text1, DiffString text2) {
+ DiffString toCompare1 = toNotNull(text1);
+ DiffString toCompare2 = toNotNull(text2);
if (getWrapper(toCompare1).equals(getWrapper(toCompare2))) {
return DiffFragment.unchanged(toCompare1, toCompare2);
}
return new DiffFragment(text1, text2);
}
+ @NotNull
@Override
- protected Object[] getWrappers(String[] strings) {
+ protected Object[] getWrappers(@NotNull DiffString[] strings) {
return trimStrings(strings);
}
}
@Override
- public void process(DiffFragment fragment, DiffCorrection.FragmentsCollector collector) {
+ public void process(@NotNull DiffFragment fragment, @NotNull DiffCorrection.FragmentsCollector collector) {
if (fragment.isEqual()) {
collector.add(fragment);
return;
}
if (fragment.isOneSide()) {
FragmentSide side = FragmentSide.chooseSide(fragment);
- String text = side.getText(fragment);
- String trimed = text.trim();
+ DiffString text = side.getText(fragment);
+ DiffString trimed = text.trim();
if (trimed.isEmpty()) {
- collector.add(side.createFragment(text, "", false));
+ collector.add(side.createFragment(text, DiffString.EMPTY, false));
return;
}
}
collector.add(fragment);
}
}
+
+ @Nullable
+ private static DiffString toNull(@Nullable DiffString text1) {
+ return text1 == null || text1.isEmpty() ? null : text1;
+ }
+
+ @NotNull
+ private static DiffString toNotNull(@Nullable DiffString text) {
+ return text == null ? DiffString.EMPTY : text;
+ }
+
+ @NotNull
+ protected Object[] trimStrings(@NotNull DiffString[] strings) {
+ Object[] result = new Object[strings.length];
+ for (int i = 0; i < strings.length; i++) {
+ DiffString string = strings[i];
+ result[i] = string.trim();
+ }
+ return result;
+ }
+
+ public boolean isEqual(@NotNull DiffFragment fragment) {
+ if (fragment.isOneSide()) return false;
+ Object[] wrappers = getLineWrappers(new DiffString[]{fragment.getText1(), fragment.getText2()});
+ return Comparing.equal(wrappers[0], wrappers[1]);
+ }
+
+ @NotNull
+ public Word createFormatting(@NotNull DiffString text, @NotNull TextRange textRange) {
+ return new Formatting(text, textRange);
+ }
+
+ public static ComparisonPolicy[] getAllInstances() {
+ return COMPARISON_POLICIES;
+ }
+
+ @NotNull
+ @TestOnly
+ protected Object[] getWrappers(@NotNull String[] lines) {
+ DiffString[] unsafeStrings = new DiffString[lines.length];
+ for (int i = 0; i < lines.length; i++) {
+ unsafeStrings[i] = DiffString.createNullable(lines[i]);
+ }
+ return getWrappers(unsafeStrings);
+ }
+
+ @NotNull
+ @TestOnly
+ protected Object[] getLineWrappers(@NotNull String[] lines) {
+ DiffString[] unsafeStrings = new DiffString[lines.length];
+ for (int i = 0; i < lines.length; i++) {
+ unsafeStrings[i] = DiffString.createNullable(lines[i]);
+ }
+ return getLineWrappers(unsafeStrings);
+ }
}
package com.intellij.openapi.diff.impl;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.diff.impl.string.DiffString;
import com.intellij.openapi.diff.ex.DiffFragment;
import com.intellij.openapi.util.TextRange;
import com.intellij.util.diff.Diff;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import java.util.LinkedList;
import java.util.List;
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.diff.impl.DiffFragmentBuilder");
- private final String[] mySource1;
- private final String[] mySource2;
+ @NotNull private final DiffString[] mySource1;
+ @NotNull private final DiffString[] mySource2;
private int myLastLine1 = 1;
private int myLastLine2 = 1;
- private final List<DiffFragment> myData = new LinkedList<DiffFragment>();
+ @NotNull private final List<DiffFragment> myData = new LinkedList<DiffFragment>();
- public DiffFragmentBuilder(String[] source1, String[] source2) {
+ public DiffFragmentBuilder(@NotNull DiffString[] source1, @NotNull DiffString[] source2) {
mySource1 = source1;
mySource2 = source2;
init();
}
+ @NotNull
private List<DiffFragment> getFragments() {
return myData;
}
private void finish() {
- String text1 = null;
- String text2 = null;
+ DiffString text1 = null;
+ DiffString text2 = null;
if (myLastLine1 &l