From 3d7699241642be41e17a4bd2aa3f573e7f043f82 Mon Sep 17 00:00:00 2001 From: Eldar Abusalimov Date: Wed, 7 Mar 2018 19:54:50 +0300 Subject: [PATCH 01/22] xdebugger: (testing) Invoke Promise.getBlocking() outside write action --- .../intellij/xdebugger/XDebuggerTestUtil.java | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestUtil.java b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestUtil.java index 64247073b53d..d6d265665176 100644 --- a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestUtil.java +++ b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestUtil.java @@ -7,7 +7,6 @@ import com.intellij.execution.impl.ConsoleViewImpl; import com.intellij.icons.AllIcons; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; -import com.intellij.openapi.application.Result; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; @@ -31,15 +30,16 @@ import com.intellij.xdebugger.impl.frame.XStackFrameContainerEx; import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.concurrency.Promise; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.*; import java.util.List; +import java.util.concurrent.ExecutionException; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import static org.junit.Assert.*; @@ -65,15 +65,13 @@ public class XDebuggerTestUtil { @Nullable public static XLineBreakpoint toggleBreakpoint(Project project, VirtualFile file, int line) { - return new WriteAction() { - @Override - protected void run(@NotNull Result result) { - Promise promise = - ((XDebuggerUtilImpl)XDebuggerUtil.getInstance()).toggleAndReturnLineBreakpoint(project, file, line, false); - - promise.done(result::setResult); - } - }.execute().getResultObject(); + try { + return WriteAction.computeAndWait(() -> ((XDebuggerUtilImpl)XDebuggerUtil.getInstance()) + .toggleAndReturnLineBreakpoint(project, file, line, false)).blockingGet(TIMEOUT_MS); + } + catch (TimeoutException | ExecutionException e) { + return null; + } } public static

XBreakpoint

insertBreakpoint(final Project project, From 72d73410258055cdb982949a016b88ed10dd1392 Mon Sep 17 00:00:00 2001 From: Daniil Ovchinnikov Date: Wed, 7 Mar 2018 21:48:31 +0300 Subject: [PATCH 02/22] [groovy] remove unnecessary myIsPartOfFqn logic This case is handled in GrReferenceResolveRunnerKt#resolveReferenceExpression before even resolve processor is created. --- .../processors/GroovyResolverProcessorImpl.java | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/GroovyResolverProcessorImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/GroovyResolverProcessorImpl.java index 5b6e73d1de18..fb8bdb4ddaf9 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/GroovyResolverProcessorImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/GroovyResolverProcessorImpl.java @@ -18,11 +18,8 @@ import static org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil.collapseRefl class GroovyResolverProcessorImpl extends GroovyResolverProcessor implements GrMethodComparator.Context { - private final boolean myIsPartOfFqn; - GroovyResolverProcessorImpl(@NotNull final GrReferenceExpression ref, @NotNull EnumSet kinds, boolean forceRValue) { super(ref, kinds, null, forceRValue); - myIsPartOfFqn = ResolveUtil.isPartOfFQN(ref); } @NotNull @@ -45,13 +42,6 @@ class GroovyResolverProcessorImpl extends GroovyResolverProcessor implements GrM return candidates; } - if (myIsPartOfFqn) { - candidates = getCandidates(GroovyResolveKind.PACKAGE, GroovyResolveKind.CLASS); - if (!candidates.isEmpty()) { - return candidates; - } - } - candidates = getCandidates(GroovyResolveKind.PROPERTY); if (!candidates.isEmpty()) { return candidates.size() <= 1 ? candidates : ContainerUtil.newSmartList(candidates.get(0)); From 3bcf8658c829090b33cb3ee6c1b1fdf580d40b2a Mon Sep 17 00:00:00 2001 From: Daniil Ovchinnikov Date: Wed, 7 Mar 2018 21:49:42 +0300 Subject: [PATCH 03/22] [groovy] clean up --- .../groovy/lang/resolve/ResolveUtil.java | 35 ------------------- 1 file changed, 35 deletions(-) diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.java index 20fc5d3c0c21..ae60d10f9b1a 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.java @@ -6,7 +6,6 @@ import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; -import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.scope.ElementClassHint; import com.intellij.psi.scope.ElementClassHint.DeclarationKind; @@ -63,8 +62,6 @@ import org.jetbrains.plugins.groovy.lang.resolve.processors.*; import java.util.*; -import static com.intellij.util.containers.ContainerUtil.count; -import static com.intellij.util.containers.ContainerUtil.filter; import static org.jetbrains.plugins.groovy.lang.psi.impl.GrAnnotationUtilKt.hasAnnotation; import static org.jetbrains.plugins.groovy.lang.psi.util.PsiTreeUtilKt.treeWalkUpAndGetSingleElement; import static org.jetbrains.plugins.groovy.lang.resolve.ResolveUtilKt.getDefaultConstructor; @@ -1080,19 +1077,6 @@ public class ResolveUtil { return true; } - public static boolean isMethodCallRef(@NotNull GrReferenceExpression ref) { - final PsiElement element = PsiTreeUtil.skipParentsOfType(ref, GrReferenceExpression.class); - return element instanceof GrMethodCall; - } - - public static boolean isPartOfFQN(@NotNull GrReferenceExpression ref) { - if (ref.hasAt()) return false; - final String name = ref.getReferenceName(); - if (StringUtil.isEmpty(name)) return false; - return Character.isUpperCase(name.charAt(0)) && !isMethodCallRef(ref) || - ref.getParent() instanceof GrReferenceExpression && isPartOfFQN((GrReferenceExpression)ref.getParent()); - } - public static boolean canResolveToMethod(@NotNull GrReferenceExpression ref) { return ref.hasMemberPointer() || ref.getParent() instanceof GrMethodCall; } @@ -1107,25 +1091,6 @@ public class ResolveUtil { return true; } - @NotNull - public static List filterAccessorMethods(@NotNull List candidates) { - return filter(candidates, it -> !(it.getElement() instanceof GrAccessorMethod)); - } - - @NotNull - public static List collapseReflectedMethodsSimple(@NotNull List candidates) { - if (count(candidates, it -> it.getElement() instanceof GrReflectedMethod) < 2) return candidates; - final Set visited = ContainerUtil.newHashSet(); - return ContainerUtil.mapNotNull(candidates, result -> { - final PsiElement element = result.getElement(); - if (!(element instanceof GrReflectedMethod)) return result; - - final GrMethod baseMethod = ((GrReflectedMethod)element).getBaseMethod(); - if (!visited.add(baseMethod)) return null; - return new ElementGroovyResult<>(baseMethod); - }); - } - @NotNull public static List collapseReflectedMethods(Collection candidates) { Set visited = ContainerUtil.newHashSet(); From d196c775ed8ca7b1de943757179c54d21442f2e4 Mon Sep 17 00:00:00 2001 From: Sergey Ignatov Date: Wed, 7 Mar 2018 22:21:28 +0300 Subject: [PATCH 04/22] go to action: don't repaint popup which is already closed --- .../lang-impl/src/com/intellij/ide/actions/GotoActionAction.java | 1 - 1 file changed, 1 deletion(-) diff --git a/platform/lang-impl/src/com/intellij/ide/actions/GotoActionAction.java b/platform/lang-impl/src/com/intellij/ide/actions/GotoActionAction.java index d3b4c8f83196..4179b7757205 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/GotoActionAction.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/GotoActionAction.java @@ -241,7 +241,6 @@ public class GotoActionAction extends GotoActionBase implements DumbAware { if (aw.isAvailable()) { String id = ActionManager.getInstance().getId(aw.getAction()); KeymapPanel.addKeyboardShortcut(id, ActionShortcutRestrictions.getInstance().getForActionId(id), activeKeymap, component); - popup.repaintListImmediate(); } } } From a0b535006444dc5df78bedb0a791c2ba469e78e7 Mon Sep 17 00:00:00 2001 From: peter Date: Wed, 7 Mar 2018 21:39:50 +0100 Subject: [PATCH 05/22] an API to avoid temporary StringRef allocations while deserializing stubs --- .../src/com/intellij/psi/stubs/StubInputStream.java | 10 ++++++---- .../src/com/intellij/psi/stubs/StubOutputStream.java | 6 ++---- .../src/com/intellij/util/io/DataInputOutputUtil.java | 10 ---------- platform/util/src/com/intellij/util/io/StringRef.java | 6 ++++++ 4 files changed, 14 insertions(+), 18 deletions(-) diff --git a/platform/core-api/src/com/intellij/psi/stubs/StubInputStream.java b/platform/core-api/src/com/intellij/psi/stubs/StubInputStream.java index b351575d015e..d569d441e46f 100644 --- a/platform/core-api/src/com/intellij/psi/stubs/StubInputStream.java +++ b/platform/core-api/src/com/intellij/psi/stubs/StubInputStream.java @@ -43,14 +43,16 @@ public class StubInputStream extends DataInputStream { @Nullable public StringRef readName() throws IOException { - return DataInputOutputUtil.readNAME(this, myNameStorage); + return StringRef.fromStream(this, myNameStorage); + } + + @Nullable + public String readNameString() throws IOException { + return StringRef.stringFromStream(this, myNameStorage); } public int readVarInt() throws IOException { return DataInputOutputUtil.readINT(this); } - public String stringFromId(int id) throws IOException { - return myNameStorage.valueOf(id); - } } diff --git a/platform/core-api/src/com/intellij/psi/stubs/StubOutputStream.java b/platform/core-api/src/com/intellij/psi/stubs/StubOutputStream.java index 79fca29c3be6..3657120fdc29 100644 --- a/platform/core-api/src/com/intellij/psi/stubs/StubOutputStream.java +++ b/platform/core-api/src/com/intellij/psi/stubs/StubOutputStream.java @@ -42,14 +42,12 @@ public class StubOutputStream extends DataOutputStream { } public void writeName(@Nullable final String arg) throws IOException { - DataInputOutputUtil.writeNAME(this, arg, myNameStorage); + final int nameId = arg != null ? myNameStorage.enumerate(arg) : 0; + DataInputOutputUtil.writeINT(this, nameId); } public void writeVarInt(final int value) throws IOException { DataInputOutputUtil.writeINT(this, value); } - public int getStringId(final String value) throws IOException { - return myNameStorage.enumerate(value); - } } diff --git a/platform/util/src/com/intellij/util/io/DataInputOutputUtil.java b/platform/util/src/com/intellij/util/io/DataInputOutputUtil.java index d302cffefde2..f21b0521f2e5 100644 --- a/platform/util/src/com/intellij/util/io/DataInputOutputUtil.java +++ b/platform/util/src/com/intellij/util/io/DataInputOutputUtil.java @@ -42,16 +42,6 @@ public class DataInputOutputUtil extends DataInputOutputUtilRt { DataInputOutputUtilRt.writeINT(record, val); } - @Nullable - public static StringRef readNAME(@NotNull DataInput record, @NotNull AbstractStringEnumerator nameStore) throws IOException { - return StringRef.fromStream(record, nameStore); - } - - public static void writeNAME(@NotNull DataOutput record, @Nullable String name, @NotNull AbstractStringEnumerator nameStore) throws IOException { - final int nameId = name != null ? nameStore.enumerate(name) : 0; - writeINT(record, nameId); - } - public static long readLONG(@NotNull DataInput record) throws IOException { final int val = record.readUnsignedByte(); if (val < 192) { diff --git a/platform/util/src/com/intellij/util/io/StringRef.java b/platform/util/src/com/intellij/util/io/StringRef.java index 7cbfbecb0dbd..045aa16a2230 100644 --- a/platform/util/src/com/intellij/util/io/StringRef.java +++ b/platform/util/src/com/intellij/util/io/StringRef.java @@ -115,6 +115,12 @@ public class StringRef { return nameId != 0 ? new StringRef(nameId, store) : null; } + @Nullable + public static String stringFromStream(@NotNull DataInput in, @NotNull AbstractStringEnumerator store) throws IOException { + final int nameId = DataInputOutputUtil.readINT(in); + return nameId != 0 ? store.valueOf(nameId) : null; + } + @NotNull public static StringRef[] createArray(int count) { return count == 0 ? EMPTY_ARRAY : new StringRef[count]; From 34a8d36e3619cf186f6a36c8500539ad341a81fe Mon Sep 17 00:00:00 2001 From: peter Date: Wed, 7 Mar 2018 21:40:14 +0100 Subject: [PATCH 06/22] avoid temporary StringRef allocations while deserializing stubs --- .../src/com/intellij/psi/impl/cache/TypeInfo.java | 3 +-- .../stubs/FunctionalExpressionElementType.java | 2 +- .../psi/impl/java/stubs/JavaClassElementType.java | 14 +++++++------- .../stubs/JavaClassReferenceListElementType.java | 3 +-- .../impl/java/stubs/JavaFieldStubElementType.java | 7 +++---- .../stubs/JavaImportStatementElementType.java | 6 +++--- .../impl/java/stubs/JavaMethodElementType.java | 6 +++--- .../impl/java/stubs/JavaModuleElementType.java | 4 +--- .../impl/java/stubs/JavaNameValuePairType.java | 3 +-- ...aPackageAccessibilityStatementElementType.java | 3 +-- .../impl/java/stubs/JavaParameterElementType.java | 4 ++-- .../stubs/JavaProvidesStatementElementType.java | 2 +- .../stubs/JavaRequiresStatementElementType.java | 2 +- .../java/stubs/JavaTypeParameterElementType.java | 4 +--- .../java/stubs/JavaUsesStatementElementType.java | 3 +-- .../psi/impl/source/JavaFileElementType.java | 4 ++-- .../src/com/intellij/psi/util/QualifiedName.java | 4 +--- .../groovy/lang/psi/stubs/GrStubUtils.java | 3 +-- .../elements/GrNameValuePairElementType.java | 2 +- .../elements/GrTypeDefinitionElementType.java | 6 +++--- .../parsing/PropertyStubElementType.java | 4 +--- .../jetbrains/python/psi/PyFileElementType.java | 2 +- .../python/psi/impl/stubs/PyClassElementType.java | 9 ++++----- .../psi/impl/stubs/PyDataclassFieldStubImpl.kt | 4 ++-- .../psi/impl/stubs/PyFunctionElementType.java | 14 +++++++------- .../impl/stubs/PyImportElementElementType.java | 4 ++-- .../impl/stubs/PyNamedParameterElementType.java | 15 +++++++-------- .../psi/impl/stubs/PyNamedTupleStubImpl.java | 13 ++++++------- .../impl/stubs/PyTargetExpressionElementType.java | 11 ++++------- .../impl/stubs/PyTupleParameterElementType.java | 4 +--- .../psi/impl/stubs/PyTypingAliasStubType.java | 4 ++-- .../psi/impl/stubs/PyTypingNewTypeStubImpl.kt | 6 +++--- .../python/psi/stubs/PropertyStubStorage.java | 9 +++------ 33 files changed, 79 insertions(+), 105 deletions(-) diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/cache/TypeInfo.java b/java/java-psi-impl/src/com/intellij/psi/impl/cache/TypeInfo.java index af2087fcadc6..ffe9eed89af7 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/cache/TypeInfo.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/cache/TypeInfo.java @@ -34,7 +34,6 @@ import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import com.intellij.psi.tree.IElementType; import com.intellij.util.SmartList; -import com.intellij.util.io.StringRef; import gnu.trove.TObjectIntHashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -210,7 +209,7 @@ public class TypeInfo { boolean hasEllipsis = isSet(flags, HAS_ELLIPSIS); int frequentIndex = FREQUENT_INDEX_MASK & flags; - String text = frequentIndex == 0 ? StringRef.toString(record.readName()) : ourIndexFrequentType[frequentIndex]; + String text = frequentIndex == 0 ? record.readNameString() : ourIndexFrequentType[frequentIndex]; return new TypeInfo(text, arrayCount, hasEllipsis, PsiAnnotationStub.EMPTY_ARRAY); } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/FunctionalExpressionElementType.java b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/FunctionalExpressionElementType.java index 63786b19e237..68551865d553 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/FunctionalExpressionElementType.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/FunctionalExpressionElementType.java @@ -40,7 +40,7 @@ public abstract class FunctionalExpressionElementType deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { - return new FunctionalExpressionStub<>(parentStub, this, StringRef.toString(dataStream.readName())); + return new FunctionalExpressionStub<>(parentStub, this, dataStream.readNameString()); } @Override diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaClassElementType.java b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaClassElementType.java index a88ae4d23bfd..fee5f8f593a8 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaClassElementType.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaClassElementType.java @@ -167,16 +167,16 @@ public abstract class JavaClassElementType extends JavaStubElementType targets = StringUtil.split(dataStream.readUTFFast(), "/"); return new PsiPackageAccessibilityStatementStubImpl(parentStub, this, packageName, targets); } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaParameterElementType.java b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaParameterElementType.java index cfb776a2cac8..4357a7f3fddf 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaParameterElementType.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaParameterElementType.java @@ -78,11 +78,11 @@ public class JavaParameterElementType extends JavaStubElementType= 0 ? LanguageLevel.values()[level] : null, compiled); + String packageName = dataStream.readNameString(); + return new PsiJavaFileStubImpl(null, packageName, level >= 0 ? LanguageLevel.values()[level] : null, compiled); } @Override diff --git a/platform/core-api/src/com/intellij/psi/util/QualifiedName.java b/platform/core-api/src/com/intellij/psi/util/QualifiedName.java index f951ee5b93ab..0119919cd682 100644 --- a/platform/core-api/src/com/intellij/psi/util/QualifiedName.java +++ b/platform/core-api/src/com/intellij/psi/util/QualifiedName.java @@ -18,7 +18,6 @@ package com.intellij.psi.util; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; -import com.intellij.util.io.StringRef; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -158,8 +157,7 @@ public class QualifiedName implements Comparable { else { qName = new QualifiedName(size); for (int i = 0; i < size; i++) { - final StringRef name = dataStream.readName(); - qName.myComponents.add(name == null ? null : name.getString()); + qName.myComponents.add(dataStream.readNameString()); } } return qName; diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/GrStubUtils.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/GrStubUtils.java index ec2abc411ca2..1e986f00c3ab 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/GrStubUtils.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/GrStubUtils.java @@ -12,7 +12,6 @@ import com.intellij.psi.util.CachedValuesManager; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.DataInputOutputUtil; -import com.intellij.util.io.StringRef; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes; @@ -42,7 +41,7 @@ public class GrStubUtils { @NotNull public static String[] readStringArray(@NotNull StubInputStream dataStream) throws IOException { - return ArrayUtil.toStringArray(readSeq(dataStream, () -> StringRef.toString(dataStream.readName()))); + return ArrayUtil.toStringArray(readSeq(dataStream, () -> dataStream.readNameString())); } public static void writeNullableString(StubOutputStream dataStream, @Nullable String typeText) throws IOException { diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrNameValuePairElementType.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrNameValuePairElementType.java index 8727dcd20ea8..fe43b17a34b7 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrNameValuePairElementType.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrNameValuePairElementType.java @@ -50,7 +50,7 @@ public class GrNameValuePairElementType extends GrStubElementType { int size = dataStream.readVarInt(); names = new ArrayList<>(size); for (int i = 0; i < size; i++) { - names.add(dataStream.readName().getString()); + names.add(dataStream.readNameString()); } } return names; diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java index 48dcd73167bd..7d7cac3d55a8 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java @@ -20,7 +20,6 @@ import com.intellij.psi.PsiElement; import com.intellij.psi.stubs.*; import com.intellij.psi.util.QualifiedName; import com.intellij.util.containers.ContainerUtil; -import com.intellij.util.io.StringRef; import com.jetbrains.python.PyElementTypes; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyClassImpl; @@ -165,7 +164,7 @@ public class PyClassElementType extends PyStubElementType @NotNull public PyClassStub deserialize(@NotNull final StubInputStream dataStream, final StubElement parentStub) throws IOException { - final String name = StringRef.toString(dataStream.readName()); + final String name = dataStream.readNameString(); final int superClassCount = dataStream.readByte(); final Map superClasses = new LinkedHashMap<>(); @@ -178,10 +177,10 @@ public class PyClassElementType extends PyStubElementType final ArrayList baseClassesText = new ArrayList<>(); for (int i = 0; i < baseClassesCount; i++) { final boolean isParametrized = dataStream.readBoolean(); - final StringRef ref = dataStream.readName(); - baseClassesText.add(ref != null ? ref.getString() : null); + String ref = dataStream.readNameString(); + baseClassesText.add(ref); if (ref != null && isParametrized) { - parametrizedBaseClasses.add(ref.getString()); + parametrizedBaseClasses.add(ref); } } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyDataclassFieldStubImpl.kt b/python/src/com/jetbrains/python/psi/impl/stubs/PyDataclassFieldStubImpl.kt index dd4ec9d7d681..327009ced15a 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyDataclassFieldStubImpl.kt +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyDataclassFieldStubImpl.kt @@ -29,12 +29,12 @@ class PyDataclassFieldStubImpl private constructor(private val calleeName: Quali @Throws(IOException::class) fun deserialize(stream: StubInputStream): PyDataclassFieldStub? { - val calleeName = stream.readName() ?: return null + val calleeName = stream.readNameString() ?: return null val hasDefault = stream.readBoolean() val hasDefaultFactory = stream.readBoolean() val initValue = stream.readBoolean() - return PyDataclassFieldStubImpl(QualifiedName.fromDottedString(calleeName.string), hasDefault, hasDefaultFactory, initValue) + return PyDataclassFieldStubImpl(QualifiedName.fromDottedString(calleeName), hasDefault, hasDefaultFactory, initValue) } private fun calculateFullyQCalleeName(callee: PyReferenceExpression): QualifiedName? { diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyFunctionElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyFunctionElementType.java index 576b7e952de0..fd231845daff 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyFunctionElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyFunctionElementType.java @@ -91,22 +91,22 @@ public class PyFunctionElementType extends PyStubElementType> fields = deserializeFields(stream, stream.readVarInt()); if (calleeName == null || name == null) { @@ -107,8 +106,8 @@ public class PyNamedTupleStubImpl implements PyNamedTupleStub { } return new PyNamedTupleStubImpl( - QualifiedName.fromDottedString(calleeName.getString()), - name.getString(), + QualifiedName.fromDottedString(calleeName), + name, fields ); } @@ -177,8 +176,8 @@ public class PyNamedTupleStubImpl implements PyNamedTupleStub { final LinkedHashMap> fields = new LinkedHashMap<>(fieldsSize); for (int i = 0; i < fieldsSize; i++) { - final String name = StringRef.toString(stream.readName()); - final String type = StringRef.toString(stream.readName()); + final String name = stream.readNameString(); + final String type = stream.readNameString(); if (name != null) { fields.put(name, Optional.ofNullable(type)); diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyTargetExpressionElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyTargetExpressionElementType.java index 8a96bb310a37..93d8e7ca84af 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyTargetExpressionElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyTargetExpressionElementType.java @@ -25,7 +25,6 @@ import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.QualifiedName; -import com.intellij.util.io.StringRef; import com.jetbrains.python.PyElementTypes; import com.jetbrains.python.PyNames; import com.jetbrains.python.PythonDialectsTokenSetProvider; @@ -127,19 +126,17 @@ public class PyTargetExpressionElementType extends PyStubElementType implements Custom me.mySetter = readOne(stream); me.myDeleter = readOne(stream); // - StringRef ref = stream.readName(); - me.myDoc = ref != null? ref.getString() : null; + me.myDoc = stream.readNameString(); return me; } @@ -92,10 +90,9 @@ public class PropertyStubStorage extends PropertyBunch implements Custom @Nullable private static Maybe readOne(StubInputStream stream) throws IOException { - StringRef ref = stream.readName(); - if (ref == null) return none; + String s = stream.readNameString(); + if (s == null) return none; else { - String s = ref.getString(); if (IMPOSSIBLE_NAME.equals(s)) return unknown; else return new Maybe<>(s); } From 7f87c20288063eff2f29b6f00df2ccc5bb8c2c01 Mon Sep 17 00:00:00 2001 From: andrey zaytsev Date: Thu, 8 Mar 2018 00:38:20 +0300 Subject: [PATCH 07/22] Intentions: assert the hint is closed only when there is nothing to show in it --- .../codeInsight/daemon/impl/DaemonRespondToChangesTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/impl/DaemonRespondToChangesTest.java b/java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/impl/DaemonRespondToChangesTest.java index ce3496a5ed9c..3c9b44e0c31e 100644 --- a/java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/impl/DaemonRespondToChangesTest.java +++ b/java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/impl/DaemonRespondToChangesTest.java @@ -2293,8 +2293,9 @@ public class DaemonRespondToChangesTest extends DaemonAnalyzerTestCase { // it must be either hidden or not have that error anymore if (lastHintAfterDeletion != null) { assertFalse(lastHintBeforeDeletion.getCachedIntentions().toString(), lastHintBeforeDeletion.getCachedIntentions().getErrorFixes().stream().anyMatch(e -> e.getText().equals("Initialize variable 'var'"))); + } else { + assertEmpty(visibleHints); } - assertEmpty(visibleHints); } public void testCodeFoldingPassRestartsOnRegionUnfolding() { From 4dd92e6b117d57912e002f48f91fa166e3e40a52 Mon Sep 17 00:00:00 2001 From: "Ilya.Kazakevich" Date: Thu, 8 Mar 2018 01:18:47 +0300 Subject: [PATCH 08/22] PY-28848: Complete python modules in PySymbolFieldWithBrowseButton If we have no qualified name yet we still provide list of all possible modules (files and packages with __init__.py) found in module or project and sdk roots. There is also refactoring that adds extension methods both to VirtualFile and PsiFileSystemItem to check if one is python module. Former does not use latter because of performance. This functionality is enabled for flask, tests, and plain python script --- .../PySymbolFieldWithBrowseButton.kt | 67 ++++++++++++------- .../extensions/PsiFileSystemItemExt.kt | 10 ++- .../extensions/python/VirtualFileExt.kt | 26 +++++++ .../jetbrains/extenstions/QualifiedNameExt.kt | 16 ++++- .../psi/impl/PythonLanguageLevelPusher.java | 9 +-- .../run/PythonRunConfigurationForm.java | 6 +- 6 files changed, 98 insertions(+), 36 deletions(-) create mode 100644 python/src/com/jetbrains/extensions/python/VirtualFileExt.kt diff --git a/python/src/com/jetbrains/PySymbolFieldWithBrowseButton.kt b/python/src/com/jetbrains/PySymbolFieldWithBrowseButton.kt index 62ad01fa9f68..bc07e9dae1c2 100644 --- a/python/src/com/jetbrains/PySymbolFieldWithBrowseButton.kt +++ b/python/src/com/jetbrains/PySymbolFieldWithBrowseButton.kt @@ -20,6 +20,7 @@ import com.intellij.util.ProcessingContext import com.intellij.util.TextFieldCompletionProvider import com.intellij.util.textCompletion.TextFieldWithCompletion import com.jetbrains.extensions.getQName +import com.jetbrains.extensions.python.toPythonPsi import com.jetbrains.extenstions.ContextAnchor import com.jetbrains.extenstions.QNameResolveContext import com.jetbrains.extenstions.resolveToElement @@ -38,7 +39,7 @@ import com.jetbrains.python.psi.types.TypeEvalContext /** * Text field to enter python symbols and browse button (from [PyGotoSymbolContributor]). - * Supports auto-completion for symbol fully qualified names inside of textbox (except first symbol). + * Supports auto-completion for symbol fully qualified names inside of textbox * @param filter lambda to filter symbols * @param startFromDirectory symbols resolved against module, but may additionally be resolved against this folder if provided like in [QNameResolveContext.folderToStart] * @@ -76,39 +77,53 @@ private class PyNameCompletionProvider(private val contextAnchor: ContextAnchor, private val startFromDirectory: (() -> VirtualFile)? = null) : TextFieldCompletionProvider() { override fun addCompletionVariants(text: String, offset: Int, prefix: String, result: CompletionResultSet) { - val evalContext = TypeEvalContext.userInitiated(contextAnchor.project, null) - var name = QualifiedName.fromDottedString(text) - val resolveContext = QNameResolveContext(contextAnchor, evalContext = evalContext, allowInaccurateResult = false, - folderToStart = startFromDirectory?.invoke()) - var element = name.resolveToElement(resolveContext, stopOnFirstFail = true) - - if (element == null && name.componentCount > 1) { - name = name.removeLastComponent() - element = name.resolveToElement(resolveContext, stopOnFirstFail = true) - } - if (element == null) { - return + val lookups: Array + var name: QualifiedName? = null + if ('.' !in text) { + lookups = contextAnchor.getRoots() + .map { rootFolder -> rootFolder.children.map { it.toPythonPsi(contextAnchor.project) } } + .flatten() + .filterNotNull() + .toSet() // Unique + .map {LookupElementBuilder.create(it, it.virtualFile.nameWithoutExtension)} + .toTypedArray() } + else { - val lookups: Array = when (element) { - is PyFile -> PyModuleType(element).getVariants(element) - is PsiDirectory -> { - val init = PyUtil.turnDirIntoInit(element) as? PyFile ?: return - PyModuleType(init).getVariants(element) + - element.children.filterIsInstance(PsiFileSystemItem::class.java) - // For package we need all symbols in initpy and all filesystem children of this folder except initpy itself - .filterNot { it.name == PyNames.INIT_DOT_PY } - .map { LookupElementBuilder.create(it, it.virtualFile.nameWithoutExtension) } + val evalContext = TypeEvalContext.userInitiated(contextAnchor.project, null) + name = QualifiedName.fromDottedString(text) + val resolveContext = QNameResolveContext(contextAnchor, evalContext = evalContext, allowInaccurateResult = false, + folderToStart = startFromDirectory?.invoke()) + var element = name.resolveToElement(resolveContext, stopOnFirstFail = true) + + if (element == null && name.componentCount > 1) { + name = name.removeLastComponent() + element = name.resolveToElement(resolveContext, stopOnFirstFail = true) } - is PyTypedElement -> { - evalContext.getType(element)?.getVariants(element) ?: return + if (element == null) { + return + } + + lookups = when (element) { + is PyFile -> PyModuleType(element).getVariants(element) + is PsiDirectory -> { + val init = PyUtil.turnDirIntoInit(element) as? PyFile ?: return + PyModuleType(init).getVariants(element) + + element.children.filterIsInstance(PsiFileSystemItem::class.java) + // For package we need all symbols in initpy and all filesystem children of this folder except initpy itself + .filterNot { it.name == PyNames.INIT_DOT_PY } + .map { LookupElementBuilder.create(it, it.virtualFile.nameWithoutExtension) } + } + is PyTypedElement -> { + evalContext.getType(element)?.getVariants(element) ?: return + } + else -> return } - else -> return } result.addAllElements(lookups .filter { it.psiElement != null } .filter { filter?.invoke(it.psiElement!!) ?: true } - .map { LookupElementBuilder.create("$name.${it.lookupString}") }) + .map { if (name != null) LookupElementBuilder.create("$name.${it.lookupString}") else it }) } } diff --git a/python/src/com/jetbrains/extensions/PsiFileSystemItemExt.kt b/python/src/com/jetbrains/extensions/PsiFileSystemItemExt.kt index 4010b1fb6b5d..b40db0777f9d 100644 --- a/python/src/com/jetbrains/extensions/PsiFileSystemItemExt.kt +++ b/python/src/com/jetbrains/extensions/PsiFileSystemItemExt.kt @@ -15,8 +15,11 @@ */ package com.jetbrains.extensions +import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiFileSystemItem import com.intellij.psi.util.QualifiedName +import com.jetbrains.python.PyNames +import com.jetbrains.python.psi.PyFile import com.jetbrains.python.psi.PyPsiFacade /** @@ -26,4 +29,9 @@ import com.jetbrains.python.psi.PyPsiFacade fun PsiFileSystemItem.getQName():QualifiedName? { val name = PyPsiFacade.getInstance(this.project).findShortestImportableName(this.virtualFile, this) ?: return null return QualifiedName.fromDottedString(name) -} \ No newline at end of file +} + +/** + * @return pyfile or package + */ +fun PsiFileSystemItem.isPythonModule() = this is PyFile || (this is PsiDirectory && this.findFile(PyNames.INIT_DOT_PY) != null) \ No newline at end of file diff --git a/python/src/com/jetbrains/extensions/python/VirtualFileExt.kt b/python/src/com/jetbrains/extensions/python/VirtualFileExt.kt new file mode 100644 index 000000000000..396b66228e4d --- /dev/null +++ b/python/src/com/jetbrains/extensions/python/VirtualFileExt.kt @@ -0,0 +1,26 @@ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. +package com.jetbrains.extensions.python + +import com.intellij.openapi.fileTypes.FileTypeRegistry +import com.intellij.openapi.project.Project +import com.intellij.openapi.vfs.VirtualFile +import com.intellij.psi.PsiFileSystemItem +import com.intellij.psi.PsiManager +import com.jetbrains.python.PyNames +import com.jetbrains.python.PythonFileType + +fun VirtualFile.isPythonFile() = PythonFileType.INSTANCE == FileTypeRegistry.getInstance().getFileTypeByFileName(name) +fun VirtualFile.isPythonPackage() = isDirectory && findChild(PyNames.INIT_DOT_PY) != null +/** + * @return pyfile or package + */ +fun VirtualFile.isPythonModule() = isPythonPackage() || isPythonFile() +/** + * @return psi element if and only if vfs item is python module + */ +fun VirtualFile.toPythonPsi(project: Project): PsiFileSystemItem? { + if (!isPythonModule()) return null + val manager = PsiManager.getInstance(project) + return if (this.isDirectory) manager.findDirectory(this) else manager.findFile(this) + +} \ No newline at end of file diff --git a/python/src/com/jetbrains/extenstions/QualifiedNameExt.kt b/python/src/com/jetbrains/extenstions/QualifiedNameExt.kt index 614410fb7628..cd6d44cf3e2c 100644 --- a/python/src/com/jetbrains/extenstions/QualifiedNameExt.kt +++ b/python/src/com/jetbrains/extenstions/QualifiedNameExt.kt @@ -18,6 +18,9 @@ package com.jetbrains.extenstions import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk +import com.intellij.openapi.roots.ModuleRootManager +import com.intellij.openapi.roots.OrderRootType +import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement @@ -37,18 +40,29 @@ interface ContextAnchor { val project: Project val qualifiedNameResolveContext: PyQualifiedNameResolveContext? val scope: GlobalSearchScope + fun getRoots(): Array { + return sdk?.rootProvider?.getFiles(OrderRootType.CLASSES) ?: emptyArray() + } } -class ModuleBasedContextAnchor(module: Module) : ContextAnchor { +class ModuleBasedContextAnchor(val module: Module) : ContextAnchor { override val sdk = module.getSdk() override val project = module.project override val qualifiedNameResolveContext = fromModule(module) override val scope = module.moduleContentScope + override fun getRoots(): Array { + val manager = ModuleRootManager.getInstance(module) + return super.getRoots() + manager.contentRoots + manager.sourceRoots + } } class ProjectSdkContextAnchor(override val project: Project, override val sdk: Sdk?) : ContextAnchor { override val qualifiedNameResolveContext = sdk?.let { fromSdk(project, it) } override val scope = GlobalSearchScope.projectScope(project) //TODO: Check if project scope includes SDK + override fun getRoots(): Array { + val manager = ProjectRootManager.getInstance(project) + return super.getRoots() + manager.contentRoots + manager.contentSourceRoots + } } diff --git a/python/src/com/jetbrains/python/psi/impl/PythonLanguageLevelPusher.java b/python/src/com/jetbrains/python/psi/impl/PythonLanguageLevelPusher.java index 12f4b40fe13d..cdeac987e9c5 100644 --- a/python/src/com/jetbrains/python/psi/impl/PythonLanguageLevelPusher.java +++ b/python/src/com/jetbrains/python/psi/impl/PythonLanguageLevelPusher.java @@ -48,6 +48,7 @@ import com.intellij.util.FileContentUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.DataInputOutputUtil; import com.intellij.util.messages.MessageBus; +import com.jetbrains.extensions.python.VirtualFileExtKt; import com.jetbrains.python.PythonFileType; import com.jetbrains.python.PythonModuleTypeBase; import com.jetbrains.python.codeInsight.typing.PyTypeShed; @@ -209,19 +210,15 @@ public class PythonLanguageLevelPusher implements FilePropertyPusher element instanceof PyFile, () -> { + element -> element instanceof PsiFileSystemItem + && PsiFileSystemItemExtKt.isPythonModule((PsiFileSystemItem)element), () -> { final String workingDirectory = myCommonOptionsForm.getWorkingDirectory(); if (StringUtil.isEmpty(workingDirectory)) { return null; From 5f4af982f672d4b9e0f6b4794bf83ad8fd0a1164 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Thu, 8 Mar 2018 07:55:44 +0100 Subject: [PATCH 09/22] change level "state changed after load" from warn to debug until known cases is not fixed --- .../src/StorageBaseEx.kt | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/platform/configuration-store-impl/src/StorageBaseEx.kt b/platform/configuration-store-impl/src/StorageBaseEx.kt index 3d8d5c64654e..a06b7a82ca56 100644 --- a/platform/configuration-store-impl/src/StorageBaseEx.kt +++ b/platform/configuration-store-impl/src/StorageBaseEx.kt @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2015 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.openapi.application.ApplicationManager @@ -93,7 +79,7 @@ private class StateGetterImpl(private val component: Persisten if (ApplicationManager.getApplication().isUnitTestMode && serializedState != serializedStateAfterLoad && (serializedStateAfterLoad == null || !JDOMUtil.areElementsEqual(serializedState, serializedStateAfterLoad))) { - LOG.warn("$componentName (from ${component.javaClass.name}) state changed after load. \nOld: ${JDOMUtil.writeElement(serializedState!!)}\n\nNew: ${serializedStateAfterLoad?.let { JDOMUtil.writeElement(it) } ?: "null"}\n") + LOG.debug("$componentName (from ${component.javaClass.name}) state changed after load. \nOld: ${JDOMUtil.writeElement(serializedState!!)}\n\nNew: ${serializedStateAfterLoad?.let { JDOMUtil.writeElement(it) } ?: "null"}\n") } storage.archiveState(storageData, componentName, serializedStateAfterLoad) From 4bfaf51e7c711efb2e7c4ce6781fbf1426f2274f Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Tue, 6 Mar 2018 16:15:50 +0100 Subject: [PATCH 10/22] access to myFilesToDelete should be not static --- .../compiler/BaseCompilerTestCase.java | 7 ++- .../JsonSchemaHighlightingTest.java | 5 +-- .../src/FileBasedStorage.kt | 7 --- .../impl/LightFileTemplatesTest.java | 11 +++-- .../diff/impl/patch/PatchReaderTest.kt | 21 ++------- .../diff/impl/patch/PatchTextDetectionTest.kt | 23 ++-------- .../project/impl/ProjectOpeningTest.java | 20 ++------- .../project/impl/RecentProjectsTest.java | 22 ++-------- .../vfs/encoding/FileEncodingTest.java | 5 ++- .../testFramework/PlatformTestCase.java | 8 ++-- .../testFramework/PlatformTestUtil.java | 43 +++++++++++-------- .../openapi/vcs/DirectoryMappingListTest.java | 42 +++++++----------- .../com/intellij/vcs/test/VcsPlatformTest.kt | 4 +- 13 files changed, 75 insertions(+), 143 deletions(-) diff --git a/java/compiler/tests/com/intellij/compiler/BaseCompilerTestCase.java b/java/compiler/tests/com/intellij/compiler/BaseCompilerTestCase.java index f63247b30d18..f02e916b127b 100644 --- a/java/compiler/tests/com/intellij/compiler/BaseCompilerTestCase.java +++ b/java/compiler/tests/com/intellij/compiler/BaseCompilerTestCase.java @@ -23,7 +23,10 @@ import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.packaging.artifacts.Artifact; import com.intellij.packaging.artifacts.ArtifactManager; import com.intellij.packaging.impl.compiler.ArtifactCompileScope; -import com.intellij.testFramework.*; +import com.intellij.testFramework.ModuleTestCase; +import com.intellij.testFramework.PlatformTestUtil; +import com.intellij.testFramework.PsiTestUtil; +import com.intellij.testFramework.VfsTestUtil; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.io.TestFileSystemBuilder; import com.intellij.util.ui.UIUtil; @@ -304,7 +307,7 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase { //todo[nik] reuse code from PlatformTestCase final VirtualFile baseDir = getOrCreateProjectBaseDir(); final File moduleFile = new File(baseDir.getPath().replace('/', File.separatorChar), moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION); - PlatformTestCase.myFilesToDelete.add(moduleFile); + myFilesToDelete.add(moduleFile); return WriteAction.computeAndWait(() -> { Module module = ModuleManager.getInstance(myProject) .newModule(FileUtil.toSystemIndependentName(moduleFile.getAbsolutePath()), getModuleType().getId()); diff --git a/json/tests/test/com/jetbrains/jsonSchema/JsonSchemaHighlightingTest.java b/json/tests/test/com/jetbrains/jsonSchema/JsonSchemaHighlightingTest.java index 53642207de4a..99a155c2f476 100644 --- a/json/tests/test/com/jetbrains/jsonSchema/JsonSchemaHighlightingTest.java +++ b/json/tests/test/com/jetbrains/jsonSchema/JsonSchemaHighlightingTest.java @@ -14,7 +14,6 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; -import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.PlatformTestUtil; import com.jetbrains.jsonSchema.ide.JsonSchemaService; import com.jetbrains.jsonSchema.impl.JsonSchemaAnnotator; @@ -593,8 +592,8 @@ public class JsonSchemaHighlightingTest extends DaemonAnalyzerTestCase { doTest(file.getVirtualFile(), true, false); } - public static void registerProvider(Project project, @NotNull String schema) throws IOException { - File dir = PlatformTestCase.createTempDir("json_schema_test", true); + public void registerProvider(Project project, @NotNull String schema) throws IOException { + File dir = createTempDir("json_schema_test", true); File child = new File(dir, "schema.json"); //noinspection ResultOfMethodCallIgnored child.createNewFile(); diff --git a/platform/configuration-store-impl/src/FileBasedStorage.kt b/platform/configuration-store-impl/src/FileBasedStorage.kt index c4c1e2f4f9f2..10584400c14c 100644 --- a/platform/configuration-store-impl/src/FileBasedStorage.kt +++ b/platform/configuration-store-impl/src/FileBasedStorage.kt @@ -79,13 +79,6 @@ open class FileBasedStorage(file: Path, storage.lineSeparator = lineSeparator } - // only app level components do not use xml prolog - if (storage.roamingType == RoamingType.DISABLED && storage.isUseXmlProlog) { - if (element == null) { - - } - } - val isUseVfs = storage.isUseVfsForWrite val virtualFile = if (isUseVfs) storage.virtualFile else null if (element == null) { diff --git a/platform/platform-tests/testSrc/com/intellij/ide/fileTemplates/impl/LightFileTemplatesTest.java b/platform/platform-tests/testSrc/com/intellij/ide/fileTemplates/impl/LightFileTemplatesTest.java index c118818af7f1..9895ebf2a267 100644 --- a/platform/platform-tests/testSrc/com/intellij/ide/fileTemplates/impl/LightFileTemplatesTest.java +++ b/platform/platform-tests/testSrc/com/intellij/ide/fileTemplates/impl/LightFileTemplatesTest.java @@ -11,8 +11,8 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.JDOMUtil; +import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.testFramework.LightPlatformTestCase; -import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.PlatformTestUtil; import com.intellij.util.ArrayUtil; import org.jdom.Element; @@ -87,7 +87,7 @@ public class LightFileTemplatesTest extends LightPlatformTestCase { myTemplateManager.setTemplates(FileTemplateManager.DEFAULT_TEMPLATES_CATEGORY, Arrays.asList(myTemplateManager.getAllTemplates())); assertNotNull(myTemplateManager.getTemplate("foo.txt")); - File foo = PlatformTestCase.createTempDir("foo"); + File foo = FileUtilRt.createTempDirectory("foo", null, false); final Project project = ProjectManager.getInstance().createProject("foo", foo.getPath()); try { assertNotNull(project); @@ -95,11 +95,12 @@ public class LightFileTemplatesTest extends LightPlatformTestCase { } finally { closeProject(project); + FileUtilRt.delete(foo); } } public void testSurviveOnProjectReopen() throws Exception { - File foo = PlatformTestCase.createTempDir("foo"); + File foo = FileUtilRt.createTempDirectory("foo", null, false); Project reloaded = null; final Project project = ProjectManager.getInstance().createProject("foo", foo.getPath()); try { @@ -127,11 +128,12 @@ public class LightFileTemplatesTest extends LightPlatformTestCase { finally { closeProject(project); closeProject(reloaded); + FileUtilRt.delete(foo); } } public void testAddRemoveShared() throws Exception { - File foo = PlatformTestCase.createTempDir("foo"); + File foo = FileUtilRt.createTempDirectory("foo", null, false); final Project project = ProjectManager.getInstance().createProject("foo", foo.getPath()); try { assertThat(project).isNotNull(); @@ -169,6 +171,7 @@ public class LightFileTemplatesTest extends LightPlatformTestCase { } finally { closeProject(project); + FileUtilRt.delete(foo); } } diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/PatchReaderTest.kt b/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/PatchReaderTest.kt index 20775fef4af6..b6373161b078 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/PatchReaderTest.kt +++ b/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/PatchReaderTest.kt @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.diff.impl.patch import com.intellij.openapi.fileEditor.impl.LoadTextUtil @@ -25,7 +11,6 @@ import junit.framework.TestCase import java.io.File class PatchReaderTest : PlatformTestCase() { - private val author = VcsUserImpl("D D", "aaaa@gmail.com") private val doubleSurname = VcsUserImpl("D D-D", "aaaa@gmail.com") private val longName = VcsUserImpl("very long author-surname", "aaaa@gmail.com") @@ -99,8 +84,8 @@ class PatchReaderTest : PlatformTestCase() { private fun read(): PatchReader { val testDataPath = PlatformTestUtil.getPlatformTestDataPath() + "diff/patchReader/" + getTestName(true) - PsiTestUtil.createTestProjectStructure(myProject, myModule, testDataPath, PlatformTestCase.myFilesToDelete) - val patchPath = testDataPath + "/test.patch" + PsiTestUtil.createTestProjectStructure(myProject, myModule, testDataPath, myFilesToDelete) + val patchPath = "$testDataPath/test.patch" val patchFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(patchPath.replace(File.separatorChar, '/')) val patchContents = patchFile!!.contentsToByteArray() diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/PatchTextDetectionTest.kt b/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/PatchTextDetectionTest.kt index bdb8e8f2f833..265cc62af3bb 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/PatchTextDetectionTest.kt +++ b/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/PatchTextDetectionTest.kt @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.diff.impl.patch import com.intellij.openapi.fileEditor.impl.LoadTextUtil @@ -23,7 +9,6 @@ import com.intellij.testFramework.PsiTestUtil import java.io.File class PatchTextDetectionTest : PlatformTestCase() { - fun testClassicalContextDiff() { doTest(true) } @@ -48,16 +33,14 @@ class PatchTextDetectionTest : PlatformTestCase() { doTest(false) } - private fun doTest(expected: Boolean) { val testDataPath = PlatformTestUtil.getPlatformTestDataPath() + "diff/patchTextDetection/" + getTestName(true) - PsiTestUtil.createTestProjectStructure(myProject, myModule, testDataPath, PlatformTestCase.myFilesToDelete) - val patchPath = testDataPath + "/test.patch" + PsiTestUtil.createTestProjectStructure(myProject, myModule, testDataPath, myFilesToDelete) + val patchPath = "$testDataPath/test.patch" val patchFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(patchPath.replace(File.separatorChar, '/')) val patchContents = patchFile!!.contentsToByteArray() val patchText = LoadTextUtil.getTextByBinaryPresentation(patchContents, patchFile); assertEquals(expected, PatchReader.isPatchContent((patchText.toString()))); } - } \ No newline at end of file diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/project/impl/ProjectOpeningTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/project/impl/ProjectOpeningTest.java index 1fb1b71c7eb2..dc371579d92f 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/project/impl/ProjectOpeningTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/project/impl/ProjectOpeningTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.project.impl; import com.intellij.ide.impl.ProjectUtil; @@ -40,7 +26,7 @@ import static com.intellij.openapi.startup.StartupActivity.POST_STARTUP_ACTIVITY public class ProjectOpeningTest extends PlatformTestCase { public void testOpenProjectCancelling() throws Exception { - File foo = PlatformTestCase.createTempDir("foo"); + File foo = createTempDir("foo"); Project project = null; MyStartupActivity activity = new MyStartupActivity(); PlatformTestUtil.registerExtension(POST_STARTUP_ACTIVITY, activity, getTestRootDisposable()); @@ -58,7 +44,7 @@ public class ProjectOpeningTest extends PlatformTestCase { } public void testCancelOnLoadingModules() throws Exception { - File foo = PlatformTestCase.createTempDir("foo"); + File foo = createTempDir("foo"); Project project = null; try { ProjectManagerEx manager = ProjectManagerEx.getInstanceEx(); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/project/impl/RecentProjectsTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/project/impl/RecentProjectsTest.java index 9977c3560dfa..21648f4fef1c 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/project/impl/RecentProjectsTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/project/impl/RecentProjectsTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.project.impl; import com.intellij.ide.ProjectGroup; @@ -76,7 +62,7 @@ public class RecentProjectsTest extends PlatformTestCase { public void testTimestampForOpenProjectUpdatesWhenGetStateCalled() throws Exception { Project project = null; try { - File path = PlatformTestCase.createTempDir("z1"); + File path = createTempDir("z1"); ProjectManagerEx manager = ProjectManagerEx.getInstanceEx(); project = manager.createProject(null, path.getPath()); project.save(); @@ -129,10 +115,10 @@ public class RecentProjectsTest extends PlatformTestCase { Assert.assertEquals(Arrays.toString(groups), Arrays.toString(recentGroups.toArray())); } - private static String createAndOpenProject(String name) throws IOException, JDOMException { + private String createAndOpenProject(String name) throws IOException, JDOMException { Project project = null; try { - File path = PlatformTestCase.createTempDir(name); + File path = createTempDir(name); ProjectManagerEx manager = ProjectManagerEx.getInstanceEx(); project = manager.createProject(null, path.getPath()); project.save(); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/vfs/encoding/FileEncodingTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/vfs/encoding/FileEncodingTest.java index 863955449f36..4a360d5d0d21 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/vfs/encoding/FileEncodingTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/vfs/encoding/FileEncodingTest.java @@ -46,6 +46,7 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; @@ -159,7 +160,7 @@ public class FileEncodingTest extends PlatformTestCase implements TestDialog { FileDocumentManager.getInstance().saveAllDocuments(); byte[] savedBytes = FileUtil.loadFileBytes(file); - String saved = new String(savedBytes, CharsetToolkit.UTF8).replace("\r\n", "\n"); + String saved = new String(savedBytes, StandardCharsets.UTF_8).replace("\r\n", "\n"); String expected = (UTF8_XML_PROLOG + XML_TEST_BODY).replace("\r\n", "\n"); assertEquals(expected, saved); @@ -238,7 +239,7 @@ public class FileEncodingTest extends PlatformTestCase implements TestDialog { ""); } - private static void doHtmlTest(final String metaWithWindowsEncoding, final String metaWithUtf8Encoding) throws IOException { + private void doHtmlTest(final String metaWithWindowsEncoding, final String metaWithUtf8Encoding) throws IOException { File temp = FileUtil.createTempFile("copy", ".html"); setContentOnDisk(temp, NO_BOM, "" + metaWithWindowsEncoding + "" + diff --git a/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java b/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java index e1c55a55b9f3..423c958a70ac 100644 --- a/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java @@ -101,7 +101,7 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro protected ProjectManagerEx myProjectManager; protected Project myProject; protected Module myModule; - protected static final Collection myFilesToDelete = new THashSet<>(); + protected final Collection myFilesToDelete = new THashSet<>(); protected boolean myAssertionsInTestDetected; public static Thread ourTestThread; private static TestCase ourTestCase; @@ -745,12 +745,12 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro } @NotNull - public static File createTempDir(@NonNls final String prefix) throws IOException { + public File createTempDir(@NonNls @NotNull String prefix) throws IOException { return createTempDir(prefix, true); } @NotNull - public static File createTempDir(@NonNls final String prefix, final boolean refresh) throws IOException { + public File createTempDir(@NonNls @NotNull String prefix, final boolean refresh) throws IOException { final File tempDirectory = FileUtilRt.createTempDirectory("idea_test_" + prefix, null, false); myFilesToDelete.add(tempDirectory); if (refresh) { @@ -797,7 +797,7 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro } @NotNull - public static VirtualFile createTempFile(@NonNls @NotNull String ext, @Nullable byte[] bom, @NonNls @NotNull String content, @NotNull Charset charset) throws IOException { + public VirtualFile createTempFile(@NonNls @NotNull String ext, @Nullable byte[] bom, @NonNls @NotNull String content, @NotNull Charset charset) throws IOException { File temp = FileUtil.createTempFile("copy", "." + ext); setContentOnDisk(temp, bom, content, charset); diff --git a/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java b/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java index 9cc5b0a82985..c636a1d97c62 100644 --- a/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java +++ b/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java @@ -35,6 +35,7 @@ import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.ui.Queryable; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtilCore; @@ -771,27 +772,33 @@ public class PlatformTestUtil { } public static void assertJarFilesEqual(File file1, File file2) throws IOException { - final File tempDirectory1; - final File tempDirectory2; + final File tempDir = FileUtilRt.createTempDirectory("assert_jar_tmp", null, false); + try { + final File tempDirectory1 = new File(tempDir, "tmp1"); + final File tempDirectory2 = new File(tempDir, "tmp2"); + FileUtilRt.createDirectory(tempDirectory1); + FileUtilRt.createDirectory(tempDirectory2); - try (JarFile jarFile1 = new JarFile(file1)) { - try (JarFile jarFile2 = new JarFile(file2)) { - tempDirectory1 = PlatformTestCase.createTempDir("tmp1"); - tempDirectory2 = PlatformTestCase.createTempDir("tmp2"); - ZipUtil.extract(jarFile1, tempDirectory1, null); - ZipUtil.extract(jarFile2, tempDirectory2, null); + try (JarFile jarFile1 = new JarFile(file1)) { + try (JarFile jarFile2 = new JarFile(file2)) { + ZipUtil.extract(jarFile1, tempDirectory1, null); + ZipUtil.extract(jarFile2, tempDirectory2, null); + } } - } - final VirtualFile dirAfter = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory1); - Assert.assertNotNull(tempDirectory1.toString(), dirAfter); - final VirtualFile dirBefore = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory2); - Assert.assertNotNull(tempDirectory2.toString(), dirBefore); - getApplication().runWriteAction(() -> { - dirAfter.refresh(false, true); - dirBefore.refresh(false, true); - }); - assertDirectoriesEqual(dirAfter, dirBefore); + final VirtualFile dirAfter = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory1); + Assert.assertNotNull(tempDirectory1.toString(), dirAfter); + final VirtualFile dirBefore = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory2); + Assert.assertNotNull(tempDirectory2.toString(), dirBefore); + getApplication().runWriteAction(() -> { + dirAfter.refresh(false, true); + dirBefore.refresh(false, true); + }); + assertDirectoriesEqual(dirAfter, dirBefore); + } + finally { + FileUtilRt.delete(tempDir); + } } /** diff --git a/platform/vcs-tests/testSrc/com/intellij/openapi/vcs/DirectoryMappingListTest.java b/platform/vcs-tests/testSrc/com/intellij/openapi/vcs/DirectoryMappingListTest.java index e83e335995cf..31d92311bc74 100644 --- a/platform/vcs-tests/testSrc/com/intellij/openapi/vcs/DirectoryMappingListTest.java +++ b/platform/vcs-tests/testSrc/com/intellij/openapi/vcs/DirectoryMappingListTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs; import com.intellij.ide.startup.impl.StartupManagerImpl; @@ -31,7 +17,6 @@ import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.PsiTestUtil; import com.intellij.util.ui.UIUtil; import com.intellij.vcsUtil.VcsUtil; -import junit.framework.Assert; import org.jetbrains.annotations.NonNls; import java.io.File; @@ -73,10 +58,13 @@ public class DirectoryMappingListTest extends PlatformTestCase { @Override protected void tearDown() throws Exception { - myMappings.disposeMe(); - ((AllVcses) myVcses).dispose(); - - super.tearDown(); + try { + myMappings.disposeMe(); + ((AllVcses)myVcses).dispose(); + } + finally { + super.tearDown(); + } } public void testMappingsFilter() { @@ -139,12 +127,12 @@ public class DirectoryMappingListTest extends PlatformTestCase { for (String child : children) { myMappings.setMapping(child, "CVS"); myMappings.cleanupMappings(); - Assert.assertEquals("cleanup failed: " + child, 1, myMappings.getDirectoryMappings().size()); + assertEquals("cleanup failed: " + child, 1, myMappings.getDirectoryMappings().size()); } for (String child : children) { myMappings.setMapping(child, "CVS"); - Assert.assertEquals("cleanup failed: " + child, 1, myMappings.getDirectoryMappings().size()); + assertEquals("cleanup failed: " + child, 1, myMappings.getDirectoryMappings().size()); } } @@ -160,7 +148,7 @@ public class DirectoryMappingListTest extends PlatformTestCase { for (String child : children) { myMappings.setMapping(child, "CVS"); myMappings.cleanupMappings(); - Assert.assertEquals("cleanup failed: " + child, 1, myMappings.getDirectoryMappings().size()); + assertEquals("cleanup failed: " + child, 1, myMappings.getDirectoryMappings().size()); } } @@ -180,14 +168,14 @@ public class DirectoryMappingListTest extends PlatformTestCase { for (int i = 0; i < children.length; i++) { String child = children[i]; final VirtualFile vf = lfs.refreshAndFindFileByIoFile(new File(child)); - Assert.assertNotNull(vf); + assertNotNull(vf); final VcsDirectoryMapping mapping = myMappings.getMappingFor(vf); - Assert.assertNotNull(mapping); - Assert.assertEquals(awaitedVcsNames[i], mapping.getVcs()); + assertNotNull(mapping); + assertEquals(awaitedVcsNames[i], mapping.getVcs()); } } - private static void createFiles(final String[] paths) { + private void createFiles(final String[] paths) { for (String path : paths) { final File file = new File(FileUtil.toSystemDependentName(path)); assert file.mkdirs() || file.isDirectory() : file; diff --git a/platform/vcs-tests/testSrc/com/intellij/vcs/test/VcsPlatformTest.kt b/platform/vcs-tests/testSrc/com/intellij/vcs/test/VcsPlatformTest.kt index c759b501245d..ebe649e2754b 100644 --- a/platform/vcs-tests/testSrc/com/intellij/vcs/test/VcsPlatformTest.kt +++ b/platform/vcs-tests/testSrc/com/intellij/vcs/test/VcsPlatformTest.kt @@ -35,7 +35,6 @@ import java.util.concurrent.Future import java.util.concurrent.TimeUnit abstract class VcsPlatformTest : PlatformTestCase() { - protected lateinit var testRoot: File protected lateinit var testRootFile: VirtualFile protected lateinit var projectRoot: VirtualFile @@ -50,8 +49,7 @@ abstract class VcsPlatformTest : PlatformTestCase() { @Throws(Exception::class) override fun setUp() { - testRoot = File(FileUtil.getTempDirectory(), "root-${Integer.toHexString(Random().nextInt())}") - PlatformTestCase.myFilesToDelete.add(testRoot) + testRoot = createTempDir("root-${Integer.toHexString(Random().nextInt())}", false) checkTestRootIsEmpty(testRoot) runInEdtAndWait { super@VcsPlatformTest.setUp() } From c44e1c3e42905d0e0571e3a10625d1c20b03fb2c Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Tue, 6 Mar 2018 16:38:26 +0100 Subject: [PATCH 11/22] reduce direct usages of myFilesToDelete --- .../javadoc/JavaDocInfoGeneratorTest.java | 9 +++-- .../dependencies/CyclicDependenciesTest.java | 18 ++-------- .../UsagesInAnalyzingDependenciesTest.java | 18 ++-------- .../execution/BaseConfigurationTestCase.java | 33 +++++-------------- .../intellij/java/psi/AddClassToFileTest.java | 20 ++--------- .../java/psi/ArrayIndexOutOfBoundsTest.java | 18 ++-------- .../java/psi/CoreJavaFileManagerTest.java | 19 ++--------- .../java/psi/ModifyAnnotationsTest.java | 18 ++-------- .../java/psi/PsiConcurrencyStressTest.java | 19 ++--------- .../java/psi/Src15RepositoryUseTest.java | 18 ++-------- .../java/psi/SrcRepositoryUseTest.java | 18 ++-------- .../java/psi/impl/cache/impl/IdCacheTest.java | 18 ++-------- .../java/psi/search/FindUsages15Test.java | 18 ++-------- .../java/psi/search/FindUsagesTest.java | 20 ++--------- .../java/psi/search/PlainTextUsagesTest.java | 2 +- .../java/psi/search/UpdateCacheTest.java | 2 +- .../java/refactoring/CopyClassTest.java | 22 +++---------- .../intellij/java/refactoring/CopyTest.java | 24 +++----------- .../refactoring/ExtractSuperClassTest.java | 22 +++---------- .../inline/InlineMethodMultifileTest.java | 18 ++-------- .../InlineToAnonymousClassMultifileTest.java | 18 ++-------- .../SmartPsiElementPointersTest.java | 6 ++-- .../ConvertingOldDetectionExcludesTest.java | 24 ++++---------- .../diff/impl/patch/ApplyPatchTest.java | 19 ++--------- .../vfs/encoding/FileEncodingTest.java | 7 ++-- .../psi/search/GlobalSearchScopeTest.java | 19 ++--------- .../testFramework/PlatformTestCase.java | 17 ++++++++++ .../committed/CommittedChangesCacheTest.java | 17 +--------- .../uiDesigner/binding/FormEnumUsageTest.java | 18 ++-------- .../binding/FormPropertyUsageTest.java | 18 ++-------- .../make/FormSourceCodeGeneratorTest.java | 18 ++-------- 31 files changed, 95 insertions(+), 440 deletions(-) diff --git a/java/java-tests/testSrc/com/intellij/java/codeInsight/javadoc/JavaDocInfoGeneratorTest.java b/java/java-tests/testSrc/com/intellij/java/codeInsight/javadoc/JavaDocInfoGeneratorTest.java index 4314edf0ec28..a932e01897f2 100644 --- a/java/java-tests/testSrc/com/intellij/java/codeInsight/javadoc/JavaDocInfoGeneratorTest.java +++ b/java/java-tests/testSrc/com/intellij/java/codeInsight/javadoc/JavaDocInfoGeneratorTest.java @@ -1,6 +1,4 @@ -/* - * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.codeInsight.javadoc; import com.intellij.JavaTestUtil; @@ -31,6 +29,7 @@ import org.intellij.lang.annotations.Flow; import java.io.File; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; @@ -271,7 +270,7 @@ public class JavaDocInfoGeneratorTest extends CodeInsightTestCase { public void testPackageInfo() throws Exception { final String path = JavaTestUtil.getJavaTestDataPath() + TEST_DATA_FOLDER; final String packageInfo = path + getTestName(true); - PsiTestUtil.createTestProjectStructure(myProject, myModule, path, myFilesToDelete); + createTestProjectStructure(path); PsiPackage psiPackage = JavaPsiFacade.getInstance(getProject()).findPackage(getTestName(true)); final String info = JavaDocumentationProvider.generateExternalJavadoc(psiPackage, (List)null); String htmlText = FileUtil.loadFile(new File(packageInfo + File.separator + "packageInfo.html")); @@ -323,7 +322,7 @@ public class JavaDocInfoGeneratorTest extends CodeInsightTestCase { PsiDirectory dir = (PsiDirectory)psiClass.getParent().getParent(); PsiFile htmlFile = dir.findFile(psiClass.getName() + ".html"); assertNotNull(htmlFile); - assertEquals(StringUtil.convertLineSeparators(new String(htmlFile.getVirtualFile().contentsToByteArray(), "UTF-8").trim()), + assertEquals(StringUtil.convertLineSeparators(new String(htmlFile.getVirtualFile().contentsToByteArray(), StandardCharsets.UTF_8).trim()), replaceEnvironmentDependentContent(doc)); } diff --git a/java/java-tests/testSrc/com/intellij/java/dependencies/CyclicDependenciesTest.java b/java/java-tests/testSrc/com/intellij/java/dependencies/CyclicDependenciesTest.java index fa6596bdc224..5b849a6bc1d2 100644 --- a/java/java-tests/testSrc/com/intellij/java/dependencies/CyclicDependenciesTest.java +++ b/java/java-tests/testSrc/com/intellij/java/dependencies/CyclicDependenciesTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.dependencies; import com.intellij.JavaTestUtil; @@ -34,7 +20,7 @@ public class CyclicDependenciesTest extends PsiTestCase { String root = JavaTestUtil.getJavaTestDataPath() + "/dependencies/cycle/" + getTestName(true); PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - PsiTestUtil.createTestProjectStructure(myProject, myModule, root, myFilesToDelete); + createTestProjectStructure(root); } public void testT1() { diff --git a/java/java-tests/testSrc/com/intellij/java/dependencies/UsagesInAnalyzingDependenciesTest.java b/java/java-tests/testSrc/com/intellij/java/dependencies/UsagesInAnalyzingDependenciesTest.java index f216f316d167..f8b98c2a8a6c 100644 --- a/java/java-tests/testSrc/com/intellij/java/dependencies/UsagesInAnalyzingDependenciesTest.java +++ b/java/java-tests/testSrc/com/intellij/java/dependencies/UsagesInAnalyzingDependenciesTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.dependencies; import com.intellij.JavaTestUtil; @@ -48,7 +34,7 @@ public class UsagesInAnalyzingDependenciesTest extends PsiTestCase { String root = JavaTestUtil.getJavaTestDataPath() + "/dependencies/search/" + getTestName(true); PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - PsiTestUtil.createTestProjectStructure(myProject, myModule, root, myFilesToDelete); + createTestProjectStructure( root); } @SuppressWarnings("ConstantConditions") diff --git a/java/java-tests/testSrc/com/intellij/java/execution/BaseConfigurationTestCase.java b/java/java-tests/testSrc/com/intellij/java/execution/BaseConfigurationTestCase.java index 2e1d68297c2a..19c216a7305f 100644 --- a/java/java-tests/testSrc/com/intellij/java/execution/BaseConfigurationTestCase.java +++ b/java/java-tests/testSrc/com/intellij/java/execution/BaseConfigurationTestCase.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.execution; import com.intellij.execution.Location; @@ -51,19 +37,16 @@ import java.util.ArrayList; import java.util.List; public abstract class BaseConfigurationTestCase extends IdeaTestCase { - protected TempFiles myTempFiles; private final List myModulesToDispose = new ArrayList<>(); - @Override - protected void setUp() throws Exception { - super.setUp(); - myTempFiles = new TempFiles(myFilesToDelete); - } - @Override protected void tearDown() throws Exception { - myModulesToDispose.clear(); - super.tearDown(); + try { + myModulesToDispose.clear(); + } + finally { + super.tearDown(); + } } protected void addModule(String path) { @@ -101,7 +84,7 @@ public abstract class BaseConfigurationTestCase extends IdeaTestCase { } private Module createTempModule() { - return createTempModule(myTempFiles, myProject); + return createTempModule(getTempDir(), myProject); } @NotNull diff --git a/java/java-tests/testSrc/com/intellij/java/psi/AddClassToFileTest.java b/java/java-tests/testSrc/com/intellij/java/psi/AddClassToFileTest.java index 7713ed1193c6..128886831934 100644 --- a/java/java-tests/testSrc/com/intellij/java/psi/AddClassToFileTest.java +++ b/java/java-tests/testSrc/com/intellij/java/psi/AddClassToFileTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.psi; import com.intellij.ide.highlighter.JavaFileType; @@ -30,7 +16,7 @@ import com.intellij.testFramework.PsiTestUtil; @PlatformTestCase.WrapInCommand public class AddClassToFileTest extends PsiTestCase{ public void test() throws Exception { - VirtualFile root = PsiTestUtil.createTestProjectStructure(myProject, myModule, myFilesToDelete); + VirtualFile root = createTestProjectStructure(); PsiDirectory dir = myPsiManager.findDirectory(root); assertNotNull(dir); PsiFile file = WriteAction.compute(() -> dir.createFile("AAA.java")); @@ -44,7 +30,7 @@ public class AddClassToFileTest extends PsiTestCase{ } public void testFileModified() throws Exception { - VirtualFile root = PsiTestUtil.createTestProjectStructure(myProject, myModule, myFilesToDelete); + VirtualFile root = createTestProjectStructure(); VirtualFile pkg = createChildDirectory(root, "foo"); PsiDirectory dir = myPsiManager.findDirectory(pkg); assertNotNull(dir); diff --git a/java/java-tests/testSrc/com/intellij/java/psi/ArrayIndexOutOfBoundsTest.java b/java/java-tests/testSrc/com/intellij/java/psi/ArrayIndexOutOfBoundsTest.java index bf9876e49082..befc0fc77f53 100644 --- a/java/java-tests/testSrc/com/intellij/java/psi/ArrayIndexOutOfBoundsTest.java +++ b/java/java-tests/testSrc/com/intellij/java/psi/ArrayIndexOutOfBoundsTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.psi; import com.intellij.JavaTestUtil; @@ -49,7 +35,7 @@ public class ArrayIndexOutOfBoundsTest extends PsiTestCase { String root = JavaTestUtil.getJavaTestDataPath() + "/psi/arrayIndexOutOfBounds/src"; PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - myProjectRoot = PsiTestUtil.createTestProjectStructure(myProject, myModule, root, myFilesToDelete); + myProjectRoot = createTestProjectStructure(root); } public void testSCR10930() { diff --git a/java/java-tests/testSrc/com/intellij/java/psi/CoreJavaFileManagerTest.java b/java/java-tests/testSrc/com/intellij/java/psi/CoreJavaFileManagerTest.java index d2be989b82eb..4de2b9a3e145 100644 --- a/java/java-tests/testSrc/com/intellij/java/psi/CoreJavaFileManagerTest.java +++ b/java/java-tests/testSrc/com/intellij/java/psi/CoreJavaFileManagerTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.psi; import com.intellij.core.CoreJavaFileManager; @@ -25,7 +11,6 @@ import com.intellij.psi.PsiFileFactory; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.PsiTestCase; -import com.intellij.testFramework.PsiTestUtil; import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NotNull; @@ -189,7 +174,7 @@ public class CoreJavaFileManagerTest extends PsiTestCase { @NotNull private CoreJavaFileManager configureManager(@Language("JAVA") @NotNull String text, @NotNull String className) throws Exception { - VirtualFile root = PsiTestUtil.createTestProjectStructure(myProject, myModule, myFilesToDelete); + VirtualFile root = createTestProjectStructure(); VirtualFile pkg = createChildDirectory(root, "foo"); PsiDirectory dir = myPsiManager.findDirectory(pkg); assertNotNull(dir); diff --git a/java/java-tests/testSrc/com/intellij/java/psi/ModifyAnnotationsTest.java b/java/java-tests/testSrc/com/intellij/java/psi/ModifyAnnotationsTest.java index b70c66665c5e..4cd33e22b5e9 100644 --- a/java/java-tests/testSrc/com/intellij/java/psi/ModifyAnnotationsTest.java +++ b/java/java-tests/testSrc/com/intellij/java/psi/ModifyAnnotationsTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.psi; import com.intellij.JavaTestUtil; @@ -38,7 +24,7 @@ public class ModifyAnnotationsTest extends PsiTestCase { String root = JavaTestUtil.getJavaTestDataPath() + "/psi/repositoryUse/modifyAnnotations"; PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - PsiTestUtil.createTestProjectStructure(myProject, myModule, root, myFilesToDelete); + createTestProjectStructure( root); } public void testReplaceAnnotation() { diff --git a/java/java-tests/testSrc/com/intellij/java/psi/PsiConcurrencyStressTest.java b/java/java-tests/testSrc/com/intellij/java/psi/PsiConcurrencyStressTest.java index 30e98c6f8bb1..66f1f0f80e0b 100644 --- a/java/java-tests/testSrc/com/intellij/java/psi/PsiConcurrencyStressTest.java +++ b/java/java-tests/testSrc/com/intellij/java/psi/PsiConcurrencyStressTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. /* * @author max @@ -24,7 +10,6 @@ import com.intellij.codeInsight.daemon.impl.DaemonProgressIndicator; import com.intellij.codeInsight.daemon.impl.HighlightVisitor; import com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.application.Result; import com.intellij.openapi.application.ex.PathManagerEx; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Document; @@ -61,7 +46,7 @@ public class PsiConcurrencyStressTest extends DaemonAnalyzerTestCase { LanguageLevelProjectExtension.getInstance(myProject).setLanguageLevel(LanguageLevel.JDK_1_5); String root = PathManagerEx.getTestDataPath() + "/psi/repositoryUse/src"; PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - PsiTestUtil.createTestProjectStructure(myProject, myModule, root, myFilesToDelete); + createTestProjectStructure( root); } @Override diff --git a/java/java-tests/testSrc/com/intellij/java/psi/Src15RepositoryUseTest.java b/java/java-tests/testSrc/com/intellij/java/psi/Src15RepositoryUseTest.java index 358de60e8fee..f4da2e2c5251 100644 --- a/java/java-tests/testSrc/com/intellij/java/psi/Src15RepositoryUseTest.java +++ b/java/java-tests/testSrc/com/intellij/java/psi/Src15RepositoryUseTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.psi; import com.intellij.openapi.application.ex.PathManagerEx; @@ -50,7 +36,7 @@ public class Src15RepositoryUseTest extends PsiTestCase { LanguageLevelProjectExtension.getInstance(myProject).setLanguageLevel(LanguageLevel.JDK_1_5); String root = PathManagerEx.getTestDataPath() + "/psi/repositoryUse/src15"; PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - PsiTestUtil.createTestProjectStructure(myProject, myModule, root, myFilesToDelete); + createTestProjectStructure( root); } @Override diff --git a/java/java-tests/testSrc/com/intellij/java/psi/SrcRepositoryUseTest.java b/java/java-tests/testSrc/com/intellij/java/psi/SrcRepositoryUseTest.java index a71d66f0ddd3..eb0896df833e 100644 --- a/java/java-tests/testSrc/com/intellij/java/psi/SrcRepositoryUseTest.java +++ b/java/java-tests/testSrc/com/intellij/java/psi/SrcRepositoryUseTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.psi; import com.intellij.openapi.application.ApplicationManager; @@ -60,7 +46,7 @@ public class SrcRepositoryUseTest extends PsiTestCase{ LanguageLevelProjectExtension.getInstance(myProject).setLanguageLevel(LanguageLevel.JDK_1_5); String root = PathManagerEx.getTestDataPath() + "/psi/repositoryUse/src"; PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - PsiTestUtil.createTestProjectStructure(myProject, myModule, root, myFilesToDelete); + createTestProjectStructure( root); } public void testGetClasses(){ diff --git a/java/java-tests/testSrc/com/intellij/java/psi/impl/cache/impl/IdCacheTest.java b/java/java-tests/testSrc/com/intellij/java/psi/impl/cache/impl/IdCacheTest.java index 3ffd68ba8664..838348d84a4a 100644 --- a/java/java-tests/testSrc/com/intellij/java/psi/impl/cache/impl/IdCacheTest.java +++ b/java/java-tests/testSrc/com/intellij/java/psi/impl/cache/impl/IdCacheTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.psi.impl.cache.impl; import com.intellij.JavaTestUtil; @@ -49,7 +35,7 @@ public class IdCacheTest extends CodeInsightTestCase{ String root = JavaTestUtil.getJavaTestDataPath()+ "/psi/impl/cache/"; PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - myRootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, root, myFilesToDelete); + myRootDir = createTestProjectStructure(root); myCacheFile = FileUtil.createTempFile("cache", ""); myCacheFile.delete(); diff --git a/java/java-tests/testSrc/com/intellij/java/psi/search/FindUsages15Test.java b/java/java-tests/testSrc/com/intellij/java/psi/search/FindUsages15Test.java index 3040ced85216..ae15933720d1 100644 --- a/java/java-tests/testSrc/com/intellij/java/psi/search/FindUsages15Test.java +++ b/java/java-tests/testSrc/com/intellij/java/psi/search/FindUsages15Test.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.psi.search; import com.intellij.JavaTestUtil; @@ -37,7 +23,7 @@ public class FindUsages15Test extends PsiTestCase{ LanguageLevelProjectExtension.getInstance(myJavaFacade.getProject()).setLanguageLevel(LanguageLevel.JDK_1_5); String root = JavaTestUtil.getJavaTestDataPath() + "/psi/search/findUsages15/" + getTestName(true); PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - PsiTestUtil.createTestProjectStructure(myProject, myModule, root, myFilesToDelete); + createTestProjectStructure(root); } public void testEnumConstructor() { diff --git a/java/java-tests/testSrc/com/intellij/java/psi/search/FindUsagesTest.java b/java/java-tests/testSrc/com/intellij/java/psi/search/FindUsagesTest.java index 0a47a215010e..769203fdbf40 100644 --- a/java/java-tests/testSrc/com/intellij/java/psi/search/FindUsagesTest.java +++ b/java/java-tests/testSrc/com/intellij/java/psi/search/FindUsagesTest.java @@ -1,24 +1,9 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.psi.search; import com.intellij.JavaTestUtil; import com.intellij.find.findUsages.JavaFindUsagesHandler; import com.intellij.find.findUsages.JavaFindUsagesHandlerFactory; -import com.intellij.openapi.application.Result; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.module.ModifiableModuleModel; @@ -40,7 +25,6 @@ import com.intellij.testFramework.fixtures.TempDirTestFixture; import com.intellij.usageView.UsageInfo; import com.intellij.util.Processor; import com.intellij.util.containers.IntArrayList; -import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collection; @@ -54,7 +38,7 @@ public class FindUsagesTest extends PsiTestCase{ String root = JavaTestUtil.getJavaTestDataPath() + "/psi/search/findUsages/" + getTestName(true); PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - PsiTestUtil.createTestProjectStructure(myProject, myModule, root, myFilesToDelete); + createTestProjectStructure(root); } public void testOverloadConstructors() { diff --git a/java/java-tests/testSrc/com/intellij/java/psi/search/PlainTextUsagesTest.java b/java/java-tests/testSrc/com/intellij/java/psi/search/PlainTextUsagesTest.java index 8695ed990119..46bbb9c29ce8 100644 --- a/java/java-tests/testSrc/com/intellij/java/psi/search/PlainTextUsagesTest.java +++ b/java/java-tests/testSrc/com/intellij/java/psi/search/PlainTextUsagesTest.java @@ -27,7 +27,7 @@ public class PlainTextUsagesTest extends PsiTestCase { String root = JavaTestUtil.getJavaTestDataPath() + "/psi/search/plainTextUsages/" + getTestName(true); PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - PsiTestUtil.createTestProjectStructure(myProject, myModule, root, myFilesToDelete); + createTestProjectStructure( root); } public void testSimple() { diff --git a/java/java-tests/testSrc/com/intellij/java/psi/search/UpdateCacheTest.java b/java/java-tests/testSrc/com/intellij/java/psi/search/UpdateCacheTest.java index 383111bc19fc..e12fa1193d9c 100644 --- a/java/java-tests/testSrc/com/intellij/java/psi/search/UpdateCacheTest.java +++ b/java/java-tests/testSrc/com/intellij/java/psi/search/UpdateCacheTest.java @@ -58,7 +58,7 @@ public class UpdateCacheTest extends PsiTestCase { setUpModule(); final String root = JavaTestUtil.getJavaTestDataPath() + "/psi/search/updateCache"; - PsiTestUtil.createTestProjectStructure(myProject, myModule, root, myFilesToDelete); + createTestProjectStructure( root); setUpJdk(); diff --git a/java/java-tests/testSrc/com/intellij/java/refactoring/CopyClassTest.java b/java/java-tests/testSrc/com/intellij/java/refactoring/CopyClassTest.java index a6ec2ed3490c..be7ef620e487 100644 --- a/java/java-tests/testSrc/com/intellij/java/refactoring/CopyClassTest.java +++ b/java/java-tests/testSrc/com/intellij/java/refactoring/CopyClassTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.refactoring; import com.intellij.JavaTestUtil; @@ -68,7 +54,7 @@ public class CopyClassTest extends CodeInsightTestCase { String root = JavaTestUtil.getJavaTestDataPath() + "/refactoring/copyClass/" + getTestName(true); PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - myRootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, root, myFilesToDelete); + myRootDir = createTestProjectStructure(root); performAction(oldName, copyName); @@ -107,7 +93,7 @@ public class CopyClassTest extends CodeInsightTestCase { String root = JavaTestUtil.getJavaTestDataPath() + "/refactoring/copyClass/multifile/" + getTestName(true); String rootBefore = root + "/before"; PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete); + VirtualFile rootDir = createTestProjectStructure(rootBefore); final HashMap map = new HashMap<>(); final VirtualFile sourceDir = rootDir.findChild("p1"); @@ -143,7 +129,7 @@ public class CopyClassTest extends CodeInsightTestCase { String root = JavaTestUtil.getJavaTestDataPath() + "/refactoring/copyClass/multifile/" + getTestName(true); String rootBefore = root + "/before"; PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete); + VirtualFile rootDir = createTestProjectStructure(rootBefore); final VirtualFile targetVDir = rootDir.findChild("p2"); final PsiDirectory sourceP1Dir = myPsiManager.findDirectory(rootDir.findChild("p1")); diff --git a/java/java-tests/testSrc/com/intellij/java/refactoring/CopyTest.java b/java/java-tests/testSrc/com/intellij/java/refactoring/CopyTest.java index eaeeed50db00..b552a9706bc3 100644 --- a/java/java-tests/testSrc/com/intellij/java/refactoring/CopyTest.java +++ b/java/java-tests/testSrc/com/intellij/java/refactoring/CopyTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.refactoring; import com.intellij.JavaTestUtil; @@ -41,7 +27,7 @@ public class CopyTest extends CodeInsightTestCase { private void doTest() throws Exception { String rootBefore = getRoot(); PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete); + createTestProjectStructure(rootBefore); PsiPackage pack1 = myJavaFacade.findPackage("pack1"); PsiPackage pack2 = myJavaFacade.findPackage("pack2"); assertTrue(CopyHandler.canCopy(new PsiElement[]{pack1.getDirectories()[0], pack2.getDirectories()[0]})); @@ -50,7 +36,7 @@ public class CopyTest extends CodeInsightTestCase { public void testMultipleClasses() throws Exception { String rootBefore = getRoot(); PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - final VirtualFile root = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete); + final VirtualFile root = createTestProjectStructure(rootBefore); final PsiClass aClass = myJavaFacade.findClass("pack1.Klass"); assertNotNull(aClass); @@ -72,7 +58,7 @@ public class CopyTest extends CodeInsightTestCase { public void testMultipleFiles() throws Exception { String rootBefore = getRoot(); PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - final VirtualFile root = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete); + final VirtualFile root = createTestProjectStructure(rootBefore); final VirtualFile first = root.findFileByRelativePath("from/1.txt"); assertNotNull(first); @@ -97,7 +83,7 @@ public class CopyTest extends CodeInsightTestCase { public void testPackageInfo() throws Exception { String rootBefore = getRoot(); PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - final VirtualFile root = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete); + final VirtualFile root = createTestProjectStructure(rootBefore); final VirtualFile first = root.findFileByRelativePath("from/package-info.java"); assertNotNull(first); diff --git a/java/java-tests/testSrc/com/intellij/java/refactoring/ExtractSuperClassTest.java b/java/java-tests/testSrc/com/intellij/java/refactoring/ExtractSuperClassTest.java index 147cf4cf8c6d..2557211c67ac 100644 --- a/java/java-tests/testSrc/com/intellij/java/refactoring/ExtractSuperClassTest.java +++ b/java/java-tests/testSrc/com/intellij/java/refactoring/ExtractSuperClassTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.refactoring; import com.intellij.JavaTestUtil; @@ -34,7 +20,6 @@ import com.intellij.refactoring.util.DocCommentPolicy; import com.intellij.refactoring.util.classMembers.MemberInfo; import com.intellij.testFramework.IdeaTestUtil; import com.intellij.testFramework.PsiTestUtil; -import java.util.HashSet; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.NonNls; @@ -42,6 +27,7 @@ import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashSet; /** * @author yole @@ -139,7 +125,7 @@ public class ExtractSuperClassTest extends RefactoringTestCase { public void testAnonymClass() throws Exception { String rootBefore = getRoot() + "/before"; PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk14()); - final VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete); + final VirtualFile rootDir = createTestProjectStructure(rootBefore); PsiClass psiClass = myJavaFacade.findClass("Test", ProjectScope.getAllScope(myProject)); assertNotNull(psiClass); final PsiField[] fields = psiClass.getFields(); @@ -192,7 +178,7 @@ public class ExtractSuperClassTest extends RefactoringTestCase { RefactoringTestUtil.MemberDescriptor... membersToFind) throws Exception { String rootBefore = getRoot() + "/before"; PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk14()); - final VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete); + final VirtualFile rootDir = createTestProjectStructure(rootBefore); PsiClass psiClass = myJavaFacade.findClass(className, ProjectScope.getAllScope(myProject)); assertNotNull(psiClass); final MemberInfo[] members = RefactoringTestUtil.findMembers(psiClass, membersToFind); diff --git a/java/java-tests/testSrc/com/intellij/java/refactoring/inline/InlineMethodMultifileTest.java b/java/java-tests/testSrc/com/intellij/java/refactoring/inline/InlineMethodMultifileTest.java index 200de3fc9b5b..0e0b93566e04 100644 --- a/java/java-tests/testSrc/com/intellij/java/refactoring/inline/InlineMethodMultifileTest.java +++ b/java/java-tests/testSrc/com/intellij/java/refactoring/inline/InlineMethodMultifileTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.refactoring.inline; import com.intellij.JavaTestUtil; @@ -55,7 +41,7 @@ public class InlineMethodMultifileTest extends RefactoringTestCase { private void doTest(String className, String methodName) throws Exception { String rootBefore = getRoot() + "/before"; PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - final VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete); + final VirtualFile rootDir = createTestProjectStructure(rootBefore); PsiClass aClass = myJavaFacade.findClass(className, ProjectScope.getAllScope(myProject)); assertTrue(aClass != null); PsiElement element = aClass.findMethodsByName(methodName, false)[0]; diff --git a/java/java-tests/testSrc/com/intellij/java/refactoring/inline/InlineToAnonymousClassMultifileTest.java b/java/java-tests/testSrc/com/intellij/java/refactoring/inline/InlineToAnonymousClassMultifileTest.java index 248c1ccaf5cd..a50c868324bf 100644 --- a/java/java-tests/testSrc/com/intellij/java/refactoring/inline/InlineToAnonymousClassMultifileTest.java +++ b/java/java-tests/testSrc/com/intellij/java/refactoring/inline/InlineToAnonymousClassMultifileTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.refactoring.inline; import com.intellij.JavaTestUtil; @@ -66,7 +52,7 @@ public class InlineToAnonymousClassMultifileTest extends RefactoringTestCase { private void doTest(String className) throws Exception { String rootBefore = getRoot() + "/before"; PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - final VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete); + final VirtualFile rootDir = createTestProjectStructure(rootBefore); String path = getRoot() + "/lib/simple.jar"; VirtualFile libJarLocal = LocalFileSystem.getInstance().findFileByPath(path); if (libJarLocal != null) { diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/smartPointers/SmartPsiElementPointersTest.java b/java/java-tests/testSrc/com/intellij/psi/impl/smartPointers/SmartPsiElementPointersTest.java index fb2d56811233..6d31b5ff67c8 100644 --- a/java/java-tests/testSrc/com/intellij/psi/impl/smartPointers/SmartPsiElementPointersTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/impl/smartPointers/SmartPsiElementPointersTest.java @@ -1,6 +1,4 @@ -/* - * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi.impl.smartPointers; import com.intellij.JavaTestUtil; @@ -68,7 +66,7 @@ public class SmartPsiElementPointersTest extends CodeInsightTestCase { String root = JavaTestUtil.getJavaTestDataPath() + "/codeEditor/smartPsiElementPointers"; PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - myRoot = PsiTestUtil.createTestProjectStructure(myProject, myModule, root, myFilesToDelete); + myRoot = createTestProjectStructure( root); } public void testChangeInDocument() { diff --git a/platform/platform-tests/testSrc/com/intellij/framework/detection/ConvertingOldDetectionExcludesTest.java b/platform/platform-tests/testSrc/com/intellij/framework/detection/ConvertingOldDetectionExcludesTest.java index 4fa8c8926ece..36ca9a7f1aee 100644 --- a/platform/platform-tests/testSrc/com/intellij/framework/detection/ConvertingOldDetectionExcludesTest.java +++ b/platform/platform-tests/testSrc/com/intellij/framework/detection/ConvertingOldDetectionExcludesTest.java @@ -1,6 +1,4 @@ -/* - * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.framework.detection; import com.intellij.framework.detection.impl.exclude.DetectionExcludesConfigurationImpl; @@ -12,7 +10,6 @@ import com.intellij.framework.detection.impl.exclude.old.OldFacetDetectionExclud import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.PsiTestUtil; -import com.intellij.testFramework.TempFiles; import static com.intellij.testFramework.assertions.Assertions.assertThat; @@ -21,17 +18,10 @@ import static com.intellij.testFramework.assertions.Assertions.assertThat; */ public class ConvertingOldDetectionExcludesTest extends PlatformTestCase { public static final String FRAMEWORK_ID = "my-framework"; - private TempFiles myTempFiles; - - @Override - protected void setUp() throws Exception { - super.setUp(); - myTempFiles = new TempFiles(myFilesToDelete); - } public void testUseOldConfiguration() { final DisabledAutodetectionInfo state = new DisabledAutodetectionInfo(); - final VirtualFile file = myTempFiles.createVFile("my-file", ".xml"); + final VirtualFile file = getTempDir().createVFile("my-file", ".xml"); state.getElements().add(new DisabledAutodetectionByTypeElement(FRAMEWORK_ID, myModule.getName(), file.getUrl(), false)); getOldConfiguration().loadState(state); @@ -42,9 +32,9 @@ public class ConvertingOldDetectionExcludesTest extends PlatformTestCase { public void testExcludeModuleConfiguration() { final DisabledAutodetectionInfo state = new DisabledAutodetectionInfo(); - final VirtualFile dir = myTempFiles.createTempVDir(); + final VirtualFile dir = getTempDir().createTempVDir(); PsiTestUtil.addContentRoot(myModule, dir); - final VirtualFile file = myTempFiles.createVFile(dir, "my-file", ".xml"); + final VirtualFile file = getTempDir().createVFile(dir, "my-file", ".xml"); state.getElements().add(new DisabledAutodetectionByTypeElement(FRAMEWORK_ID, myModule.getName())); getOldConfiguration().loadState(state); @@ -55,7 +45,7 @@ public class ConvertingOldDetectionExcludesTest extends PlatformTestCase { public void testExcludeFrameworkConfiguration() { final DisabledAutodetectionInfo state = new DisabledAutodetectionInfo(); - final VirtualFile file = myTempFiles.createVFile("my-file", ".xml"); + final VirtualFile file = getTempDir().createVFile("my-file", ".xml"); state.getElements().add(new DisabledAutodetectionByTypeElement(FRAMEWORK_ID)); getOldConfiguration().loadState(state); @@ -66,7 +56,7 @@ public class ConvertingOldDetectionExcludesTest extends PlatformTestCase { public void testUseNewConfiguration() { final ExcludesConfigurationState state = new ExcludesConfigurationState(); - final VirtualFile file = myTempFiles.createVFile("xxx", ".xml"); + final VirtualFile file = getTempDir().createVFile("xxx", ".xml"); state.getFiles().add(new ExcludedFileState(file.getUrl(), FRAMEWORK_ID)); getNewConfiguration().loadState(state); @@ -83,7 +73,7 @@ public class ConvertingOldDetectionExcludesTest extends PlatformTestCase { public void testConvert() { final DisabledAutodetectionInfo state = new DisabledAutodetectionInfo(); - final VirtualFile file = myTempFiles.createVFile("my-file", ".xml"); + final VirtualFile file = getTempDir().createVFile("my-file", ".xml"); state.getElements().add(new DisabledAutodetectionByTypeElement(FRAMEWORK_ID, myModule.getName(), file.getUrl(), false)); getOldConfiguration().loadState(state); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/ApplyPatchTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/ApplyPatchTest.java index c6afd479ede6..0cd5e31f77ee 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/ApplyPatchTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/ApplyPatchTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.diff.impl.patch; @@ -27,7 +13,6 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileFilter; import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.PlatformTestUtil; -import com.intellij.testFramework.PsiTestUtil; import java.io.File; import java.util.ArrayList; @@ -200,7 +185,7 @@ public class ApplyPatchTest extends PlatformTestCase { String afterPath = testDataPath + "/after"; VirtualFile afterDir = LocalFileSystem.getInstance().refreshAndFindFileByPath(afterPath.replace(File.separatorChar, '/')); - VirtualFile patchedDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, beforePath, myFilesToDelete); + VirtualFile patchedDir = createTestProjectStructure(beforePath); String patchPath = testDataPath + "/apply.patch"; VirtualFile patchFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(patchPath.replace(File.separatorChar, '/')); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/vfs/encoding/FileEncodingTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/vfs/encoding/FileEncodingTest.java index 4a360d5d0d21..af5383b58cf4 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/vfs/encoding/FileEncodingTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/vfs/encoding/FileEncodingTest.java @@ -215,8 +215,7 @@ public class FileEncodingTest extends PlatformTestCase implements TestDialog { String text = document.getText(); assertEquals("\u041f\u0440\u0438", text); - File copy = FileUtil.createTempFile("copy", ".txt"); - myFilesToDelete.add(copy); + File copy = getTempDir().createTempFile("copy", ".txt"); FileUtil.copy(source, copy); VirtualFile fileCopy = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(copy); document = getDocument(fileCopy); @@ -240,14 +239,12 @@ public class FileEncodingTest extends PlatformTestCase implements TestDialog { } private void doHtmlTest(final String metaWithWindowsEncoding, final String metaWithUtf8Encoding) throws IOException { - File temp = FileUtil.createTempFile("copy", ".html"); + File temp = getTempDir().createTempFile("copy", ".html"); setContentOnDisk(temp, NO_BOM, "" + metaWithWindowsEncoding + "" + THREE_RUSSIAN_LETTERS + "", WINDOWS_1252); - - myFilesToDelete.add(temp); VirtualFile file = ObjectUtils.assertNotNull(LocalFileSystem.getInstance().refreshAndFindFileByIoFile(temp)); assertEquals(WINDOWS_1252, file.getCharset()); diff --git a/platform/platform-tests/testSrc/com/intellij/psi/search/GlobalSearchScopeTest.java b/platform/platform-tests/testSrc/com/intellij/psi/search/GlobalSearchScopeTest.java index 5bc8c3699e3f..4422b441fa31 100644 --- a/platform/platform-tests/testSrc/com/intellij/psi/search/GlobalSearchScopeTest.java +++ b/platform/platform-tests/testSrc/com/intellij/psi/search/GlobalSearchScopeTest.java @@ -1,25 +1,10 @@ -/* - * Copyright 2000-2015 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi.search; import com.intellij.openapi.roots.ModuleRootModificationUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.PsiTestUtil; -import com.intellij.testFramework.TempFiles; import org.jetbrains.annotations.NotNull; import java.io.IOException; @@ -62,7 +47,7 @@ public class GlobalSearchScopeTest extends PlatformTestCase { } public void testNotScope() { - VirtualFile moduleRoot = new TempFiles(myFilesToDelete).createTempVDir(); + VirtualFile moduleRoot = getTempDir().createTempVDir(); ModuleRootModificationUtil.addContentRoot(getModule(), moduleRoot.getPath()); GlobalSearchScope projectScope = GlobalSearchScope.projectScope(getProject()); diff --git a/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java b/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java index 423c958a70ac..ae9d3091e9c1 100644 --- a/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java @@ -101,7 +101,10 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro protected ProjectManagerEx myProjectManager; protected Project myProject; protected Module myModule; + protected final Collection myFilesToDelete = new THashSet<>(); + private final TempFiles myTempFiles = new TempFiles(myFilesToDelete); + protected boolean myAssertionsInTestDetected; public static Thread ourTestThread; private static TestCase ourTestCase; @@ -115,6 +118,20 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro private SdkLeakTracker myOldSdks; private VirtualFilePointerTracker myVirtualFilePointerTracker; + + @NotNull + public TempFiles getTempDir() { + return myTempFiles; + } + + protected final VirtualFile createTestProjectStructure() throws IOException { + return PsiTestUtil.createTestProjectStructure(myProject, myModule, myFilesToDelete); + } + + protected final VirtualFile createTestProjectStructure(String rootPath) throws Exception { + return PsiTestUtil.createTestProjectStructure(myProject, myModule, rootPath, myFilesToDelete); + } + /** * If a temp directory is reused from some previous test run, there might be cached children in its VFS. * Ensure they're removed diff --git a/platform/vcs-tests/testSrc/com/intellij/openapi/vcs/changes/committed/CommittedChangesCacheTest.java b/platform/vcs-tests/testSrc/com/intellij/openapi/vcs/changes/committed/CommittedChangesCacheTest.java index 8612206fa319..5ad23dab9938 100644 --- a/platform/vcs-tests/testSrc/com/intellij/openapi/vcs/changes/committed/CommittedChangesCacheTest.java +++ b/platform/vcs-tests/testSrc/com/intellij/openapi/vcs/changes/committed/CommittedChangesCacheTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.committed; import com.intellij.openapi.application.ApplicationManager; @@ -325,7 +311,6 @@ public class CommittedChangesCacheTest extends PlatformTestCase { private File createTestFile(final String fileName) throws IOException { final File testFile = new File(myTempDir, fileName); testFile.createNewFile(); - myFilesToDelete.add(testFile); ApplicationManager.getApplication().runWriteAction(() -> { VirtualFileManager.getInstance().syncRefresh(); }); diff --git a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/binding/FormEnumUsageTest.java b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/binding/FormEnumUsageTest.java index 0b8309f9f1cd..3be5af8d7b8b 100644 --- a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/binding/FormEnumUsageTest.java +++ b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/binding/FormEnumUsageTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.uiDesigner.binding; @@ -40,7 +26,7 @@ public class FormEnumUsageTest extends PsiTestCase { String root = PluginPathManager.getPluginHomePath("ui-designer") + "/testData/binding/" + getTestName(true); PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - myTestProjectRoot = PsiTestUtil.createTestProjectStructure(myProject, myModule, root, myFilesToDelete); + myTestProjectRoot = createTestProjectStructure(root); } @Override protected void tearDown() throws Exception { diff --git a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/binding/FormPropertyUsageTest.java b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/binding/FormPropertyUsageTest.java index 2bc0648eb378..826686ca4567 100644 --- a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/binding/FormPropertyUsageTest.java +++ b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/binding/FormPropertyUsageTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.uiDesigner.binding; @@ -45,7 +31,7 @@ public class FormPropertyUsageTest extends PsiTestCase { String root = PluginPathManager.getPluginHomePath("ui-designer") + "/testData/binding/" + getTestName(true); PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - myTestProjectRoot = PsiTestUtil.createTestProjectStructure(myProject, myModule, root, myFilesToDelete); + myTestProjectRoot = createTestProjectStructure(root); } @Override protected void tearDown() throws Exception { diff --git a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/make/FormSourceCodeGeneratorTest.java b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/make/FormSourceCodeGeneratorTest.java index 66f628052470..5d6b49047c7e 100644 --- a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/make/FormSourceCodeGeneratorTest.java +++ b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/make/FormSourceCodeGeneratorTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2015 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.uiDesigner.make; @@ -44,7 +30,7 @@ public class FormSourceCodeGeneratorTest extends PsiTestCase { String root = PluginPathManager.getPluginHomePath("ui-designer") + "/testData/sourceCodeGenerator/" + getTestName(true); PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - myTestProjectRoot = PsiTestUtil.createTestProjectStructure(myProject, myModule, root, myFilesToDelete); + myTestProjectRoot = createTestProjectStructure(root); myGenerator = new FormSourceCodeGenerator(getProject()); } From 6a29cee47453b9c2ee5f35c4d95034ab852a64c1 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Tue, 6 Mar 2018 17:21:22 +0100 Subject: [PATCH 12/22] reduce direct usages of myFilesToDelete --- .../impl/FileTemplatesTest.groovy | 21 ++---------- .../psi/impl/file/impl/PsiEventsTest.java | 18 +--------- .../refactoring/MoveClassAndFileTest.java | 18 ++-------- .../java/refactoring/MoveClassTest.java | 18 ++-------- .../refactoring/MoveClassToInnerTest.java | 18 ++-------- .../roots/ModuleRootsExternalizationTest.java | 3 +- .../com/intellij/openapi/ui/TestDialog.java | 7 ++-- .../diff/impl/mergeTool/MergeDataTest.java | 34 ++----------------- .../diff/impl/patch/PatchReaderTest.kt | 3 +- .../diff/impl/patch/PatchTextDetectionTest.kt | 3 +- .../vfs/encoding/FileEncodingTest.java | 9 ++--- .../testFramework/PlatformTestCase.java | 13 ++----- .../com/intellij/testFramework/TempFiles.java | 29 +++++++--------- .../UpdateBreakpointsAfterRenameTest.java | 18 ++-------- .../xdebugger/XBreakpointManagerTest.java | 6 ++-- .../xdebugger/XBreakpointsTestCase.java | 7 +--- 16 files changed, 38 insertions(+), 187 deletions(-) diff --git a/java/java-tests/testSrc/com/intellij/java/ide/fileTemplates/impl/FileTemplatesTest.groovy b/java/java-tests/testSrc/com/intellij/java/ide/fileTemplates/impl/FileTemplatesTest.groovy index 9393335463bc..4473b3844a22 100644 --- a/java/java-tests/testSrc/com/intellij/java/ide/fileTemplates/impl/FileTemplatesTest.groovy +++ b/java/java-tests/testSrc/com/intellij/java/ide/fileTemplates/impl/FileTemplatesTest.groovy @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.ide.fileTemplates.impl import com.intellij.ide.fileTemplates.FileTemplate @@ -141,9 +127,7 @@ class FileTemplatesTest extends IdeaTestCase { String name = "my_class" FileTemplate template = addTestTemplate(name, 'package ${PACKAGE_NAME}; public class ${NAME} {}') - File temp = FileUtil.createTempDirectory(getTestName(true), "") - - myFilesToDelete.add(temp) + File temp = createTempDirectory(false) VirtualFile tempDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(temp) PsiTestUtil.addSourceRoot(getModule(), tempDir) @@ -204,7 +188,6 @@ class FileTemplatesTest extends IdeaTestCase { //noinspection GroovyAccessibility String name = FTManager.encodeFileName("test", "ext.has.dots") File file = createTempFile(name, "test") - myFilesToDelete.add(file) FileUtil.loadFile(new File(file.getAbsolutePath()), CharsetToolkit.UTF8_CHARSET) LOG.debug("File loaded: " + file.getAbsolutePath()) File dir = new File(file.getParent()) diff --git a/java/java-tests/testSrc/com/intellij/java/psi/impl/file/impl/PsiEventsTest.java b/java/java-tests/testSrc/com/intellij/java/psi/impl/file/impl/PsiEventsTest.java index d95e533550e8..3132d031ca20 100644 --- a/java/java-tests/testSrc/com/intellij/java/psi/impl/file/impl/PsiEventsTest.java +++ b/java/java-tests/testSrc/com/intellij/java/psi/impl/file/impl/PsiEventsTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.psi.impl.file.impl; import com.intellij.openapi.application.ApplicationManager; @@ -578,7 +564,6 @@ public class PsiEventsTest extends PsiTestCase { rename(virtualFile, "b.xml"); } - private String newText; private String original; private String eventsFired = ""; private PsiTreeChangeListener listener; @@ -691,7 +676,6 @@ public class PsiEventsTest extends PsiTestCase { try { getPsiManager().addPsiTreeChangeListener(listener); eventsFired = ""; - this.newText = newText; original = getFile().getText(); Document document = PsiDocumentManager.getInstance(getProject()).getDocument(getFile()); ApplicationManager.getApplication().runWriteAction(() -> document.setText(newText)); diff --git a/java/java-tests/testSrc/com/intellij/java/refactoring/MoveClassAndFileTest.java b/java/java-tests/testSrc/com/intellij/java/refactoring/MoveClassAndFileTest.java index 6f7dfbbbbfb3..54ac61b9e0f5 100644 --- a/java/java-tests/testSrc/com/intellij/java/refactoring/MoveClassAndFileTest.java +++ b/java/java-tests/testSrc/com/intellij/java/refactoring/MoveClassAndFileTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.refactoring; import com.intellij.JavaTestUtil; @@ -53,7 +39,7 @@ public class MoveClassAndFileTest extends RefactoringTestCase { String rootBefore = root + "/before"; PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete); + VirtualFile rootDir = createTestProjectStructure(rootBefore); performAction(newPackageName, fileNameNearFirstClass, classNames); diff --git a/java/java-tests/testSrc/com/intellij/java/refactoring/MoveClassTest.java b/java/java-tests/testSrc/com/intellij/java/refactoring/MoveClassTest.java index b4a6684d8719..b05cd53c5e40 100644 --- a/java/java-tests/testSrc/com/intellij/java/refactoring/MoveClassTest.java +++ b/java/java-tests/testSrc/com/intellij/java/refactoring/MoveClassTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.refactoring; import com.intellij.JavaTestUtil; @@ -106,7 +92,7 @@ public class MoveClassTest extends RefactoringTestCase { String rootBefore = root + "/before"; PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete); + VirtualFile rootDir = createTestProjectStructure(rootBefore); performAction(classNames, newPackageName); diff --git a/java/java-tests/testSrc/com/intellij/java/refactoring/MoveClassToInnerTest.java b/java/java-tests/testSrc/com/intellij/java/refactoring/MoveClassToInnerTest.java index d3fefef4565f..8c504b793ecf 100644 --- a/java/java-tests/testSrc/com/intellij/java/refactoring/MoveClassToInnerTest.java +++ b/java/java-tests/testSrc/com/intellij/java/refactoring/MoveClassToInnerTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.refactoring; import com.intellij.JavaTestUtil; @@ -146,7 +132,7 @@ public class MoveClassToInnerTest extends RefactoringTestCase { private VirtualFile prepareTest() throws Exception { String rootBefore = getRoot() + "/before"; PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); - return PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete); + return createTestProjectStructure(rootBefore); } private String getRoot() { diff --git a/java/java-tests/testSrc/com/intellij/roots/ModuleRootsExternalizationTest.java b/java/java-tests/testSrc/com/intellij/roots/ModuleRootsExternalizationTest.java index f2ab44b61672..8465b4b92ee0 100644 --- a/java/java-tests/testSrc/com/intellij/roots/ModuleRootsExternalizationTest.java +++ b/java/java-tests/testSrc/com/intellij/roots/ModuleRootsExternalizationTest.java @@ -13,7 +13,6 @@ import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.impl.ModuleRootManagerImpl; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTable; -import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.IdeaTestUtil; @@ -47,7 +46,7 @@ public class ModuleRootsExternalizationTest extends ModuleTestCase { } private ModuleRootManagerImpl createTempModuleRootManager() throws IOException { - File tmpModule = FileUtil.createTempFile("tst", ModuleFileType.DOT_DEFAULT_EXTENSION); + File tmpModule = getTempDir().createTempFile("tst", ModuleFileType.DOT_DEFAULT_EXTENSION, false); myFilesToDelete.add(tmpModule); final Module module = createModule(tmpModule); return (ModuleRootManagerImpl)ModuleRootManager.getInstance(module); diff --git a/platform/platform-api/src/com/intellij/openapi/ui/TestDialog.java b/platform/platform-api/src/com/intellij/openapi/ui/TestDialog.java index 943aa742687e..51686aeb8e9c 100644 --- a/platform/platform-api/src/com/intellij/openapi/ui/TestDialog.java +++ b/platform/platform-api/src/com/intellij/openapi/ui/TestDialog.java @@ -9,9 +9,6 @@ public interface TestDialog { } }; TestDialog OK = new TestDialog() { - public int show(String message) { - return 0; - } }; TestDialog NO = new TestDialog() { public int show(String message) { @@ -19,5 +16,7 @@ public interface TestDialog { } }; - int show(String message); + default int show(String message) { + return 0; + } } diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/mergeTool/MergeDataTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/mergeTool/MergeDataTest.java index deeb119ae800..071c606c677a 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/mergeTool/MergeDataTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/mergeTool/MergeDataTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.diff.impl.mergeTool; import com.intellij.openapi.diff.ActionButtonPresentation; @@ -21,13 +7,10 @@ import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.testFramework.TempFiles; public class MergeDataTest extends BaseDiffTestCase { - private TempFiles myTempFiles; - public void testWorkingDocument() { - VirtualFile file = myTempFiles.createVFile("merge", ".txt"); + VirtualFile file = getTempDir().createVFile("merge", ".txt"); assertNotNull(file); assertEquals("txt", file.getExtension()); Document document = FileDocumentManager.getInstance().getDocument(file); @@ -44,17 +27,4 @@ public class MergeDataTest extends BaseDiffTestCase { mergeData.setResult(DialogWrapper.OK_EXIT_CODE); assertEquals("corrected", document.getText()); } - - @Override - protected void setUp() throws Exception { - super.setUp(); - myTempFiles = new TempFiles(myFilesToDelete); - } - - @Override - protected void tearDown() throws Exception { - myTempFiles.deleteAll(); - myTempFiles = null; - super.tearDown(); - } } diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/PatchReaderTest.kt b/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/PatchReaderTest.kt index b6373161b078..965a22ec3976 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/PatchReaderTest.kt +++ b/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/PatchReaderTest.kt @@ -5,7 +5,6 @@ import com.intellij.openapi.fileEditor.impl.LoadTextUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.testFramework.PlatformTestCase import com.intellij.testFramework.PlatformTestUtil -import com.intellij.testFramework.PsiTestUtil import com.intellij.vcs.log.impl.VcsUserImpl import junit.framework.TestCase import java.io.File @@ -84,7 +83,7 @@ class PatchReaderTest : PlatformTestCase() { private fun read(): PatchReader { val testDataPath = PlatformTestUtil.getPlatformTestDataPath() + "diff/patchReader/" + getTestName(true) - PsiTestUtil.createTestProjectStructure(myProject, myModule, testDataPath, myFilesToDelete) + createTestProjectStructure(testDataPath) val patchPath = "$testDataPath/test.patch" val patchFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(patchPath.replace(File.separatorChar, '/')) diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/PatchTextDetectionTest.kt b/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/PatchTextDetectionTest.kt index 265cc62af3bb..df89b18c0c0e 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/PatchTextDetectionTest.kt +++ b/platform/platform-tests/testSrc/com/intellij/openapi/diff/impl/patch/PatchTextDetectionTest.kt @@ -5,7 +5,6 @@ import com.intellij.openapi.fileEditor.impl.LoadTextUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.testFramework.PlatformTestCase import com.intellij.testFramework.PlatformTestUtil -import com.intellij.testFramework.PsiTestUtil import java.io.File class PatchTextDetectionTest : PlatformTestCase() { @@ -35,7 +34,7 @@ class PatchTextDetectionTest : PlatformTestCase() { private fun doTest(expected: Boolean) { val testDataPath = PlatformTestUtil.getPlatformTestDataPath() + "diff/patchTextDetection/" + getTestName(true) - PsiTestUtil.createTestProjectStructure(myProject, myModule, testDataPath, myFilesToDelete) + createTestProjectStructure(testDataPath) val patchPath = "$testDataPath/test.patch" val patchFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(patchPath.replace(File.separatorChar, '/')) diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/vfs/encoding/FileEncodingTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/vfs/encoding/FileEncodingTest.java index af5383b58cf4..52d1ba3413f1 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/vfs/encoding/FileEncodingTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/vfs/encoding/FileEncodingTest.java @@ -85,11 +85,6 @@ public class FileEncodingTest extends PlatformTestCase implements TestDialog { } } - @Override - public int show(String message) { - return 0; - } - private static Document getDocument(VirtualFile file) { return FileDocumentManager.getInstance().getDocument(file); } @@ -215,7 +210,7 @@ public class FileEncodingTest extends PlatformTestCase implements TestDialog { String text = document.getText(); assertEquals("\u041f\u0440\u0438", text); - File copy = getTempDir().createTempFile("copy", ".txt"); + File copy = getTempDir().createTempFile("copy", ".txt", false); FileUtil.copy(source, copy); VirtualFile fileCopy = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(copy); document = getDocument(fileCopy); @@ -239,7 +234,7 @@ public class FileEncodingTest extends PlatformTestCase implements TestDialog { } private void doHtmlTest(final String metaWithWindowsEncoding, final String metaWithUtf8Encoding) throws IOException { - File temp = getTempDir().createTempFile("copy", ".html"); + File temp = getTempDir().createTempFile("copy", ".html", false); setContentOnDisk(temp, NO_BOM, "" + metaWithWindowsEncoding + "" + THREE_RUSSIAN_LETTERS + diff --git a/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java b/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java index ae9d3091e9c1..cac928a6d98d 100644 --- a/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java @@ -517,10 +517,8 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro }) .append(() -> { ((JarFileSystemImpl)JarFileSystem.getInstance()).cleanupForNextTest(); - - for (final File fileToDelete : myFilesToDelete) { - delete(fileToDelete); - } + + getTempDir().deleteAll(); LocalFileSystem.getInstance().refreshIoFiles(myFilesToDelete); }) .append(() -> { @@ -603,13 +601,6 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro return getClass().getName() + "." + getName(); } - private void delete(File file) { - boolean b = FileUtil.delete(file); - if (!b && file.exists() && !myAssertionsInTestDetected) { - fail("Can't delete " + file.getAbsolutePath() + " in " + getFullName()); - } - } - protected void setUpJdk() { //final ProjectJdkEx jdk = ProjectJdkUtil.getDefaultJdk("java 1.4"); final Sdk jdk = getTestProjectJdk(); diff --git a/platform/testFramework/src/com/intellij/testFramework/TempFiles.java b/platform/testFramework/src/com/intellij/testFramework/TempFiles.java index dc27670903c9..a93f9f1d0160 100644 --- a/platform/testFramework/src/com/intellij/testFramework/TempFiles.java +++ b/platform/testFramework/src/com/intellij/testFramework/TempFiles.java @@ -1,23 +1,10 @@ -/* - * Copyright 2000-2015 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testFramework; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; @@ -52,10 +39,17 @@ public class TempFiles { @NotNull public File createTempFile(@NotNull String prefix, String suffix) { + return createTempFile(prefix, suffix, true); + } + + @NotNull + public File createTempFile(@NotNull String prefix, String suffix, boolean isRefreshVfs) { try { - File tempFile = FileUtil.createTempFile(prefix, suffix); + File tempFile = FileUtilRt.createTempFile(prefix, suffix, false); tempFileCreated(tempFile); - getVFileByFile(tempFile); + if (isRefreshVfs) { + getVFileByFile(tempFile); + } return tempFile; } catch (IOException e) { @@ -103,6 +97,7 @@ public class TempFiles { public void deleteAll() { for (File file : myFilesToDelete) { if (!FileUtil.delete(file)) { + //noinspection SSBasedInspection file.deleteOnExit(); } } diff --git a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/UpdateBreakpointsAfterRenameTest.java b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/UpdateBreakpointsAfterRenameTest.java index a77137b1340a..d6f222895893 100644 --- a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/UpdateBreakpointsAfterRenameTest.java +++ b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/UpdateBreakpointsAfterRenameTest.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.xdebugger; import com.intellij.openapi.application.WriteAction; @@ -57,7 +43,7 @@ public class UpdateBreakpointsAfterRenameTest extends XBreakpointsTestCase { } private VirtualFile createFile(String path) { - final File ioFile = new File(myTempFiles.createTempDir(), FileUtil.toSystemDependentName(path)); + final File ioFile = new File(getTempDir().createTempDir(), FileUtil.toSystemDependentName(path)); FileUtil.createIfDoesntExist(ioFile); final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(ioFile); assertNotNull(virtualFile); diff --git a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XBreakpointManagerTest.java b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XBreakpointManagerTest.java index e4c18c119b39..22f168199377 100644 --- a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XBreakpointManagerTest.java +++ b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XBreakpointManagerTest.java @@ -1,6 +1,4 @@ -/* - * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.xdebugger; import com.intellij.openapi.vfs.VirtualFile; @@ -136,7 +134,7 @@ public class XBreakpointManagerTest extends XBreakpointsTestCase { } public void testRemoveFile() { - final VirtualFile file = myTempFiles.createVFile("breakpoint", ".txt"); + final VirtualFile file = getTempDir().createVFile("breakpoint", ".txt"); addLineBreakpoint(myBreakpointManager, file.getUrl(), 0, null); assertOneElement(myBreakpointManager.getBreakpoints(MY_LINE_BREAKPOINT_TYPE)); delete(file); diff --git a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XBreakpointsTestCase.java b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XBreakpointsTestCase.java index 66eeb163e590..468a042cb7d4 100644 --- a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XBreakpointsTestCase.java +++ b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XBreakpointsTestCase.java @@ -1,11 +1,8 @@ -/* - * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.xdebugger; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.testFramework.TempFiles; import com.intellij.xdebugger.breakpoints.XBreakpoint; import com.intellij.xdebugger.breakpoints.XBreakpointType; import com.intellij.xdebugger.impl.BreakpointManagerState; @@ -25,13 +22,11 @@ import static com.intellij.configurationStore.XmlSerializer.serialize; */ public abstract class XBreakpointsTestCase extends XDebuggerTestCase { protected XBreakpointManagerImpl myBreakpointManager; - protected TempFiles myTempFiles; @Override protected void setUp() throws Exception { super.setUp(); myBreakpointManager = (XBreakpointManagerImpl)XDebuggerManager.getInstance(myProject).getBreakpointManager(); - myTempFiles = new TempFiles(myFilesToDelete); } @Override From dc5c8c26baa8fc3199d72090c5d5ac560b95ad43 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Thu, 8 Mar 2018 08:38:20 +0100 Subject: [PATCH 13/22] fix compilation --- .../platform-api/src/com/intellij/openapi/ui/TestDialog.java | 1 - 1 file changed, 1 deletion(-) diff --git a/platform/platform-api/src/com/intellij/openapi/ui/TestDialog.java b/platform/platform-api/src/com/intellij/openapi/ui/TestDialog.java index 51686aeb8e9c..03dd78682a09 100644 --- a/platform/platform-api/src/com/intellij/openapi/ui/TestDialog.java +++ b/platform/platform-api/src/com/intellij/openapi/ui/TestDialog.java @@ -2,7 +2,6 @@ package com.intellij.openapi.ui; public interface TestDialog { - TestDialog DEFAULT = new TestDialog() { public int show(String message) { throw new RuntimeException(message); From c24a3562a57693740aa9a65dbda5aad721c246de Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Thu, 8 Mar 2018 09:21:45 +0100 Subject: [PATCH 14/22] fix compilation, take 2 --- .../src/com/intellij/openapi/ui/TestDialog.java | 8 +++++--- .../intellij/openapi/vfs/encoding/FileEncodingTest.java | 9 +++++++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/platform/platform-api/src/com/intellij/openapi/ui/TestDialog.java b/platform/platform-api/src/com/intellij/openapi/ui/TestDialog.java index 03dd78682a09..16c8de6b059d 100644 --- a/platform/platform-api/src/com/intellij/openapi/ui/TestDialog.java +++ b/platform/platform-api/src/com/intellij/openapi/ui/TestDialog.java @@ -8,6 +8,10 @@ public interface TestDialog { } }; TestDialog OK = new TestDialog() { + @Override + public int show(String message) { + return 0; + } }; TestDialog NO = new TestDialog() { public int show(String message) { @@ -15,7 +19,5 @@ public interface TestDialog { } }; - default int show(String message) { - return 0; - } + int show(String message); } diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/vfs/encoding/FileEncodingTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/vfs/encoding/FileEncodingTest.java index 52d1ba3413f1..db884f2c9aec 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/vfs/encoding/FileEncodingTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/vfs/encoding/FileEncodingTest.java @@ -65,6 +65,11 @@ public class FileEncodingTest extends PlatformTestCase implements TestDialog { private static final String THREE_RUSSIAN_LETTERS = "\u0416\u041e\u041f"; private TestDialog myOldTestDialogValue; + @Override + public int show(String message) { + return 0; + } + private static String prolog(Charset charset) { return "\n"; } @@ -88,7 +93,7 @@ public class FileEncodingTest extends PlatformTestCase implements TestDialog { private static Document getDocument(VirtualFile file) { return FileDocumentManager.getInstance().getDocument(file); } - + public void testWin1251() { VirtualFile vTestRoot = getTestRoot(); VirtualFile xml = vTestRoot.findChild("xWin1251.xml"); @@ -696,7 +701,7 @@ public class FileEncodingTest extends PlatformTestCase implements TestDialog { VirtualFile file = createTempFile("txt", CharsetToolkit.UTF8_BOM, text, CharsetToolkit.UTF8_CHARSET); file.contentsToByteArray(); Document document = ObjectUtils.assertNotNull(FileDocumentManager.getInstance().getDocument(file)); - + assertEquals(text, document.getText()); assertEquals(CharsetToolkit.UTF8_CHARSET, file.getCharset()); assertArrayEquals(CharsetToolkit.UTF8_BOM, file.getBOM()); From b7fc354b0b1e5019e1805f79470c48d7bf8f16d9 Mon Sep 17 00:00:00 2001 From: Dmitry Jemerov Date: Wed, 7 Mar 2018 15:42:03 +0100 Subject: [PATCH 15/22] Provide API for creating CompletionParameters instance --- .../completion/CompletionService.java | 33 +-- .../completion/CodeCompletionHandlerBase.java | 200 +--------------- .../CompletionInitializationContextImpl.java | 26 +++ .../CompletionInitializationUtil.java | 213 ++++++++++++++++++ .../CompletionProgressIndicator.java | 48 +--- .../CompletionProgressIndicatorBase.java | 49 ++++ .../impl/CompletionServiceImpl.java | 30 +-- 7 files changed, 336 insertions(+), 263 deletions(-) create mode 100644 platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionInitializationContextImpl.java create mode 100644 platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionInitializationUtil.java create mode 100644 platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicatorBase.java diff --git a/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionService.java b/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionService.java index ee5b32d968c4..1add0177bc3a 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionService.java +++ b/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionService.java @@ -1,23 +1,12 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.completion; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.editor.Caret; +import com.intellij.openapi.editor.Editor; import com.intellij.openapi.progress.ProgressManager; +import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.psi.Weigher; import com.intellij.util.Consumer; @@ -62,6 +51,20 @@ public abstract class CompletionService { */ public abstract void setAdvertisementText(@Nullable String text); + /** + * Creates the completion parameters for the given context. + * + * @param caret the selected caret in the given editor + * @param invocationCount the number of times the user has pressed the code completion shortcut (0 if autopopup) + * @return the completion parameters instance + */ + @SuppressWarnings("unused") + public abstract CompletionParameters createCompletionParameters(@NotNull Project project, + @NotNull Editor editor, + @NotNull Caret caret, + int invocationCount, + CompletionType completionType); + /** * Run all contributors until any of them returns false or the list is exhausted. If from parameter is not null, contributors * will be run starting from the next one after that. diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java index 1cf0be65a1d7..3dd808492a9e 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java @@ -1,18 +1,4 @@ -/* - * 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.completion; @@ -26,7 +12,6 @@ import com.intellij.codeInsight.lookup.*; import com.intellij.codeInsight.lookup.impl.LookupImpl; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.ide.DataManager; -import com.intellij.injected.editor.DocumentWindow; import com.intellij.lang.Language; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.openapi.actionSystem.ActionManager; @@ -37,29 +22,25 @@ import com.intellij.openapi.application.TransactionGuard; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.editor.*; +import com.intellij.openapi.editor.Caret; +import com.intellij.openapi.editor.CaretAction; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.EditorModificationUtil; import com.intellij.openapi.editor.actionSystem.EditorActionManager; import com.intellij.openapi.editor.ex.DocumentEx; -import com.intellij.openapi.editor.ex.util.EditorUtil; -import com.intellij.openapi.editor.impl.DocumentImpl; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; -import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; -import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; -import com.intellij.psi.impl.PsiFileEx; import com.intellij.psi.impl.source.PostprocessReformattingAspect; -import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.util.PsiUtilBase; import com.intellij.psi.util.PsiUtilCore; -import com.intellij.reference.SoftReference; import com.intellij.util.ThreeState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -166,18 +147,8 @@ public class CodeCompletionHandlerBase { } Runnable initCmd = () -> { - CompletionInitializationContext context = WriteAction.compute(() -> { - EditorUtil.fillVirtualSpaceUntilCaret(editor); - PsiDocumentManager.getInstance(project).commitAllDocuments(); - CompletionAssertions.checkEditorValid(editor); - - final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(caret, project); - assert psiFile != null : "no PSI file: " + FileDocumentManager.getInstance().getFile(editor.getDocument()); - psiFile.putUserData(PsiFileEx.BATCH_REFERENCE_PROCESSING, Boolean.TRUE); - CompletionAssertions.assertCommitSuccessful(editor, psiFile); - - return runContributorsBeforeCompletion(editor, psiFile, invocationCount, caret); - }); + CompletionInitializationContextImpl context = CompletionInitializationUtil.createCompletionInitializationContext(project, editor, caret, + invocationCount, completionType); doComplete(context, hasModifiers); }; if (autopopup) { @@ -187,31 +158,6 @@ public class CodeCompletionHandlerBase { } } - private CompletionInitializationContext runContributorsBeforeCompletion(Editor editor, PsiFile psiFile, int invocationCount, @NotNull Caret caret) { - final Ref current = Ref.create(null); - CompletionInitializationContext context = new CompletionInitializationContext(editor, caret, psiFile, completionType, invocationCount) { - CompletionContributor dummyIdentifierChanger; - - @Override - public void setDummyIdentifier(@NotNull String dummyIdentifier) { - super.setDummyIdentifier(dummyIdentifier); - - if (dummyIdentifierChanger != null) { - LOG.error("Changing the dummy identifier twice, already changed by " + dummyIdentifierChanger); - } - dummyIdentifierChanger = current.get(); - } - }; - Project project = psiFile.getProject(); - for (final CompletionContributor contributor : CompletionContributor.forLanguageHonorDumbness(context.getPositionLanguage(), project)) { - current.set(contributor); - contributor.beforeCompletion(context); - CompletionAssertions.checkEditorValid(editor); - assert !PsiDocumentManager.getInstance(project).isUncommited(editor.getDocument()) : "Contributor " + contributor + " left the document uncommitted"; - } - return context; - } - private static void checkNoWriteAccess() { if (!ApplicationManager.getApplication().isUnitTestMode()) { if (ApplicationManager.getApplication().isWriteAccessAllowed()) { @@ -264,11 +210,10 @@ public class CodeCompletionHandlerBase { return lookup; } - private void doComplete(CompletionInitializationContext initContext, boolean hasModifiers) { + private void doComplete(CompletionInitializationContextImpl initContext, boolean hasModifiers) { final Editor editor = initContext.getEditor(); CompletionAssertions.checkEditorValid(editor); - OffsetsInFile hostOffsets = new OffsetsInFile(initContext.getFile(), initContext.getOffsetMap()).toTopLevelFile(); LookupImpl lookup = obtainLookup(editor, initContext.getProject()); CompletionPhase phase = CompletionServiceImpl.getCompletionPhase(); @@ -283,7 +228,9 @@ public class CodeCompletionHandlerBase { CompletionProgressIndicator indicator = new CompletionProgressIndicator(editor, initContext.getCaret(), initContext.getInvocationCount(), this, - initContext.getOffsetMap(), hostOffsets, hasModifiers, lookup); + initContext.getOffsetMap(), + initContext.getHostOffsets(), + hasModifiers, lookup); CompletionServiceImpl.setCompletionPhase(synchronous ? new CompletionPhase.Synchronous(indicator) : new CompletionPhase.BgCalculation(indicator)); @@ -323,36 +270,7 @@ public class CodeCompletionHandlerBase { if (autopopup && shouldSkipAutoPopup(initContext.getEditor(), initContext.getFile())) { return null; } - - OffsetsInFile hostCopyOffsets = insertDummyIdentifier(initContext, indicator, indicator.getHostOffsets()); - if (hostCopyOffsets == null) { - return null; - } - - indicator.registerChildDisposable(hostCopyOffsets::getOffsets); - OffsetsInFile finalOffsets = toInjectedIfAny(initContext.getFile(), hostCopyOffsets); - indicator.registerChildDisposable(finalOffsets::getOffsets); - - return createCompletionParameters(initContext, indicator, finalOffsets); - } - - @NotNull - private CompletionParameters createCompletionParameters(CompletionInitializationContext initContext, - CompletionProgressIndicator indicator, OffsetsInFile finalOffsets) { - int offset = finalOffsets.getOffsets().getOffset(CompletionInitializationContext.START_OFFSET); - PsiFile fileCopy = finalOffsets.getFile(); - PsiFile originalFile = fileCopy.getOriginalFile(); - PsiElement insertedElement = findCompletionPositionLeaf(finalOffsets, offset, originalFile); - insertedElement.putUserData(CompletionContext.COMPLETION_CONTEXT_KEY, new CompletionContext(fileCopy, finalOffsets.getOffsets())); - return new CompletionParameters(insertedElement, originalFile, completionType, offset, initContext.getInvocationCount(), - initContext.getEditor(), indicator); - } - - @NotNull - private static PsiElement findCompletionPositionLeaf(OffsetsInFile offsets, int offset, PsiFile originalFile) { - PsiElement insertedElement = offsets.getFile().findElementAt(offset); - CompletionAssertions.assertCompletionPositionPsiConsistent(offsets, offset, originalFile, insertedElement); - return insertedElement; + return CompletionInitializationUtil.prepareCompletionParameters(initContext, indicator); } private static void checkNotSync(CompletionProgressIndicator indicator, List allItems) { @@ -460,49 +378,6 @@ public class CodeCompletionHandlerBase { } } - private static OffsetsInFile insertDummyIdentifier(CompletionInitializationContext initContext, - CompletionProgressIndicator indicator, - OffsetsInFile topLevelOffsets) { - CompletionAssertions.checkEditorValid(initContext.getEditor()); - - Editor hostEditor = InjectedLanguageUtil.getTopLevelEditor(initContext.getEditor()); - OffsetMap hostMap = topLevelOffsets.getOffsets(); - - PsiFile hostCopy = obtainFileCopy(topLevelOffsets.getFile()); - Document copyDocument = Objects.requireNonNull(hostCopy.getViewProvider().getDocument()); - - String dummyIdentifier = initContext.getDummyIdentifier(); - int startOffset = hostMap.getOffset(CompletionInitializationContext.START_OFFSET); - int endOffset = hostMap.getOffset(CompletionInitializationContext.SELECTION_END_OFFSET); - - indicator.registerChildDisposable( - () -> new OffsetTranslator(hostEditor.getDocument(), initContext.getFile(), copyDocument, startOffset, endOffset, dummyIdentifier)); - - OffsetsInFile copyOffsets = topLevelOffsets.replaceInCopy(hostCopy, startOffset, endOffset, dummyIdentifier); - return hostCopy.isValid() ? copyOffsets : null; - } - - private static OffsetsInFile toInjectedIfAny(PsiFile originalFile, OffsetsInFile hostCopyOffsets) { - CompletionAssertions.assertHostInfo(hostCopyOffsets.getFile(), hostCopyOffsets.getOffsets()); - - int hostStartOffset = hostCopyOffsets.getOffsets().getOffset(CompletionInitializationContext.START_OFFSET); - OffsetsInFile translatedOffsets = hostCopyOffsets.toInjectedIfAny(hostStartOffset); - if (translatedOffsets != hostCopyOffsets) { - PsiFile injected = translatedOffsets.getFile(); - if (injected instanceof PsiFileImpl) { - ((PsiFileImpl)injected).setOriginalFile(originalFile); - } - DocumentWindow documentWindow = InjectedLanguageUtil.getDocumentWindow(injected); - CompletionAssertions.assertInjectedOffsets(hostStartOffset, injected, documentWindow); - - if (injected.getTextRange().contains(translatedOffsets.getOffsets().getOffset(CompletionInitializationContext.START_OFFSET))) { - return translatedOffsets; - } - } - - return hostCopyOffsets; - } - protected void lookupItemSelected(final CompletionProgressIndicator indicator, @NotNull final LookupElement item, final char completionChar, final List items) { if (indicator.isAutopopupCompletion()) { @@ -666,57 +541,6 @@ public class CodeCompletionHandlerBase { } } - private static final Key>> FILE_COPY_KEY = Key.create("CompletionFileCopy"); - - private static boolean isCopyUpToDate(Document document, @NotNull PsiFile copyFile, @NotNull PsiFile originalFile) { - if (!copyFile.getClass().equals(originalFile.getClass()) || - !copyFile.isValid() || - !copyFile.getName().equals(originalFile.getName())) { - return false; - } - // the psi file cache might have been cleared by some external activity, - // in which case PSI-document sync may stop working - PsiFile current = PsiDocumentManager.getInstance(copyFile.getProject()).getPsiFile(document); - return current != null && current.getViewProvider().getPsi(copyFile.getLanguage()) == copyFile; - } - - private static PsiFile obtainFileCopy(PsiFile file) { - final VirtualFile virtualFile = file.getVirtualFile(); - boolean mayCacheCopy = file.isPhysical() && - // we don't want to cache code fragment copies even if they appear to be physical - virtualFile != null && virtualFile.isInLocalFileSystem(); - if (mayCacheCopy) { - final Pair cached = SoftReference.dereference(file.getUserData(FILE_COPY_KEY)); - if (cached != null && isCopyUpToDate(cached.second, cached.first, file)) { - PsiFile copy = cached.first; - CompletionAssertions.assertCorrectOriginalFile("Cached", file, copy); - return copy; - } - } - - final PsiFile copy = (PsiFile)file.copy(); - if (copy.isPhysical() || copy.getViewProvider().isEventSystemEnabled()) { - LOG.error("File copy should be non-physical and non-event-system-enabled! Language=" + file.getLanguage() + "; file=" + file + " of " + file.getClass()); - } - CompletionAssertions.assertCorrectOriginalFile("New", file, copy); - - if (mayCacheCopy) { - final Document document = copy.getViewProvider().getDocument(); - assert document != null; - syncAcceptSlashR(file.getViewProvider().getDocument(), document); - file.putUserData(FILE_COPY_KEY, new SoftReference<>(Pair.create(copy, document))); - } - return copy; - } - - private static void syncAcceptSlashR(Document originalDocument, Document documentCopy) { - if (!(originalDocument instanceof DocumentImpl) || !(documentCopy instanceof DocumentImpl)) { - return; - } - - ((DocumentImpl) documentCopy).setAcceptSlashR(((DocumentImpl) originalDocument).acceptsSlashR()); - } - private static boolean isAutocompleteOnInvocation(final CompletionType type) { final CodeInsightSettings settings = CodeInsightSettings.getInstance(); if (type == CompletionType.SMART) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionInitializationContextImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionInitializationContextImpl.java new file mode 100644 index 000000000000..9f8cb656a7ef --- /dev/null +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionInitializationContextImpl.java @@ -0,0 +1,26 @@ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. +package com.intellij.codeInsight.completion; + +import com.intellij.openapi.editor.Caret; +import com.intellij.openapi.editor.Editor; +import com.intellij.psi.PsiFile; +import org.jetbrains.annotations.NotNull; + +/** + * @author yole + */ +class CompletionInitializationContextImpl extends CompletionInitializationContext { + private final OffsetsInFile myHostOffsets; + + CompletionInitializationContextImpl(Editor editor, + @NotNull Caret caret, + PsiFile file, + CompletionType completionType, int invocationCount) { + super(editor, caret, file, completionType, invocationCount); + myHostOffsets = new OffsetsInFile(file, getOffsetMap()).toTopLevelFile(); + } + + OffsetsInFile getHostOffsets() { + return myHostOffsets; + } +} diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionInitializationUtil.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionInitializationUtil.java new file mode 100644 index 000000000000..af1aad635f35 --- /dev/null +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionInitializationUtil.java @@ -0,0 +1,213 @@ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. +package com.intellij.codeInsight.completion; + +import com.intellij.injected.editor.DocumentWindow; +import com.intellij.openapi.application.WriteAction; +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.editor.Caret; +import com.intellij.openapi.editor.Document; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.ex.util.EditorUtil; +import com.intellij.openapi.editor.impl.DocumentImpl; +import com.intellij.openapi.fileEditor.FileDocumentManager; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Key; +import com.intellij.openapi.util.Pair; +import com.intellij.openapi.util.Ref; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.psi.PsiDocumentManager; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; +import com.intellij.psi.impl.PsiFileEx; +import com.intellij.psi.impl.source.PsiFileImpl; +import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; +import com.intellij.psi.util.PsiUtilBase; +import com.intellij.reference.SoftReference; +import org.jetbrains.annotations.NotNull; + +import java.util.Objects; + +/** + * @author yole + */ +public class CompletionInitializationUtil { + private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.CompletionServiceUtil"); + + public static CompletionInitializationContextImpl createCompletionInitializationContext(@NotNull Project project, + @NotNull Editor editor, + @NotNull Caret caret, + int invocationCount, + CompletionType completionType) { + return WriteAction.compute(() -> { + EditorUtil.fillVirtualSpaceUntilCaret(editor); + PsiDocumentManager.getInstance(project).commitAllDocuments(); + CompletionAssertions.checkEditorValid(editor); + + final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(caret, project); + assert psiFile != null : "no PSI file: " + FileDocumentManager.getInstance().getFile(editor.getDocument()); + psiFile.putUserData(PsiFileEx.BATCH_REFERENCE_PROCESSING, Boolean.TRUE); + CompletionAssertions.assertCommitSuccessful(editor, psiFile); + + return runContributorsBeforeCompletion(editor, psiFile, invocationCount, caret, completionType); + }); + } + + private static CompletionInitializationContextImpl runContributorsBeforeCompletion(Editor editor, + PsiFile psiFile, + int invocationCount, + @NotNull Caret caret, + CompletionType completionType) { + final Ref current = Ref.create(null); + CompletionInitializationContextImpl context = new CompletionInitializationContextImpl(editor, caret, psiFile, completionType, invocationCount) { + CompletionContributor dummyIdentifierChanger; + + @Override + public void setDummyIdentifier(@NotNull String dummyIdentifier) { + super.setDummyIdentifier(dummyIdentifier); + + if (dummyIdentifierChanger != null) { + LOG.error("Changing the dummy identifier twice, already changed by " + dummyIdentifierChanger); + } + dummyIdentifierChanger = current.get(); + } + }; + Project project = psiFile.getProject(); + for (final CompletionContributor contributor : CompletionContributor.forLanguageHonorDumbness(context.getPositionLanguage(), project)) { + current.set(contributor); + contributor.beforeCompletion(context); + CompletionAssertions.checkEditorValid(editor); + assert !PsiDocumentManager.getInstance(project).isUncommited(editor.getDocument()) : "Contributor " + contributor + " left the document uncommitted"; + } + return context; + } + + public static CompletionParameters prepareCompletionParameters(CompletionInitializationContext initContext, + CompletionProcess process) { + CompletionProgressIndicatorBase indicator = (CompletionProgressIndicatorBase) process; + OffsetsInFile hostCopyOffsets = insertDummyIdentifier(initContext, indicator, indicator.getHostOffsets()); + if (hostCopyOffsets == null) { + return null; + } + + indicator.registerChildDisposable(hostCopyOffsets::getOffsets); + OffsetsInFile finalOffsets = toInjectedIfAny(initContext.getFile(), hostCopyOffsets); + indicator.registerChildDisposable(finalOffsets::getOffsets); + + return createCompletionParameters(initContext, indicator, finalOffsets); + } + + @NotNull + private static CompletionParameters createCompletionParameters(CompletionInitializationContext initContext, + CompletionProgressIndicatorBase indicator, OffsetsInFile finalOffsets) { + int offset = finalOffsets.getOffsets().getOffset(CompletionInitializationContext.START_OFFSET); + PsiFile fileCopy = finalOffsets.getFile(); + PsiFile originalFile = fileCopy.getOriginalFile(); + PsiElement insertedElement = findCompletionPositionLeaf(finalOffsets, offset, originalFile); + insertedElement.putUserData(CompletionContext.COMPLETION_CONTEXT_KEY, new CompletionContext(fileCopy, finalOffsets.getOffsets())); + return new CompletionParameters(insertedElement, originalFile, initContext.getCompletionType(), offset, initContext.getInvocationCount(), + initContext.getEditor(), indicator); + } + + + private static OffsetsInFile insertDummyIdentifier(CompletionInitializationContext initContext, + CompletionProgressIndicatorBase indicator, + OffsetsInFile topLevelOffsets) { + CompletionAssertions.checkEditorValid(initContext.getEditor()); + + Editor hostEditor = InjectedLanguageUtil.getTopLevelEditor(initContext.getEditor()); + OffsetMap hostMap = topLevelOffsets.getOffsets(); + + PsiFile hostCopy = obtainFileCopy(topLevelOffsets.getFile()); + Document copyDocument = Objects.requireNonNull(hostCopy.getViewProvider().getDocument()); + + String dummyIdentifier = initContext.getDummyIdentifier(); + int startOffset = hostMap.getOffset(CompletionInitializationContext.START_OFFSET); + int endOffset = hostMap.getOffset(CompletionInitializationContext.SELECTION_END_OFFSET); + + indicator.registerChildDisposable( + () -> new OffsetTranslator(hostEditor.getDocument(), initContext.getFile(), copyDocument, startOffset, endOffset, dummyIdentifier)); + + OffsetsInFile copyOffsets = topLevelOffsets.replaceInCopy(hostCopy, startOffset, endOffset, dummyIdentifier); + return hostCopy.isValid() ? copyOffsets : null; + } + + private static OffsetsInFile toInjectedIfAny(PsiFile originalFile, OffsetsInFile hostCopyOffsets) { + CompletionAssertions.assertHostInfo(hostCopyOffsets.getFile(), hostCopyOffsets.getOffsets()); + + int hostStartOffset = hostCopyOffsets.getOffsets().getOffset(CompletionInitializationContext.START_OFFSET); + OffsetsInFile translatedOffsets = hostCopyOffsets.toInjectedIfAny(hostStartOffset); + if (translatedOffsets != hostCopyOffsets) { + PsiFile injected = translatedOffsets.getFile(); + if (injected instanceof PsiFileImpl) { + ((PsiFileImpl)injected).setOriginalFile(originalFile); + } + DocumentWindow documentWindow = InjectedLanguageUtil.getDocumentWindow(injected); + CompletionAssertions.assertInjectedOffsets(hostStartOffset, injected, documentWindow); + + if (injected.getTextRange().contains(translatedOffsets.getOffsets().getOffset(CompletionInitializationContext.START_OFFSET))) { + return translatedOffsets; + } + } + + return hostCopyOffsets; + } + + @NotNull + private static PsiElement findCompletionPositionLeaf(OffsetsInFile offsets, int offset, PsiFile originalFile) { + PsiElement insertedElement = offsets.getFile().findElementAt(offset); + CompletionAssertions.assertCompletionPositionPsiConsistent(offsets, offset, originalFile, insertedElement); + return insertedElement; + } + + private static PsiFile obtainFileCopy(PsiFile file) { + final VirtualFile virtualFile = file.getVirtualFile(); + boolean mayCacheCopy = file.isPhysical() && + // we don't want to cache code fragment copies even if they appear to be physical + virtualFile != null && virtualFile.isInLocalFileSystem(); + if (mayCacheCopy) { + final Pair cached = SoftReference.dereference(file.getUserData(FILE_COPY_KEY)); + if (cached != null && isCopyUpToDate(cached.second, cached.first, file)) { + PsiFile copy = cached.first; + CompletionAssertions.assertCorrectOriginalFile("Cached", file, copy); + return copy; + } + } + + final PsiFile copy = (PsiFile)file.copy(); + if (copy.isPhysical() || copy.getViewProvider().isEventSystemEnabled()) { + LOG.error("File copy should be non-physical and non-event-system-enabled! Language=" + file.getLanguage() + "; file=" + file + " of " + file.getClass()); + } + CompletionAssertions.assertCorrectOriginalFile("New", file, copy); + + if (mayCacheCopy) { + final Document document = copy.getViewProvider().getDocument(); + assert document != null; + syncAcceptSlashR(file.getViewProvider().getDocument(), document); + file.putUserData(FILE_COPY_KEY, new SoftReference<>(Pair.create(copy, document))); + } + return copy; + } + + private static final Key>> FILE_COPY_KEY = Key.create("CompletionFileCopy"); + + private static boolean isCopyUpToDate(Document document, @NotNull PsiFile copyFile, @NotNull PsiFile originalFile) { + if (!copyFile.getClass().equals(originalFile.getClass()) || + !copyFile.isValid() || + !copyFile.getName().equals(originalFile.getName())) { + return false; + } + // the psi file cache might have been cleared by some external activity, + // in which case PSI-document sync may stop working + PsiFile current = PsiDocumentManager.getInstance(copyFile.getProject()).getPsiFile(document); + return current != null && current.getViewProvider().getPsi(copyFile.getLanguage()) == copyFile; + } + + private static void syncAcceptSlashR(Document originalDocument, Document documentCopy) { + if (!(originalDocument instanceof DocumentImpl) || !(documentCopy instanceof DocumentImpl)) { + return; + } + + ((DocumentImpl) documentCopy).setAcceptSlashR(((DocumentImpl) originalDocument).acceptsSlashR()); + } + +} diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java index 1d6664d329af..ac353a9b8d5c 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2016 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.completion; @@ -31,7 +17,6 @@ import com.intellij.diagnostic.PerformanceWatcher; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.injected.editor.DocumentWindow; import com.intellij.injected.editor.EditorWindow; -import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; @@ -43,7 +28,6 @@ import com.intellij.openapi.editor.Editor; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressManager; -import com.intellij.openapi.progress.util.ProgressIndicatorBase; import com.intellij.openapi.progress.util.ProgressWrapper; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.IndexNotReadyException; @@ -83,14 +67,13 @@ import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; /** * Please don't use this class directly from plugins */ @SuppressWarnings("deprecation") @Deprecated -public class CompletionProgressIndicator extends ProgressIndicatorBase implements CompletionProcess, Disposable { +public class CompletionProgressIndicator extends CompletionProgressIndicatorBase { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.CompletionProgressIndicator"); private final Editor myEditor; @NotNull @@ -99,8 +82,6 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement private final CodeCompletionHandlerBase myHandler; private final CompletionLookupArranger myArranger; private final CompletionType myCompletionType; - private final int myInvocationCount; - private OffsetsInFile myHostOffsets; private final LookupImpl myLookup; private final Alarm mySuppressTimeoutAlarm = new Alarm(this); private final MergingUpdateQueue myQueue; @@ -137,18 +118,16 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement private final List myDelayedMiddleMatches = ContainerUtil.newArrayList(); private final int myStartCaret; private final CompletionThreadingBase myThreading; - private final Object myLock = new String("CompletionProgressIndicator"); CompletionProgressIndicator(Editor editor, @NotNull Caret caret, int invocationCount, CodeCompletionHandlerBase handler, OffsetMap offsetMap, OffsetsInFile hostOffsets, boolean hasModifiers, LookupImpl lookup) { + super(invocationCount, hostOffsets); myEditor = editor; myCaret = caret; myHandler = handler; myCompletionType = handler.completionType; - myInvocationCount = invocationCount; myOffsetMap = offsetMap; - myHostOffsets = hostOffsets; myLookup = lookup; myStartCaret = myEditor.getCaretModel().getOffset(); myThreading = ApplicationManager.getApplication().isWriteAccessAllowed() ? new SyncCompletion() : new AsyncCompletion(); @@ -193,10 +172,6 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement return myOffsetMap; } - OffsetsInFile getHostOffsets() { - return myHostOffsets; - } - void duringCompletion(CompletionInitializationContext initContext, CompletionParameters parameters) { if (isAutopopupCompletion() && shouldPreselectFirstSuggestion(parameters)) { myLookup.setFocusDegree(CodeInsightSettings.getInstance().SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS @@ -285,10 +260,6 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement } } - @Override - public void dispose() { - } - private static int findReplacementOffset(int selectionEndOffset, PsiReference reference) { final List ranges = ReferenceRange.getAbsoluteRanges(reference); for (TextRange range : ranges) { @@ -513,14 +484,6 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement } } - void registerChildDisposable(@NotNull Supplier child) { - synchronized (myLock) { - // avoid registering stuff on an indicator being disposed concurrently - checkCanceled(); - Disposer.register(this, child.get()); - } - } - @TestOnly public static void cleanupForNextTest() { CompletionProgressIndicator currentCompletion = CompletionServiceImpl.getCompletionService().getCurrentCompletion(); @@ -648,11 +611,6 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement return true; } - @Override - public boolean isAutopopupCompletion() { - return myInvocationCount == 0; - } - @NotNull public Project getProject() { return ObjectUtils.assertNotNull(myEditor.getProject()); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicatorBase.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicatorBase.java new file mode 100644 index 000000000000..1890511f5c0a --- /dev/null +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicatorBase.java @@ -0,0 +1,49 @@ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. +package com.intellij.codeInsight.completion; + +import com.intellij.openapi.Disposable; +import com.intellij.openapi.progress.util.ProgressIndicatorBase; +import com.intellij.openapi.util.Disposer; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Supplier; + +/** + * @author yole + */ +public class CompletionProgressIndicatorBase extends ProgressIndicatorBase implements CompletionProcess, Disposable { + protected final int myInvocationCount; + protected final Object myLock = new String("CompletionProgressIndicator"); + protected OffsetsInFile myHostOffsets; + + CompletionProgressIndicatorBase(int invocationCount, OffsetsInFile hostOffsets) { + myInvocationCount = invocationCount; + myHostOffsets = hostOffsets; + } + + public CompletionProgressIndicatorBase(CompletionInitializationContext context) { + myInvocationCount = context.getInvocationCount(); + myHostOffsets = ((CompletionInitializationContextImpl) context).getHostOffsets(); + } + + @Override + public boolean isAutopopupCompletion() { + return myInvocationCount == 0; + } + + OffsetsInFile getHostOffsets() { + return myHostOffsets; + } + + void registerChildDisposable(@NotNull Supplier child) { + synchronized (myLock) { + // avoid registering stuff on an indicator being disposed concurrently + checkCanceled(); + Disposer.register(this, child.get()); + } + } + + @Override + public void dispose() { + } +} diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/impl/CompletionServiceImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/impl/CompletionServiceImpl.java index bf393fd69674..92cb935d27e8 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/impl/CompletionServiceImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/impl/CompletionServiceImpl.java @@ -1,24 +1,12 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.completion.impl; import com.intellij.codeInsight.completion.*; import com.intellij.codeInsight.lookup.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.editor.Caret; +import com.intellij.openapi.editor.Editor; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; @@ -80,6 +68,18 @@ public final class CompletionServiceImpl extends CompletionService { } } + @Override + public CompletionParameters createCompletionParameters(@NotNull Project project, + @NotNull Editor editor, + @NotNull Caret caret, + int invocationCount, + CompletionType completionType) { + CompletionInitializationContext context = CompletionInitializationUtil.createCompletionInitializationContext(project, editor, caret, + invocationCount, completionType); + CompletionProgressIndicatorBase progress = new CompletionProgressIndicatorBase(context); + return CompletionInitializationUtil.prepareCompletionParameters(context, progress); + } + @Override public CompletionResultSet createResultSet(final CompletionParameters parameters, final Consumer consumer, @NotNull final CompletionContributor contributor) { From 815d14e153793cb4ffdf562480d20401c0a9fb0e Mon Sep 17 00:00:00 2001 From: Dmitry Jemerov Date: Wed, 7 Mar 2018 18:46:20 +0100 Subject: [PATCH 16/22] Don't extend ProgressIndicatorBase in base CompletionProcess implementation --- .../CompletionInitializationUtil.java | 8 ++-- ...orBase.java => CompletionProcessBase.java} | 17 +++---- .../completion/CompletionProcessEx.java | 15 +++++++ .../CompletionProgressIndicator.java | 44 ++++++++++++++++--- .../impl/CompletionServiceImpl.java | 2 +- 5 files changed, 63 insertions(+), 23 deletions(-) rename platform/lang-impl/src/com/intellij/codeInsight/completion/{CompletionProgressIndicatorBase.java => CompletionProcessBase.java} (64%) create mode 100644 platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProcessEx.java diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionInitializationUtil.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionInitializationUtil.java index af1aad635f35..6859f6fda345 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionInitializationUtil.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionInitializationUtil.java @@ -82,8 +82,8 @@ public class CompletionInitializationUtil { } public static CompletionParameters prepareCompletionParameters(CompletionInitializationContext initContext, - CompletionProcess process) { - CompletionProgressIndicatorBase indicator = (CompletionProgressIndicatorBase) process; + CompletionProcessEx process) { + CompletionProcessEx indicator = (CompletionProcessEx) process; OffsetsInFile hostCopyOffsets = insertDummyIdentifier(initContext, indicator, indicator.getHostOffsets()); if (hostCopyOffsets == null) { return null; @@ -98,7 +98,7 @@ public class CompletionInitializationUtil { @NotNull private static CompletionParameters createCompletionParameters(CompletionInitializationContext initContext, - CompletionProgressIndicatorBase indicator, OffsetsInFile finalOffsets) { + CompletionProcessEx indicator, OffsetsInFile finalOffsets) { int offset = finalOffsets.getOffsets().getOffset(CompletionInitializationContext.START_OFFSET); PsiFile fileCopy = finalOffsets.getFile(); PsiFile originalFile = fileCopy.getOriginalFile(); @@ -110,7 +110,7 @@ public class CompletionInitializationUtil { private static OffsetsInFile insertDummyIdentifier(CompletionInitializationContext initContext, - CompletionProgressIndicatorBase indicator, + CompletionProcessEx indicator, OffsetsInFile topLevelOffsets) { CompletionAssertions.checkEditorValid(initContext.getEditor()); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicatorBase.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProcessBase.java similarity index 64% rename from platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicatorBase.java rename to platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProcessBase.java index 1890511f5c0a..83262e7578b3 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicatorBase.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProcessBase.java @@ -2,7 +2,6 @@ package com.intellij.codeInsight.completion; import com.intellij.openapi.Disposable; -import com.intellij.openapi.progress.util.ProgressIndicatorBase; import com.intellij.openapi.util.Disposer; import org.jetbrains.annotations.NotNull; @@ -11,17 +10,12 @@ import java.util.function.Supplier; /** * @author yole */ -public class CompletionProgressIndicatorBase extends ProgressIndicatorBase implements CompletionProcess, Disposable { +public class CompletionProcessBase implements CompletionProcessEx, Disposable { protected final int myInvocationCount; protected final Object myLock = new String("CompletionProgressIndicator"); protected OffsetsInFile myHostOffsets; - CompletionProgressIndicatorBase(int invocationCount, OffsetsInFile hostOffsets) { - myInvocationCount = invocationCount; - myHostOffsets = hostOffsets; - } - - public CompletionProgressIndicatorBase(CompletionInitializationContext context) { + public CompletionProcessBase(CompletionInitializationContext context) { myInvocationCount = context.getInvocationCount(); myHostOffsets = ((CompletionInitializationContextImpl) context).getHostOffsets(); } @@ -31,14 +25,15 @@ public class CompletionProgressIndicatorBase extends ProgressIndicatorBase imple return myInvocationCount == 0; } - OffsetsInFile getHostOffsets() { + @Override + public OffsetsInFile getHostOffsets() { return myHostOffsets; } - void registerChildDisposable(@NotNull Supplier child) { + @Override + public void registerChildDisposable(@NotNull Supplier child) { synchronized (myLock) { // avoid registering stuff on an indicator being disposed concurrently - checkCanceled(); Disposer.register(this, child.get()); } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProcessEx.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProcessEx.java new file mode 100644 index 000000000000..cd01d5dad362 --- /dev/null +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProcessEx.java @@ -0,0 +1,15 @@ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. +package com.intellij.codeInsight.completion; + +import com.intellij.openapi.Disposable; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Supplier; + +/** + * @author yole + */ +interface CompletionProcessEx extends CompletionProcess { + OffsetsInFile getHostOffsets(); + void registerChildDisposable(@NotNull Supplier child); +} diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java index ac353a9b8d5c..be01578f822a 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java @@ -17,6 +17,7 @@ import com.intellij.diagnostic.PerformanceWatcher; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.injected.editor.DocumentWindow; import com.intellij.injected.editor.EditorWindow; +import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; @@ -28,6 +29,7 @@ import com.intellij.openapi.editor.Editor; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressManager; +import com.intellij.openapi.progress.util.ProgressIndicatorBase; import com.intellij.openapi.progress.util.ProgressWrapper; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.IndexNotReadyException; @@ -67,13 +69,14 @@ import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; /** * Please don't use this class directly from plugins */ @SuppressWarnings("deprecation") @Deprecated -public class CompletionProgressIndicator extends CompletionProgressIndicatorBase { +public class CompletionProgressIndicator extends ProgressIndicatorBase implements CompletionProcessEx, Disposable { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.CompletionProgressIndicator"); private final Editor myEditor; @NotNull @@ -82,6 +85,8 @@ public class CompletionProgressIndicator extends CompletionProgressIndicatorBase private final CodeCompletionHandlerBase myHandler; private final CompletionLookupArranger myArranger; private final CompletionType myCompletionType; + private final int myInvocationCount; + private OffsetsInFile myHostOffsets; private final LookupImpl myLookup; private final Alarm mySuppressTimeoutAlarm = new Alarm(this); private final MergingUpdateQueue myQueue; @@ -118,16 +123,18 @@ public class CompletionProgressIndicator extends CompletionProgressIndicatorBase private final List myDelayedMiddleMatches = ContainerUtil.newArrayList(); private final int myStartCaret; private final CompletionThreadingBase myThreading; + private final Object myLock = new String("CompletionProgressIndicator"); CompletionProgressIndicator(Editor editor, @NotNull Caret caret, int invocationCount, CodeCompletionHandlerBase handler, OffsetMap offsetMap, OffsetsInFile hostOffsets, boolean hasModifiers, LookupImpl lookup) { - super(invocationCount, hostOffsets); myEditor = editor; myCaret = caret; myHandler = handler; myCompletionType = handler.completionType; + myInvocationCount = invocationCount; myOffsetMap = offsetMap; + myHostOffsets = hostOffsets; myLookup = lookup; myStartCaret = myEditor.getCaretModel().getOffset(); myThreading = ApplicationManager.getApplication().isWriteAccessAllowed() ? new SyncCompletion() : new AsyncCompletion(); @@ -172,6 +179,11 @@ public class CompletionProgressIndicator extends CompletionProgressIndicatorBase return myOffsetMap; } + @Override + public OffsetsInFile getHostOffsets() { + return myHostOffsets; + } + void duringCompletion(CompletionInitializationContext initContext, CompletionParameters parameters) { if (isAutopopupCompletion() && shouldPreselectFirstSuggestion(parameters)) { myLookup.setFocusDegree(CodeInsightSettings.getInstance().SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS @@ -190,9 +202,9 @@ public class CompletionProgressIndicator extends CompletionProgressIndicatorBase if (reference != null) { final int replacementOffset = findReplacementOffset(selectionEndOffset, reference); if (replacementOffset > document.getTextLength()) { - LOG.error("Invalid replacementOffset: " + replacementOffset + " returned by reference " + reference + " of " + reference.getClass() + - "; doc=" + document + - "; doc actual=" + (document == initContext.getFile().getViewProvider().getDocument()) + + LOG.error("Invalid replacementOffset: " + replacementOffset + " returned by reference " + reference + " of " + reference.getClass() + + "; doc=" + document + + "; doc actual=" + (document == initContext.getFile().getViewProvider().getDocument()) + "; doc committed=" + PsiDocumentManager.getInstance(getProject()).isCommitted(document)); } else { initContext.setReplacementOffset(replacementOffset); @@ -211,14 +223,14 @@ public class CompletionProgressIndicator extends CompletionProgressIndicatorBase myHostOffsets = new OffsetsInFile(initContext.getFile(), initContext.getOffsetMap()).toTopLevelFile(); } } - + private void addDefaultAdvertisements(CompletionParameters parameters) { if (DumbService.isDumb(getProject())) { addAdvertisement("The results might be incomplete while indexing is in progress", MessageType.WARNING.getPopupBackground()); return; } - + advertiseTabReplacement(parameters); if (isAutopopupCompletion()) { if (shouldPreselectFirstSuggestion(parameters) && !CodeInsightSettings.getInstance().SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS) { @@ -260,6 +272,10 @@ public class CompletionProgressIndicator extends CompletionProgressIndicatorBase } } + @Override + public void dispose() { + } + private static int findReplacementOffset(int selectionEndOffset, PsiReference reference) { final List ranges = ReferenceRange.getAbsoluteRanges(reference); for (TextRange range : ranges) { @@ -484,6 +500,15 @@ public class CompletionProgressIndicator extends CompletionProgressIndicatorBase } } + @Override + public void registerChildDisposable(@NotNull Supplier child) { + synchronized (myLock) { + // avoid registering stuff on an indicator being disposed concurrently + checkCanceled(); + Disposer.register(this, child.get()); + } + } + @TestOnly public static void cleanupForNextTest() { CompletionProgressIndicator currentCompletion = CompletionServiceImpl.getCompletionService().getCurrentCompletion(); @@ -611,6 +636,11 @@ public class CompletionProgressIndicator extends CompletionProgressIndicatorBase return true; } + @Override + public boolean isAutopopupCompletion() { + return myInvocationCount == 0; + } + @NotNull public Project getProject() { return ObjectUtils.assertNotNull(myEditor.getProject()); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/impl/CompletionServiceImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/impl/CompletionServiceImpl.java index 92cb935d27e8..82a0e5936eae 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/impl/CompletionServiceImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/impl/CompletionServiceImpl.java @@ -76,7 +76,7 @@ public final class CompletionServiceImpl extends CompletionService { CompletionType completionType) { CompletionInitializationContext context = CompletionInitializationUtil.createCompletionInitializationContext(project, editor, caret, invocationCount, completionType); - CompletionProgressIndicatorBase progress = new CompletionProgressIndicatorBase(context); + CompletionProcessBase progress = new CompletionProcessBase(context); return CompletionInitializationUtil.prepareCompletionParameters(context, progress); } From a2380049598f40b0999b2013195f901474489e5e Mon Sep 17 00:00:00 2001 From: Dmitry Jemerov Date: Thu, 8 Mar 2018 10:23:20 +0100 Subject: [PATCH 17/22] Revert API for accessing LineMarkerInfo from RangeHighlighter --- .../com/intellij/codeInsight/daemon/LineMarkerInfo.java | 7 ------- .../codeInsight/daemon/impl/LineMarkersUtil.java | 9 ++++++--- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/platform/lang-api/src/com/intellij/codeInsight/daemon/LineMarkerInfo.java b/platform/lang-api/src/com/intellij/codeInsight/daemon/LineMarkerInfo.java index f4de6375bc78..3670515b821c 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/daemon/LineMarkerInfo.java +++ b/platform/lang-api/src/com/intellij/codeInsight/daemon/LineMarkerInfo.java @@ -11,7 +11,6 @@ import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.editor.markup.SeparatorPlacement; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.util.Comparing; -import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; @@ -26,7 +25,6 @@ import java.awt.*; public class LineMarkerInfo { private static final Logger LOG = Logger.getInstance(LineMarkerInfo.class); - public static final Key LINE_MARKER_INFO = Key.create("LINE_MARKER_INFO"); protected final Icon myIcon; private final SmartPsiElementPointer elementRef; @@ -146,11 +144,6 @@ public class LineMarkerInfo { return myNavigationHandler; } - @SuppressWarnings({"unused", "unchecked"}) - public static LineMarkerInfo fromRangeHighlighter(RangeHighlighter rangeHighlighter) { - return (LineMarkerInfo) rangeHighlighter.getUserData(LINE_MARKER_INFO); - } - public static class LineMarkerGutterIconRenderer extends GutterIconRenderer { private final LineMarkerInfo myInfo; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LineMarkersUtil.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LineMarkersUtil.java index f43c9d5e4472..71c7c150a078 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LineMarkersUtil.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LineMarkersUtil.java @@ -12,6 +12,7 @@ import com.intellij.openapi.editor.impl.DocumentMarkupModel; import com.intellij.openapi.editor.markup.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; +import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Segment; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; @@ -97,7 +98,7 @@ class LineMarkersUtil { markerEx.setLineSeparatorColor(info.separatorColor); markerEx.setLineSeparatorPlacement(info.separatorPlacement); - markerEx.putUserData(LineMarkerInfo.LINE_MARKER_INFO, info); + markerEx.putUserData(LINE_MARKER_INFO, info); }); MarkupEditorFilter editorFilter = info.getEditorFilter(); @@ -107,7 +108,7 @@ class LineMarkersUtil { } if (!newHighlighter) { - highlighter.putUserData(LineMarkerInfo.LINE_MARKER_INFO, info); + highlighter.putUserData(LINE_MARKER_INFO, info); LineMarkerInfo.LineMarkerGutterIconRenderer oldRenderer = highlighter.getGutterIconRenderer() instanceof LineMarkerInfo.LineMarkerGutterIconRenderer ? (LineMarkerInfo.LineMarkerGutterIconRenderer)highlighter.getGutterIconRenderer() : null; boolean rendererChanged = oldRenderer == null || newRenderer == null || !newRenderer.equals(oldRenderer); @@ -150,6 +151,8 @@ class LineMarkersUtil { } private static LineMarkerInfo getLineMarkerInfo(@NotNull RangeHighlighter highlighter) { - return highlighter.getUserData(LineMarkerInfo.LINE_MARKER_INFO); + return highlighter.getUserData(LINE_MARKER_INFO); } + + private static final Key LINE_MARKER_INFO = Key.create("LINE_MARKER_INFO"); } From 8eddbb3fdbeb0504c1e2330a8b08f1834351e160 Mon Sep 17 00:00:00 2001 From: Michael Golubev Date: Thu, 8 Mar 2018 10:33:00 +0100 Subject: [PATCH 18/22] fixed possible IAE for @NotNull component in FocusManager#requestFocus - better fix for IDEA-187015, followup for IDEA-CR-30379 --- .../src/com/intellij/ui/content/impl/ContentManagerImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/platform-impl/src/com/intellij/ui/content/impl/ContentManagerImpl.java b/platform/platform-impl/src/com/intellij/ui/content/impl/ContentManagerImpl.java index 854eda3028dc..45d408909fc3 100644 --- a/platform/platform-impl/src/com/intellij/ui/content/impl/ContentManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/ui/content/impl/ContentManagerImpl.java @@ -491,7 +491,7 @@ public class ContentManagerImpl implements ContentManager, PropertyChangeListene boolean enabledFocus = getFocusManager().isFocusTransferEnabled(); if (focused || requestFocus) { if (enabledFocus) { - return getFocusManager().requestFocus(myComponent, true).doWhenProcessed(() -> selection.run().notify(result)); + return getFocusManager().requestFocus(getComponent(), true).doWhenProcessed(() -> selection.run().notify(result)); } } return selection.run().notify(result); From d58d4ccd5fd93e22a6394b369b870d833984ca7a Mon Sep 17 00:00:00 2001 From: Dmitry Jemerov Date: Thu, 8 Mar 2018 10:40:37 +0100 Subject: [PATCH 19/22] Allow passing null Presentation to AnActionEvent.createFromInputEvent() --- .../openapi/actionSystem/AnActionEvent.java | 22 ++++--------------- 1 file changed, 4 insertions(+), 18 deletions(-) diff --git a/platform/editor-ui-api/src/com/intellij/openapi/actionSystem/AnActionEvent.java b/platform/editor-ui-api/src/com/intellij/openapi/actionSystem/AnActionEvent.java index 77c0879c789e..37defaaa603e 100644 --- a/platform/editor-ui-api/src/com/intellij/openapi/actionSystem/AnActionEvent.java +++ b/platform/editor-ui-api/src/com/intellij/openapi/actionSystem/AnActionEvent.java @@ -1,18 +1,4 @@ -/* - * Copyright 2000-2017 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. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.actionSystem; import com.intellij.ide.DataManager; @@ -119,7 +105,7 @@ public class AnActionEvent implements PlaceProvider { @NotNull public static AnActionEvent createFromInputEvent(@Nullable InputEvent event, @NotNull String place, - @NotNull Presentation presentation, + @Nullable Presentation presentation, @NotNull DataContext dataContext) { return createFromInputEvent(event, place, presentation, dataContext, false, false); } @@ -127,11 +113,11 @@ public class AnActionEvent implements PlaceProvider { @NotNull public static AnActionEvent createFromInputEvent(@Nullable InputEvent event, @NotNull String place, - @NotNull Presentation presentation, + @Nullable Presentation presentation, @NotNull DataContext dataContext, boolean isContextMenuAction, boolean isToolbarAction) { - return new AnActionEvent(event, dataContext, place, presentation, ActionManager.getInstance(), + return new AnActionEvent(event, dataContext, place, presentation == null ? new Presentation() : presentation, ActionManager.getInstance(), event == null ? 0 : event.getModifiers(), isContextMenuAction, isToolbarAction); } From 39452636c511adfe03112c4a61d135712e528a9f Mon Sep 17 00:00:00 2001 From: Ivan Semenov Date: Thu, 8 Mar 2018 13:24:42 +0300 Subject: [PATCH 20/22] Use Git from PATH in tests --- .../intellij/testFramework/vcs/ExecutableHelper.java | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/platform/vcs-tests/src/com/intellij/testFramework/vcs/ExecutableHelper.java b/platform/vcs-tests/src/com/intellij/testFramework/vcs/ExecutableHelper.java index 4fc7d07d6cb5..af97c6eafd1a 100644 --- a/platform/vcs-tests/src/com/intellij/testFramework/vcs/ExecutableHelper.java +++ b/platform/vcs-tests/src/com/intellij/testFramework/vcs/ExecutableHelper.java @@ -23,8 +23,8 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; -import java.util.Arrays; import java.util.Collection; +import java.util.Collections; /** * @author Sergey Karashevich @@ -34,17 +34,16 @@ public class ExecutableHelper { private static final Logger LOG = Logger.getInstance(ExecutableHelper.class); private static final String GIT_EXECUTABLE_ENV = "IDEA_TEST_GIT_EXECUTABLE"; - private static final String TEAMCITY_GIT_EXECUTABLE_ENV = "TEAMCITY_GIT_PATH"; public static String findGitExecutable() { - return findExecutable("Git", "git", "git.exe", Arrays.asList(GIT_EXECUTABLE_ENV, TEAMCITY_GIT_EXECUTABLE_ENV)); + return findExecutable("Git", "git", "git.exe", Collections.singletonList(GIT_EXECUTABLE_ENV)); } @NotNull public static String findExecutable(@NotNull String programName, - @NotNull String unixExec, - @NotNull String winExec, - @NotNull Collection envs) { + @NotNull String unixExec, + @NotNull String winExec, + @NotNull Collection envs) { String exec = findEnvValue(programName, envs); if (exec != null) { return exec; @@ -78,5 +77,4 @@ public class ExecutableHelper { LOG.info(msg); } } - } From 877b2424ce584fba49372465e88777be5a7f2556 Mon Sep 17 00:00:00 2001 From: "Anna.Kozlova" Date: Thu, 8 Mar 2018 11:49:25 +0100 Subject: [PATCH 21/22] inference: don't process lambda return expressions for void return type those lambda return expressions can't influence containing call inference according to lambda constraint; which means that no additional inference variables could be propagated during inference process hence exception constraints could operate with proper types which are in fact type parameters - which would lead to unhandled exceptions on the top level (IDEA-187930) --- .../graphInference/InferenceSession.java | 2 +- .../UnhandledExceptionInLambdaChain.java | 56 +++++++++++++++++++ .../lambda/NewLambdaHighlightingTest.java | 1 + 3 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/UnhandledExceptionInLambdaChain.java diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java index 8ad03948b1a8..a0d53a8c3810 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java @@ -501,7 +501,7 @@ public class InferenceSession { boolean addConstraint, PsiSubstitutor initialSubstitutor) { final PsiType interfaceReturnType = LambdaUtil.getFunctionalInterfaceReturnType(parameterType); - if (interfaceReturnType != null) { + if (interfaceReturnType != null && !PsiType.VOID.equals(interfaceReturnType)) { final List returnExpressions = LambdaUtil.getReturnExpressions(lambdaExpression); for (PsiExpression returnExpression : returnExpressions) { processReturnExpression(additionalConstraints, ignoredConstraints, returnExpression, interfaceReturnType, addConstraint, initialSubstitutor); diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/UnhandledExceptionInLambdaChain.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/UnhandledExceptionInLambdaChain.java new file mode 100644 index 000000000000..c39a082ae48b --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/UnhandledExceptionInLambdaChain.java @@ -0,0 +1,56 @@ + +import java.io.IOException; + +class Test { + + interface ThrowableRunnable { + void run() throws T; + } + + interface ThrowableComputable { + R compute() throws E; + } + + private void doTest(ThrowableRunnable action) { } + + + public void testNoNotificationForWorkspace() { + doTest(() -> computeAndWait(() -> foo())); + } + + private String foo() throws IOException { + return null; + } + + + public static R computeAndWait(ThrowableComputable action) throws E { + return null; + } +} + +class TestWithImplicitLambda { + + interface ThrowableRunnable { + void run(int k) throws T; + } + + interface ThrowableComputable { + R compute() throws E; + } + + private void doTest(ThrowableRunnable action) { } + + + public void testNoNotificationForWorkspace() { + doTest((k) -> computeAndWait(() -> foo())); + } + + private String foo() throws IOException { + return null; + } + + + public static R computeAndWait(ThrowableComputable action) throws E { + return null; + } +} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/lambda/NewLambdaHighlightingTest.java b/java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/lambda/NewLambdaHighlightingTest.java index 16a469412910..74216f085a77 100644 --- a/java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/lambda/NewLambdaHighlightingTest.java +++ b/java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/lambda/NewLambdaHighlightingTest.java @@ -164,6 +164,7 @@ public class NewLambdaHighlightingTest extends LightDaemonAnalyzerTestCase { public void testVoidValueCompatibilityWithBreakInSwitch() { doTest(); } public void testExceptionInferenceForVarargMethods() { doTest(); } public void testConditionalBooleanAsFunctionalInterfaceType() { doTest(); } + public void testUnhandledExceptionInLambdaChain() { doTest(); } private void doTest() { IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_8, getModule(), getTestRootDisposable()); From b84d39eef33c7b758e59168db11c2879b78dbebb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yann=20C=C3=A9bron?= Date: Thu, 8 Mar 2018 12:28:11 +0100 Subject: [PATCH 22/22] Revert: IDEA-181529 return last selected editor before others IDEA-CR-30306 --- .../openapi/fileEditor/impl/FileEditorManagerImpl.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java index 948f0cd8e1b8..432f63802b7e 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java @@ -1249,12 +1249,11 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Persis @Override @NotNull public FileEditor[] getSelectedEditors() { - Set selectedEditors = new LinkedHashSet<>(); - EditorComposite selected = getLastSelected(); - if (selected != null) selectedEditors.add(selected.getSelectedEditor()); + Set selectedEditors = new HashSet<>(); for (EditorsSplitters each : getAllSplitters()) { ContainerUtil.addAll(selectedEditors, each.getSelectedEditors()); } + return selectedEditors.toArray(new FileEditor[0]); }