diff --git a/build/conf/nsis/paths.nsi b/build/conf/nsis/paths.nsi index 0e9299aaffba..c9e28527f1ea 100644 --- a/build/conf/nsis/paths.nsi +++ b/build/conf/nsis/paths.nsi @@ -1,6 +1,6 @@ ; Installer images !define IMAGES_LOCATION "${BASE_DIR}\build\images\idea" -!define LICENSE_FILE "${BASE_DIR}\license\IDEA_license" +;!define LICENSE_FILE "${BASE_DIR}\license\IDEA_license" !define PRODUCT_PROPERTIES_FILE "${BASE_DIR}\out\release\dist.all\bin\idea.properties" !define PRODUCT_VM_OPTIONS_NAME idea*.exe.vmoptions !define PRODUCT_VM_OPTIONS_FILE "${BASE_DIR}\out\release\dist.win\bin\${PRODUCT_VM_OPTIONS_NAME}" \ No newline at end of file diff --git a/build/scripts/dist.gant b/build/scripts/dist.gant index 652a97d759bf..607a28263ff1 100644 --- a/build/scripts/dist.gant +++ b/build/scripts/dist.gant @@ -144,8 +144,11 @@ def layoutAll(Map args, String home, String out, Paths _paths = null, buildJps = include(name: "*.*") } } + dir("license") { - fileset(dir: "${home}/license") + fileset(dir: "${home}/license") { + exclude(name: "placeholder.txt") + } } fileset(file: "${home}/LICENSE.txt") fileset(file: "${home}/NOTICE.txt") diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/CompoundPositionManager.java b/java/debugger/impl/src/com/intellij/debugger/engine/CompoundPositionManager.java index f17787b67de6..52665815abb2 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/CompoundPositionManager.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/CompoundPositionManager.java @@ -79,6 +79,7 @@ public class CompoundPositionManager extends PositionManagerEx implements MultiR return defaultValue; } + @Nullable @Override public SourcePosition getSourcePosition(final Location location) { if (location == null) return null; diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java index 43b131c92c25..2ed9b5283ada 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java @@ -20,6 +20,7 @@ import com.intellij.debugger.NoDataException; import com.intellij.debugger.PositionManager; import com.intellij.debugger.SourcePosition; import com.intellij.debugger.engine.evaluation.EvaluateException; +import com.intellij.debugger.impl.DebuggerUtilsEx; import com.intellij.debugger.jdi.VirtualMachineProxyImpl; import com.intellij.debugger.requests.ClassPrepareRequestor; import com.intellij.execution.filters.LineNumbersMapping; @@ -122,6 +123,7 @@ public class PositionManagerImpl implements PositionManager, MultiRequestPositio }); } + @Nullable public SourcePosition getSourcePosition(final Location location) throws NoDataException { DebuggerManagerThreadImpl.assertIsManagerThread(); if(location == null) { @@ -254,51 +256,17 @@ public class PositionManagerImpl implements PositionManager, MultiRequestPositio PsiFile file = original.getFile(); int line = original.getLine(); if (LambdaMethodFilter.isLambdaName(myExpectedMethodName) && myLambdaOrdinal > -1) { + List lambdas = DebuggerUtilsEx.collectLambdas(original, false); + Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file); if (document == null || line >= document.getLineCount()) { return original; } - PsiElement element = original.getElementAt(); - TextRange lineRange = new TextRange(document.getLineStartOffset(line), document.getLineEndOffset(line)); - do { - PsiElement parent = element.getParent(); - if (parent == null || (parent.getTextOffset() < lineRange.getStartOffset())) { - break; - } - element = parent; - } - while(true); - final List lambdas = new ArrayList(3); - final PsiElementVisitor lambdaCollector = new JavaRecursiveElementVisitor() { - @Override - public void visitLambdaExpression(PsiLambdaExpression expression) { - super.visitLambdaExpression(expression); - lambdas.add(expression); - } - }; - element.accept(lambdaCollector); - // add initial lambda if we're inside already - NavigatablePsiElement method = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiLambdaExpression.class); - if (method instanceof PsiLambdaExpression) { - lambdas.add((PsiLambdaExpression)method); - } - for (PsiElement sibling = getNextElement(element); sibling != null; sibling = getNextElement(sibling)) { - if (!lineRange.intersects(sibling.getTextRange())) { - break; - } - sibling.accept(lambdaCollector); - } if (myLambdaOrdinal < lambdas.size()) { - PsiElement body = lambdas.get(myLambdaOrdinal).getBody(); - if (body instanceof PsiCodeBlock) { - for (PsiStatement statement : ((PsiCodeBlock)body).getStatements()) { - if (lineRange.intersects(statement.getTextRange())) { - body = statement; - break; - } - } + PsiElement firstElem = DebuggerUtilsEx.getFirstElementOnTheLine(lambdas.get(myLambdaOrdinal), document, line); + if (firstElem != null) { + return SourcePosition.createFromElement(firstElem); } - return SourcePosition.createFromElement(body); } } else { @@ -316,14 +284,6 @@ public class PositionManagerImpl implements PositionManager, MultiRequestPositio }); } - private static PsiElement getNextElement(PsiElement element) { - PsiElement sibling = element.getNextSibling(); - if (sibling != null) return sibling; - element = element.getParent(); - if (element != null) return getNextElement(element); - return null; - } - @Nullable @Override public RangeHighlighter createHighlighter(Document document, Project project, TextAttributes attributes) { diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextRunnable.java b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextRunnable.java index 6df6a1463d71..671bd9813bb9 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextRunnable.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextRunnable.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * 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. @@ -15,8 +15,6 @@ */ package com.intellij.debugger.engine; -import com.intellij.debugger.engine.SuspendContextImpl; - public interface SuspendContextRunnable { void run(SuspendContextImpl suspendContext) throws Exception; } diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerUtilsEx.java b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerUtilsEx.java index 6d908e1c7476..359f61fdf403 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerUtilsEx.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerUtilsEx.java @@ -58,6 +58,7 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.Navigatable; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; +import com.intellij.psi.util.PsiTreeUtil; import com.intellij.ui.classFilter.ClassFilter; import com.intellij.ui.content.Content; import com.intellij.unscramble.ThreadDumpPanel; @@ -779,4 +780,85 @@ public abstract class DebuggerUtilsEx extends DebuggerUtils { res.append(location.method().name()); return res.toString(); } + + private static PsiElement getNextElement(PsiElement element) { + PsiElement sibling = element.getNextSibling(); + if (sibling != null) return sibling; + element = element.getParent(); + if (element != null) return getNextElement(element); + return null; + } + + public static List collectLambdas(SourcePosition position, final boolean onlyOnTheLine) { + ApplicationManager.getApplication().assertReadAccessAllowed(); + PsiFile file = position.getFile(); + int line = position.getLine(); + Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file); + if (document == null || line >= document.getLineCount()) { + return Collections.emptyList(); + } + PsiElement element = position.getElementAt(); + final TextRange lineRange = new TextRange(document.getLineStartOffset(line), document.getLineEndOffset(line)); + do { + PsiElement parent = element.getParent(); + if (parent == null || (parent.getTextOffset() < lineRange.getStartOffset())) { + break; + } + element = parent; + } + while(true); + + final List lambdas = new ArrayList(3); + final PsiElementVisitor lambdaCollector = new JavaRecursiveElementVisitor() { + @Override + public void visitLambdaExpression(PsiLambdaExpression expression) { + super.visitLambdaExpression(expression); + if (!onlyOnTheLine || lineRange.intersects(expression.getTextRange())) { + lambdas.add(expression); + } + } + }; + element.accept(lambdaCollector); + // add initial lambda if we're inside already + NavigatablePsiElement method = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiLambdaExpression.class); + if (method instanceof PsiLambdaExpression) { + lambdas.add((PsiLambdaExpression)method); + } + for (PsiElement sibling = getNextElement(element); sibling != null; sibling = getNextElement(sibling)) { + if (!lineRange.intersects(sibling.getTextRange())) { + break; + } + sibling.accept(lambdaCollector); + } + return lambdas; + } + + @Nullable + public static PsiElement getFirstElementOnTheLine(PsiLambdaExpression lambda, Document document, int line) { + ApplicationManager.getApplication().assertReadAccessAllowed(); + TextRange lineRange = new TextRange(document.getLineStartOffset(line), document.getLineEndOffset(line)); + if (!lineRange.intersects(lambda.getTextRange())) return null; + PsiElement body = lambda.getBody(); + if (body instanceof PsiCodeBlock) { + for (PsiStatement statement : ((PsiCodeBlock)body).getStatements()) { + if (lineRange.intersects(statement.getTextRange())) { + return statement; + } + } + } + return body; + } + + public static boolean inTheSameMethod(@NotNull SourcePosition pos1, @NotNull SourcePosition pos2) { + ApplicationManager.getApplication().assertReadAccessAllowed(); + PsiElement elem1 = pos1.getElementAt(); + PsiElement elem2 = pos2.getElementAt(); + if (elem1 == null) return elem2 == null; + if (elem2 != null) { + NavigatablePsiElement expectedMethod = PsiTreeUtil.getParentOfType(elem1, PsiMethod.class, PsiLambdaExpression.class); + NavigatablePsiElement currentMethod = PsiTreeUtil.getParentOfType(elem2, PsiMethod.class, PsiLambdaExpression.class); + return Comparing.equal(expectedMethod, currentMethod); + } + return false; + } } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/JavaLineBreakpointType.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/JavaLineBreakpointType.java index a3c442fb410b..ff1b10d1d8d6 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/JavaLineBreakpointType.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/JavaLineBreakpointType.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * 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. @@ -17,26 +17,39 @@ package com.intellij.debugger.ui.breakpoints; import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.HelpID; -import com.intellij.icons.AllIcons; +import com.intellij.debugger.SourcePosition; +import com.intellij.debugger.impl.DebuggerUtilsEx; +import com.intellij.openapi.editor.Document; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.TextRange; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.psi.*; +import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.util.SmartList; import com.intellij.xdebugger.XDebuggerUtil; +import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.breakpoints.XBreakpoint; import com.intellij.xdebugger.breakpoints.XLineBreakpoint; import com.intellij.xdebugger.breakpoints.ui.XBreakpointGroupingRule; +import com.intellij.xdebugger.impl.XSourcePositionImpl; +import com.intellij.xdebugger.impl.breakpoints.XLineBreakpointVariant; +import com.intellij.xdebugger.impl.breakpoints.XLineBreakpointVariantsProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.java.debugger.breakpoints.properties.JavaBreakpointProperties; import org.jetbrains.java.debugger.breakpoints.properties.JavaLineBreakpointProperties; import javax.swing.*; +import java.util.Collections; import java.util.List; /** * Base class for java line-connected exceptions (line, method, field) * @author egor */ -public class JavaLineBreakpointType extends JavaLineBreakpointTypeBase implements JavaBreakpointType { +public class JavaLineBreakpointType extends JavaLineBreakpointTypeBase + implements JavaBreakpointType, XLineBreakpointVariantsProvider { public JavaLineBreakpointType() { super("java-line", DebuggerBundle.message("line.breakpoints.tab.title")); } @@ -58,13 +71,13 @@ public class JavaLineBreakpointType extends JavaLineBreakpointTypeBase computeLineBreakpointVariants(@NotNull Project project, @NotNull XSourcePosition position) { + PsiFile file = PsiManager.getInstance(project).findFile(position.getFile()); + if (file == null) { + return Collections.emptyList(); + } + + SourcePosition pos = SourcePosition.createFromLine(file, position.getLine()); + List lambdas = DebuggerUtilsEx.collectLambdas(pos, true); + if (lambdas.isEmpty()) { + return Collections.emptyList(); + } + + NavigatablePsiElement startMethod = PsiTreeUtil.getParentOfType(pos.getElementAt(), PsiMethod.class, PsiLambdaExpression.class); + //noinspection SuspiciousMethodCalls + if (lambdas.contains(startMethod) && lambdas.size() == 1) { + return Collections.emptyList(); + } + + Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file); + if (document == null) { + return Collections.emptyList(); + } + + List res = new SmartList(); + res.add(new JavaBreakpointVariant(position)); //all + + if (startMethod instanceof PsiMethod) { + res.add(new ExactJavaBreakpointVariant(position, startMethod)); // base method + } + + for (PsiLambdaExpression lambda : lambdas) { //lambdas + PsiElement firstElem = DebuggerUtilsEx.getFirstElementOnTheLine(lambda, document, position.getLine()); + res.add(new ExactJavaBreakpointVariant(XSourcePositionImpl.createByElement(firstElem), lambda)); + } + + return res; + } + + class JavaBreakpointVariant extends XLineBreakpointVariant { + protected final XSourcePosition mySourcePosition; + + private JavaBreakpointVariant(XSourcePosition position) { + mySourcePosition = position; + } + + @Override + public String getText() { + return "All"; + } + + @Override + public Icon getIcon() { + return null; + } + + @Override + public TextRange getHighlightRange() { + return null; + } + + @Override + public JavaLineBreakpointProperties createProperties() { + return createBreakpointProperties(mySourcePosition.getFile(), + mySourcePosition.getLine()); + } + } + + private class ExactJavaBreakpointVariant extends JavaBreakpointVariant { + private final PsiElement myElement; + + public ExactJavaBreakpointVariant(XSourcePosition position, PsiElement element) { + super(position); + myElement = element; + } + + @Override + public Icon getIcon() { + return myElement.getIcon(0); + } + + @Override + public String getText() { + return StringUtil.shortenTextWithEllipsis(myElement.getText(), 100, 0); + } + + @Override + public TextRange getHighlightRange() { + return myElement.getTextRange(); + } + + @Override + public JavaLineBreakpointProperties createProperties() { + JavaLineBreakpointProperties properties = super.createProperties(); + properties.setOffset(mySourcePosition.getOffset()); + return properties; + } + } } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/LineBreakpoint.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/LineBreakpoint.java index c322f67641d2..8cf083f49710 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/LineBreakpoint.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/LineBreakpoint.java @@ -62,6 +62,7 @@ import com.sun.jdi.request.BreakpointRequest; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.java.debugger.breakpoints.properties.JavaLineBreakpointProperties; import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes; import javax.swing.*; @@ -198,12 +199,30 @@ public class LineBreakpoint extends BreakpointWithHighlighter { return false; } - protected boolean acceptLocation(DebugProcessImpl debugProcess, ReferenceType classType, Location loc) { + protected boolean acceptLocation(final DebugProcessImpl debugProcess, ReferenceType classType, final Location loc) { Method method = loc.method(); if (DebuggerUtils.isSynthetic(method)) { return false; } - return !(method.isConstructor() && loc.codeIndex() == 0 && isAnonymousClass(classType)); + boolean res = !(method.isConstructor() && loc.codeIndex() == 0 && isAnonymousClass(classType)); + if (!res) return false; + return ApplicationManager.getApplication().runReadAction(new Computable() { + @Override + public Boolean compute() { + if (getProperties() instanceof JavaLineBreakpointProperties) { + Integer offset = ((JavaLineBreakpointProperties)getProperties()).getOffset(); + if (offset == null) return true; + PsiFile file = getPsiFile(); + if (file != null) { + SourcePosition exactPosition = SourcePosition.createFromOffset(file, offset); + SourcePosition position = debugProcess.getPositionManager().getSourcePosition(loc); + if (position == null) return false; + return DebuggerUtilsEx.inTheSameMethod(exactPosition, position); + } + } + return true; + } + }); } private boolean isInScopeOf(DebugProcessImpl debugProcess, String className) { diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/RunToCursorBreakpoint.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/RunToCursorBreakpoint.java index 52af16623eb7..e30d0f866fbe 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/RunToCursorBreakpoint.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/RunToCursorBreakpoint.java @@ -17,17 +17,18 @@ package com.intellij.debugger.ui.breakpoints; import com.intellij.debugger.SourcePosition; import com.intellij.debugger.engine.DebugProcessImpl; +import com.intellij.debugger.impl.DebuggerUtilsEx; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Computable; -import com.intellij.psi.*; -import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiManager; import com.intellij.xdebugger.XSourcePosition; import com.sun.jdi.Location; import com.sun.jdi.ReferenceType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.java.debugger.breakpoints.properties.JavaBreakpointProperties; /** * @author Eugene Zhuravlev @@ -114,6 +115,11 @@ public class RunToCursorBreakpoint extends LineBreakpoint { return true; } + @Override + protected JavaBreakpointProperties getProperties() { + return null; + } + @Override protected boolean isMuted(@NotNull final DebugProcessImpl debugProcess) { return false; // always enabled @@ -125,19 +131,9 @@ public class RunToCursorBreakpoint extends LineBreakpoint { return ApplicationManager.getApplication().runReadAction(new Computable() { @Override public Boolean compute() { - PsiElement expectedElement = myCustomPosition.getElementAt(); - if (expectedElement != null) { - SourcePosition position = debugProcess.getPositionManager().getSourcePosition(loc); - if (position != null) { - PsiElement currentElement = position.getElementAt(); - if (currentElement != null) { - NavigatablePsiElement expectedMethod = PsiTreeUtil.getParentOfType(expectedElement, PsiMethod.class, PsiLambdaExpression.class); - NavigatablePsiElement currentMethod = PsiTreeUtil.getParentOfType(currentElement, PsiMethod.class, PsiLambdaExpression.class); - return Comparing.equal(expectedMethod, currentMethod); - } - } - } - return true; + SourcePosition position = debugProcess.getPositionManager().getSourcePosition(loc); + if (position == null) return false; + return DebuggerUtilsEx.inTheSameMethod(myCustomPosition, position); } }); } diff --git a/java/debugger/impl/src/org/jetbrains/java/debugger/breakpoints/properties/JavaLineBreakpointProperties.java b/java/debugger/impl/src/org/jetbrains/java/debugger/breakpoints/properties/JavaLineBreakpointProperties.java index 9a892346ac04..1ddf268f5895 100644 --- a/java/debugger/impl/src/org/jetbrains/java/debugger/breakpoints/properties/JavaLineBreakpointProperties.java +++ b/java/debugger/impl/src/org/jetbrains/java/debugger/breakpoints/properties/JavaLineBreakpointProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * 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. @@ -15,8 +15,20 @@ */ package org.jetbrains.java.debugger.breakpoints.properties; +import com.intellij.util.xmlb.annotations.OptionTag; + /** * @author egor */ public class JavaLineBreakpointProperties extends JavaBreakpointProperties { + private Integer myOffset = null; + + @OptionTag("offset") + public Integer getOffset() { + return myOffset; + } + + public void setOffset(Integer offset) { + myOffset = offset; + } } diff --git a/java/debugger/openapi/src/com/intellij/debugger/SourcePosition.java b/java/debugger/openapi/src/com/intellij/debugger/SourcePosition.java index 831a5fc3c4ae..1b748b7691e6 100644 --- a/java/debugger/openapi/src/com/intellij/debugger/SourcePosition.java +++ b/java/debugger/openapi/src/com/intellij/debugger/SourcePosition.java @@ -312,7 +312,7 @@ public abstract class SourcePosition implements Navigatable{ } @Nullable - public static SourcePosition createFromElement(PsiElement element) { + public static SourcePosition createFromElement(@NotNull PsiElement element) { ApplicationManager.getApplication().assertReadAccessAllowed(); PsiElement navigationElement = element.getNavigationElement(); final SmartPsiElementPointer pointer = diff --git a/java/execution/impl/src/com/intellij/execution/application/ApplicationRunLineMarkerProvider.java b/java/execution/impl/src/com/intellij/execution/application/ApplicationRunLineMarkerProvider.java index b161cbec1885..fe21ddd71d80 100644 --- a/java/execution/impl/src/com/intellij/execution/application/ApplicationRunLineMarkerProvider.java +++ b/java/execution/impl/src/com/intellij/execution/application/ApplicationRunLineMarkerProvider.java @@ -20,6 +20,7 @@ import com.intellij.codeInsight.daemon.LineMarkerProvider; import com.intellij.execution.lineMarker.RunLineMarkerInfo; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiIdentifier; import com.intellij.psi.PsiMethod; import com.intellij.psi.util.PsiMethodUtil; import org.jetbrains.annotations.NotNull; @@ -35,11 +36,14 @@ public class ApplicationRunLineMarkerProvider implements LineMarkerProvider { @Nullable @Override - public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement element) { - if (element instanceof PsiClass && PsiMethodUtil.findMainInClass((PsiClass)element) != null) - return new RunLineMarkerInfo(element, ApplicationConfigurationType.getInstance().getIcon(), null); - if (element instanceof PsiMethod && "main".equals(((PsiMethod)element).getName()) && PsiMethodUtil.isMainMethod((PsiMethod)element)) - return new RunLineMarkerInfo(element, ApplicationConfigurationType.getInstance().getIcon(), null); + public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement e) { + if (e instanceof PsiIdentifier) { + PsiElement element = e.getParent(); + if (element instanceof PsiClass && PsiMethodUtil.findMainInClass((PsiClass)element) != null) + return new RunLineMarkerInfo(element, ApplicationConfigurationType.getInstance().getIcon(), null); + if (element instanceof PsiMethod && "main".equals(((PsiMethod)element).getName()) && PsiMethodUtil.isMainMethod((PsiMethod)element)) + return new RunLineMarkerInfo(element, ApplicationConfigurationType.getInstance().getIcon(), null); + } return null; } diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/RefCountHolder.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/RefCountHolder.java index dc9be261626f..7ebb225ec25d 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/RefCountHolder.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/RefCountHolder.java @@ -71,7 +71,7 @@ class RefCountHolder { private static final Key> REF_COUNT_HOLDER_IN_FILE_KEY = Key.create("REF_COUNT_HOLDER_IN_FILE_KEY"); @NotNull - public static RefCountHolder get(@NotNull PsiFile file) { + static RefCountHolder get(@NotNull PsiFile file) { Reference ref = file.getUserData(REF_COUNT_HOLDER_IN_FILE_KEY); RefCountHolder holder = com.intellij.reference.SoftReference.dereference(ref); if (holder == null) { @@ -171,7 +171,7 @@ class RefCountHolder { } } - public boolean isReferenced(@NotNull PsiElement element) { + boolean isReferenced(@NotNull PsiElement element) { Collection array; synchronized (myLocalRefsMap) { array = myLocalRefsMap.get(element); @@ -272,10 +272,10 @@ class RefCountHolder { return false; } - public boolean analyze(@NotNull PsiFile file, - TextRange dirtyScope, - @NotNull ProgressIndicator indicator, - @NotNull Runnable analyze) { + boolean analyze(@NotNull PsiFile file, + TextRange dirtyScope, + @NotNull ProgressIndicator indicator, + @NotNull Runnable analyze) { ProgressIndicator result; if (myState.compareAndSet(EMPTY, indicator)) { if (!file.getTextRange().equals(dirtyScope)) { diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java index 5c42a1f0deaa..88019cd763c4 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java @@ -124,7 +124,7 @@ public class JavaCompletionContributor extends CompletionContributor { return new AnnotationTypeFilter(); } - if (JavaCompletionData.DECLARATION_START.accepts(position) || + if (JavaCompletionData.DECLARATION_START.getValue().accepts(position) || JavaCompletionData.isInsideParameterList(position) || psiElement().inside(psiElement(PsiJavaCodeReferenceElement.class).withParent(psiAnnotation())).accepts(position)) { return new OrFilter(ElementClassFilter.CLASS, ElementClassFilter.PACKAGE_FILTER); diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionData.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionData.java index 67670d5d2d18..5da35bb89eba 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionData.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionData.java @@ -20,6 +20,8 @@ import com.intellij.codeInsight.TailType; import com.intellij.codeInsight.TailTypes; import com.intellij.codeInsight.completion.util.ParenthesesInsertHandler; import com.intellij.codeInsight.lookup.*; +import com.intellij.openapi.util.AtomicNotNullLazyValue; +import com.intellij.openapi.util.NotNullLazyValue; import com.intellij.patterns.ElementPattern; import com.intellij.patterns.PsiJavaElementPattern; import com.intellij.pom.java.LanguageLevel; @@ -37,6 +39,7 @@ import com.intellij.psi.util.PsiUtil; import com.intellij.util.Consumer; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; import static com.intellij.patterns.PsiJavaPatterns.*; import static com.intellij.patterns.StandardPatterns.not; @@ -86,33 +89,39 @@ public class JavaCompletionData extends JavaAwareCompletionData { new StartElementFilter() ); - static final ElementFilter END_OF_BLOCK = new OrFilter( - new AndFilter( - new LeftNeighbour( - new OrFilter( + static final NotNullLazyValue END_OF_BLOCK = new AtomicNotNullLazyValue() { + @NotNull + @Override + protected ElementFilter compute() { + return new OrFilter( + new AndFilter( + new LeftNeighbour( + new OrFilter( new AndFilter ( - new TextFilter(BLOCK_FINALIZERS), - new NotFilter ( - new SuperParentFilter(new ClassFilter(PsiAnnotation.class)) - ) + new TextFilter(BLOCK_FINALIZERS), + new NotFilter ( + new SuperParentFilter(new ClassFilter(PsiAnnotation.class)) + ) ), new TextFilter("*/"), new TokenTypeFilter(JspElementType.HOLDER_TEMPLATE_DATA), new ClassFilter(OuterLanguageElement.class), new AndFilter( - new TextFilter(")"), - new NotFilter( - new OrFilter( - new ParentElementFilter(new ClassFilter(PsiExpressionList.class)), - new ParentElementFilter(new ClassFilter(PsiParameterList.class)), - new ParentElementFilter(new ClassFilter(PsiTypeCastExpression.class)) - ) + new TextFilter(")"), + new NotFilter( + new OrFilter( + new ParentElementFilter(new ClassFilter(PsiExpressionList.class)), + new ParentElementFilter(new ClassFilter(PsiParameterList.class)), + new ParentElementFilter(new ClassFilter(PsiTypeCastExpression.class)) ) + ) ))), - new NotFilter(new TextFilter(".")) - ), - START_OF_CODE_FRAGMENT - ); + new NotFilter(new TextFilter(".")) + ), + START_OF_CODE_FRAGMENT + ); + } + }; static final ElementPattern START_SWITCH = psiElement().afterLeaf(psiElement().withText("{").withParents(PsiCodeBlock.class, PsiSwitchStatement.class)); @@ -132,9 +141,15 @@ public class JavaCompletionData extends JavaAwareCompletionData { PsiKeyword.CHAR, PsiKeyword.BYTE }; - private static final ElementFilter CLASS_BODY = new OrFilter( - new AfterElementFilter(new TextFilter("{")), - new ScopeFilter(new ClassFilter(JspClassLevelDeclarationStatement.class))); + private static final NotNullLazyValue CLASS_BODY = new AtomicNotNullLazyValue() { + @NotNull + @Override + protected ElementFilter compute() { + return new OrFilter( + new AfterElementFilter(new TextFilter("{")), + new ScopeFilter(new ClassFilter(JspClassLevelDeclarationStatement.class))); + } + }; public static final ElementPattern START_FOR = psiElement().afterLeaf(psiElement().withText("(").afterLeaf("for")).withParents(PsiJavaCodeReferenceElement.class, @@ -166,25 +181,31 @@ public class JavaCompletionData extends JavaAwareCompletionData { defineScopeEquivalence(PsiMethod.class, JavaCodeFragment.class); } - public static final ElementPattern DECLARATION_START = psiElement().andNot(psiElement().afterLeaf("@", ".")). - andOr( - psiElement().and(new FilterPattern(CLASS_BODY)). + public static final NotNullLazyValue> DECLARATION_START = new NotNullLazyValue>() { + @NotNull + @Override + protected ElementPattern compute() { + return psiElement().andNot(psiElement().afterLeaf("@", ".")). andOr( - new FilterPattern(END_OF_BLOCK), - psiElement().afterLeaf(or( - psiElement().inside(PsiModifierList.class), - psiElement().withElementType(JavaTokenType.GT).inside(PsiTypeParameterList.class) - ))), - psiElement().withParents(PsiJavaCodeReferenceElement.class, PsiTypeElement.class, PsiMember.class), - psiElement().withParents(PsiJavaCodeReferenceElement.class, PsiTypeElement.class, PsiClassLevelDeclarationStatement.class) - ); + psiElement().and(new FilterPattern(CLASS_BODY.getValue())). + andOr( + new FilterPattern(END_OF_BLOCK.getValue()), + psiElement().afterLeaf(or( + psiElement().inside(PsiModifierList.class), + psiElement().withElementType(JavaTokenType.GT).inside(PsiTypeParameterList.class) + ))), + psiElement().withParents(PsiJavaCodeReferenceElement.class, PsiTypeElement.class, PsiMember.class), + psiElement().withParents(PsiJavaCodeReferenceElement.class, PsiTypeElement.class, PsiClassLevelDeclarationStatement.class) + ); + } + }; private void declareCompletionSpaces() { declareFinalScope(PsiFile.class); { // Class body - final CompletionVariant variant = new CompletionVariant(CLASS_BODY); + final CompletionVariant variant = new CompletionVariant(CLASS_BODY.getValue()); variant.includeScopeClass(PsiClass.class, true); registerVariant(variant); } @@ -219,7 +240,7 @@ public class JavaCompletionData extends JavaAwareCompletionData { // position { final ElementFilter position = new AndFilter( - new NotFilter(CLASS_BODY), + new NotFilter(CLASS_BODY.getValue()), new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.EXTENDS)))), new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.IMPLEMENTS)))), new NotFilter(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))), @@ -240,7 +261,7 @@ public class JavaCompletionData extends JavaAwareCompletionData { // position { final ElementFilter position = new AndFilter( - new NotFilter(CLASS_BODY), + new NotFilter(CLASS_BODY.getValue()), new NotFilter(new BeforeElementFilter(new ContentFilter(new TextFilter(PsiKeyword.EXTENDS)))), new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.IMPLEMENTS)))), new NotFilter(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))), @@ -476,7 +497,7 @@ public class JavaCompletionData extends JavaAwareCompletionData { result.consume(new OverrideableSpace(createKeyword(position, PsiKeyword.PACKAGE), TailType.HUMBLE_SPACE_BEFORE_WORD)); result.consume(new OverrideableSpace(createKeyword(position, PsiKeyword.IMPORT), TailType.HUMBLE_SPACE_BEFORE_WORD)); } - else if (END_OF_BLOCK.isAcceptable(position, position) && PsiTreeUtil.getParentOfType(position, PsiMember.class) == null) { + else if (END_OF_BLOCK.getValue().isAcceptable(position, position) && PsiTreeUtil.getParentOfType(position, PsiMember.class) == null) { result.consume(new OverrideableSpace(createKeyword(position, PsiKeyword.IMPORT), TailType.HUMBLE_SPACE_BEFORE_WORD)); } } @@ -589,7 +610,7 @@ public class JavaCompletionData extends JavaAwareCompletionData { return true; } - return END_OF_BLOCK.isAcceptable(position, position); + return END_OF_BLOCK.getValue().isAcceptable(position, position); } static void addExpectedTypeMembers(CompletionParameters parameters, final CompletionResultSet result) { @@ -656,7 +677,7 @@ public class JavaCompletionData extends JavaAwareCompletionData { .accepts(position); boolean typeFragment = position.getContainingFile() instanceof PsiTypeCodeFragment && PsiTreeUtil.prevVisibleLeaf(position) == null; - boolean declaration = DECLARATION_START.accepts(position); + boolean declaration = DECLARATION_START.getValue().accepts(position); boolean expressionPosition = isExpressionPosition(position); boolean inGenerics = PsiTreeUtil.getParentOfType(position, PsiReferenceParameterList.class) != null; if (START_FOR.accepts(position) || @@ -723,7 +744,7 @@ public class JavaCompletionData extends JavaAwareCompletionData { return false; } - if (END_OF_BLOCK.isAcceptable(position, position) && + if (END_OF_BLOCK.getValue().isAcceptable(position, position) && PsiTreeUtil.getParentOfType(position, PsiCodeBlock.class, true, PsiMember.class) != null) { return true; } diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/ModifierChooser.java b/java/java-impl/src/com/intellij/codeInsight/completion/ModifierChooser.java index 3762bb671c15..807144519108 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/ModifierChooser.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/ModifierChooser.java @@ -130,7 +130,7 @@ public class ModifierChooser { PsiElement prev = FilterPositionUtil.searchNonSpaceNonCommentBack(element); if (parent instanceof PsiJavaFile || parent instanceof PsiClass) { - if (prev == null || JavaCompletionData.END_OF_BLOCK.isAcceptable(element, prev.getParent())) { + if (prev == null || JavaCompletionData.END_OF_BLOCK.getValue().isAcceptable(element, prev.getParent())) { return true; } } diff --git a/java/java-impl/src/com/intellij/refactoring/actions/ReplaceConstructorWithBuilderAction.java b/java/java-impl/src/com/intellij/refactoring/actions/ReplaceConstructorWithBuilderAction.java index 0775c65258a8..b71b01bef480 100644 --- a/java/java-impl/src/com/intellij/refactoring/actions/ReplaceConstructorWithBuilderAction.java +++ b/java/java-impl/src/com/intellij/refactoring/actions/ReplaceConstructorWithBuilderAction.java @@ -39,7 +39,7 @@ public class ReplaceConstructorWithBuilderAction extends BaseRefactoringAction{ final int offset = editor.getCaretModel().getOffset(); final PsiElement elementAt = file.findElementAt(offset); final PsiClass psiClass = ReplaceConstructorWithBuilderHandler.getParentNamedClass(elementAt); - return psiClass != null && psiClass.getConstructors().length > 0; + return psiClass != null && psiClass.getConstructors().length > 0 && !psiClass.isEnum(); } protected boolean isEnabledOnElements(@NotNull final PsiElement[] elements) { diff --git a/java/java-impl/src/com/intellij/refactoring/actions/ReplaceConstructorWithFactoryAction.java b/java/java-impl/src/com/intellij/refactoring/actions/ReplaceConstructorWithFactoryAction.java index 1d32d0ee5183..a464fad6902a 100644 --- a/java/java-impl/src/com/intellij/refactoring/actions/ReplaceConstructorWithFactoryAction.java +++ b/java/java-impl/src/com/intellij/refactoring/actions/ReplaceConstructorWithFactoryAction.java @@ -17,8 +17,10 @@ package com.intellij.refactoring.actions; import com.intellij.lang.java.JavaLanguage; import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; import com.intellij.psi.PsiMethod; import com.intellij.refactoring.RefactoringActionHandler; import com.intellij.refactoring.replaceConstructorWithFactory.ReplaceConstructorWithFactoryHandler; @@ -32,10 +34,25 @@ public class ReplaceConstructorWithFactoryAction extends BaseRefactoringAction { return false; } + @Override protected boolean isEnabledOnElements(@NotNull PsiElement[] elements) { - return elements.length == 1 && - (elements[0] instanceof PsiMethod && ((PsiMethod)elements[0]).isConstructor() || elements[0] instanceof PsiClass) - && elements[0].getLanguage().isKindOf(JavaLanguage.INSTANCE); + return false; + } + + @Override + protected boolean isAvailableOnElementInEditorAndFile(@NotNull PsiElement element, + @NotNull Editor editor, + @NotNull PsiFile file, + @NotNull DataContext context) { + return (element instanceof PsiMethod && + ((PsiMethod)element).isConstructor() && + acceptClass(((PsiMethod)element).getContainingClass()) || + acceptClass(element)) + && element.getLanguage().isKindOf(JavaLanguage.INSTANCE); + } + + private static boolean acceptClass(PsiElement element) { + return element instanceof PsiClass && !((PsiClass)element).isEnum(); } protected RefactoringActionHandler getHandler(@NotNull DataContext dataContext) { diff --git a/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaChangeSignatureHandler.java b/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaChangeSignatureHandler.java index 89a123347364..687f7a2a3576 100644 --- a/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaChangeSignatureHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaChangeSignatureHandler.java @@ -136,7 +136,7 @@ public class JavaChangeSignatureHandler implements ChangeSignatureHandler { return elementParent; } if (elementParent instanceof PsiClass && ((PsiClass)elementParent).getNameIdentifier()==element) { - if (((PsiClass)elementParent).isAnnotationType()) { + if (((PsiClass)elementParent).isAnnotationType() || ((PsiClass)elementParent).isEnum()) { return null; } return elementParent; diff --git a/java/java-impl/src/com/intellij/refactoring/encapsulateFields/EncapsulateFieldsHandler.java b/java/java-impl/src/com/intellij/refactoring/encapsulateFields/EncapsulateFieldsHandler.java index b4b26c1ccc3f..e453744c4f86 100644 --- a/java/java-impl/src/com/intellij/refactoring/encapsulateFields/EncapsulateFieldsHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/encapsulateFields/EncapsulateFieldsHandler.java @@ -22,17 +22,17 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiField; -import com.intellij.psi.PsiFile; +import com.intellij.openapi.util.Condition; +import com.intellij.psi.*; import com.intellij.refactoring.HelpID; import com.intellij.refactoring.RefactoringActionHandler; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.util.CommonRefactoringUtil; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.HashSet; +import java.util.List; public class EncapsulateFieldsHandler implements RefactoringActionHandler { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.encapsulateFields.EncapsulateFieldsHandler"); @@ -108,8 +108,13 @@ public class EncapsulateFieldsHandler implements RefactoringActionHandler { } LOG.assertTrue(aClass != null); - final PsiField[] fields = aClass.getFields(); - if (fields.length == 0) { + final List fields = ContainerUtil.filter(aClass.getFields(), new Condition() { + @Override + public boolean value(PsiField field) { + return !(field instanceof PsiEnumConstant); + } + }); + if (fields.isEmpty()) { CommonRefactoringUtil.showErrorHint(project, CommonDataKeys.EDITOR.getData(dataContext), "Class has no fields to encapsulate", REFACTORING_NAME, HelpID.ENCAPSULATE_FIELDS); return; diff --git a/java/java-impl/src/com/intellij/refactoring/encapsulateFields/JavaEncapsulateFieldHelper.java b/java/java-impl/src/com/intellij/refactoring/encapsulateFields/JavaEncapsulateFieldHelper.java index 1430a4b98fb7..972824d18d62 100644 --- a/java/java-impl/src/com/intellij/refactoring/encapsulateFields/JavaEncapsulateFieldHelper.java +++ b/java/java-impl/src/com/intellij/refactoring/encapsulateFields/JavaEncapsulateFieldHelper.java @@ -17,6 +17,7 @@ package com.intellij.refactoring.encapsulateFields; import com.intellij.codeInsight.generation.GenerateMembersUtil; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.tree.IElementType; @@ -25,10 +26,13 @@ import com.intellij.psi.util.PsiUtil; import com.intellij.refactoring.util.RefactoringUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.VisibilityUtil; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.List; + /** * @author Max Medvedev */ @@ -307,7 +311,13 @@ public class JavaEncapsulateFieldHelper extends EncapsulateFieldHelper { @NotNull @Override public PsiField[] getApplicableFields(@NotNull PsiClass aClass) { - return aClass.getFields(); + final List fields = ContainerUtil.filter(aClass.getFields(), new Condition() { + @Override + public boolean value(PsiField field) { + return !(field instanceof PsiEnumConstant); + } + }); + return fields.toArray(new PsiField[fields.size()]); } @Override diff --git a/java/java-impl/src/com/intellij/refactoring/extractInterface/ExtractInterfaceDialog.java b/java/java-impl/src/com/intellij/refactoring/extractInterface/ExtractInterfaceDialog.java index b07cb31c92b0..162f88b294b7 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractInterface/ExtractInterfaceDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/extractInterface/ExtractInterfaceDialog.java @@ -51,7 +51,7 @@ class ExtractInterfaceDialog extends JavaExtractSuperBaseDialog { return element.hasModifierProperty(PsiModifier.PUBLIC) && !element.hasModifierProperty(PsiModifier.STATIC); } - else if (element instanceof PsiField) { + else if (element instanceof PsiField && !(element instanceof PsiEnumConstant)) { return element.hasModifierProperty(PsiModifier.FINAL) && element.hasModifierProperty(PsiModifier.STATIC) && element.hasModifierProperty(PsiModifier.PUBLIC); diff --git a/java/java-impl/src/com/intellij/refactoring/util/duplicates/MethodDuplicatesHandler.java b/java/java-impl/src/com/intellij/refactoring/util/duplicates/MethodDuplicatesHandler.java index 78c4ed2ab216..11568aedf84f 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/duplicates/MethodDuplicatesHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/util/duplicates/MethodDuplicatesHandler.java @@ -108,7 +108,7 @@ public class MethodDuplicatesHandler implements RefactoringActionHandler { } } else if (member instanceof PsiField) { final PsiField field = (PsiField)member; - if (!field.hasInitializer()) { + if (field.getInitializer() == null) { return "Field " + member.getName() + " doesn't have initializer"; } final PsiClass containingClass = field.getContainingClass(); diff --git a/java/java-impl/src/com/intellij/slicer/SliceUtil.java b/java/java-impl/src/com/intellij/slicer/SliceUtil.java index 91dde1c7efaf..2b047f95aa71 100644 --- a/java/java-impl/src/com/intellij/slicer/SliceUtil.java +++ b/java/java-impl/src/com/intellij/slicer/SliceUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * 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. @@ -49,13 +49,13 @@ import java.util.Set; /** * @author cdr */ -public class SliceUtil { - public static boolean processUsagesFlownDownTo(@NotNull PsiElement expression, - @NotNull Processor processor, - @NotNull SliceUsage parent, - @NotNull PsiSubstitutor parentSubstitutor, - int indexNesting, - @NotNull String syntheticField) { +class SliceUtil { + static boolean processUsagesFlownDownTo(@NotNull PsiElement expression, + @NotNull Processor processor, + @NotNull SliceUsage parent, + @NotNull PsiSubstitutor parentSubstitutor, + int indexNesting, + @NotNull String syntheticField) { assert indexNesting >= 0 : indexNesting; expression = simplify(expression); PsiElement original = expression; @@ -337,16 +337,18 @@ public class SliceUtil { } @NotNull - public static SliceUsage createSliceUsage(@NotNull PsiElement element, - @NotNull SliceUsage parent, - @NotNull PsiSubstitutor substitutor, - int indexNesting, - @NotNull String syntheticField) { + static SliceUsage createSliceUsage(@NotNull PsiElement element, + @NotNull SliceUsage parent, + @NotNull PsiSubstitutor substitutor, + int indexNesting, + @NotNull String syntheticField) { return new SliceUsage(simplify(element), parent, substitutor,indexNesting, syntheticField); } @NotNull - public static SliceUsage createTooComplexDFAUsage(@NotNull PsiElement element, @NotNull SliceUsage parent, @NotNull PsiSubstitutor substitutor) { + private static SliceUsage createTooComplexDFAUsage(@NotNull PsiElement element, + @NotNull SliceUsage parent, + @NotNull PsiSubstitutor substitutor) { return new SliceTooComplexDFAUsage(simplify(element), parent, substitutor); } diff --git a/java/java-psi-impl/src/com/intellij/codeInsight/ExceptionUtil.java b/java/java-psi-impl/src/com/intellij/codeInsight/ExceptionUtil.java index e268bbdcd526..15f57c2dd018 100644 --- a/java/java-psi-impl/src/com/intellij/codeInsight/ExceptionUtil.java +++ b/java/java-psi-impl/src/com/intellij/codeInsight/ExceptionUtil.java @@ -336,7 +336,8 @@ public class ExceptionUtil { final JavaResolveResult resolveResult = methodReferenceExpression.advancedResolve(false); final PsiElement resolve = resolveResult.getElement(); if (resolve instanceof PsiMethod) { - return getUnhandledExceptions((PsiMethod)resolve, methodReferenceExpression, topElement, resolveResult.getSubstitutor()); + final PsiElement referenceNameElement = methodReferenceExpression.getReferenceNameElement(); + return getUnhandledExceptions((PsiMethod)resolve, referenceNameElement, topElement, resolveResult.getSubstitutor()); } return Collections.emptyList(); } @@ -667,12 +668,9 @@ public class ExceptionUtil { // like in void f() throws XXX { new AA(methodThrowingXXX()) { ... }; } return parent instanceof PsiAnonymousClass && isHandled(parent, exceptionType, topElement); } - else if (parent instanceof PsiLambdaExpression) { - final PsiType interfaceType = ((PsiLambdaExpression)parent).getFunctionalInterfaceType(); - return isDeclaredBySAMMethod(exceptionType, interfaceType); - } - else if (element instanceof PsiMethodReferenceExpression) { - final PsiType interfaceType = ((PsiMethodReferenceExpression)element).getFunctionalInterfaceType(); + else if (parent instanceof PsiLambdaExpression || + parent instanceof PsiMethodReferenceExpression && element == ((PsiMethodReferenceExpression)parent).getReferenceNameElement()) { + final PsiType interfaceType = ((PsiFunctionalExpression)parent).getFunctionalInterfaceType(); return isDeclaredBySAMMethod(exceptionType, interfaceType); } else if (parent instanceof PsiClassInitializer) { diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiLambdaExpressionImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiLambdaExpressionImpl.java index e756149618df..ffb9de9ebcfa 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiLambdaExpressionImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiLambdaExpressionImpl.java @@ -272,6 +272,6 @@ public class PsiLambdaExpressionImpl extends ExpressionPsiElement implements Psi @Nullable @Override public Icon getIcon(int flags) { - return AllIcons.Nodes.AnonymousClass; + return AllIcons.Nodes.Function; } } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/UnhandledExceptionsInQualifier.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/UnhandledExceptionsInQualifier.java new file mode 100644 index 000000000000..e1c64801451e --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/UnhandledExceptionsInQualifier.java @@ -0,0 +1,17 @@ +class E1 extends Exception {} +class E2 extends Exception {} +class Test { + interface I { + void m() throws E1; + } + + void a(I i) {} + Test b() throws E2 {return this;} + void c() throws E1 {} + void e() throws E1, E2 {} + + void d() throws E2 { + a(b()::c); + a(this::e); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/changeSignatureTarget/disabledForEnum.java b/java/java-tests/testData/refactoring/changeSignatureTarget/disabledForEnum.java new file mode 100644 index 000000000000..2245a8a54298 --- /dev/null +++ b/java/java-tests/testData/refactoring/changeSignatureTarget/disabledForEnum.java @@ -0,0 +1,3 @@ +enum E { + ; +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/encapsulateFields/filterEnumConstants/after/Test.java b/java/java-tests/testData/refactoring/encapsulateFields/filterEnumConstants/after/Test.java new file mode 100644 index 000000000000..f6d508b6a552 --- /dev/null +++ b/java/java-tests/testData/refactoring/encapsulateFields/filterEnumConstants/after/Test.java @@ -0,0 +1,12 @@ +enum A { + B; + private int i; + + public int getI() { + return i; + } + + public void setI(int i) { + this.i = i; + } +} diff --git a/java/java-tests/testData/refactoring/encapsulateFields/filterEnumConstants/before/Test.java b/java/java-tests/testData/refactoring/encapsulateFields/filterEnumConstants/before/Test.java new file mode 100644 index 000000000000..0b36fa5f5bbd --- /dev/null +++ b/java/java-tests/testData/refactoring/encapsulateFields/filterEnumConstants/before/Test.java @@ -0,0 +1,4 @@ +enum A { + B; + private int i; +} diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewMethodRefHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewMethodRefHighlightingTest.java index ac55c709b1f9..94d0a6427790 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewMethodRefHighlightingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewMethodRefHighlightingTest.java @@ -410,6 +410,10 @@ public class NewMethodRefHighlightingTest extends LightDaemonAnalyzerTestCase { doTest(); } + public void testUnhandledExceptionsInQualifier() throws Exception { + doTest(); + } + private void doTest() { doTest(false); } diff --git a/java/java-tests/testSrc/com/intellij/index/ConcurrentIndexTest.groovy b/java/java-tests/testSrc/com/intellij/index/ConcurrentIndexTest.groovy index 2b94e5a42c23..348d793e8652 100644 --- a/java/java-tests/testSrc/com/intellij/index/ConcurrentIndexTest.groovy +++ b/java/java-tests/testSrc/com/intellij/index/ConcurrentIndexTest.groovy @@ -22,13 +22,13 @@ import com.intellij.psi.PsiFile import com.intellij.psi.PsiJavaFile import com.intellij.psi.impl.PsiDocumentManagerBase import com.intellij.psi.impl.source.PsiFileImpl +import com.intellij.psi.search.GlobalSearchScope import com.intellij.testFramework.BombedProgressIndicator import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.SkipSlowTestLocally import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase import java.util.concurrent.CountDownLatch - /** * @author peter */ @@ -128,4 +128,46 @@ class ConcurrentIndexTest extends JavaCodeInsightFixtureTestCase { for(future in futuresToWait) future.get(); } } + + public void "test forceUpdateAffectsReadOfDataForUnsavedDocuments"() { + def N = Math.max(2, (int)(Runtime.runtime.availableProcessors())); + PsiFileImpl file = (PsiFileImpl) myFixture.addFileToProject("Foo.java", "class Foo {" + ("public void foo() {}\n") * 1000 + "}") + assert myFixture.findClass("Foo").node + + for (i in 1..20) { + println "iteration $i" + WriteCommandAction.runWriteCommandAction(project) { + ((PsiJavaFile) file).importList.add(JavaPsiFacade.getElementFactory(project).createImportStatementOnDemand("foo.bar$i")) + } + PlatformTestUtil.tryGcSoftlyReachableObjects() + assert !file.contentsLoaded + + myFixture.addFileToProject("Foo" + i + ".java", "class Foo" + i + " {" + ("public void foo() {}\n") * 1000 + "}") + + def futuresToWait = [] + def sameStartCondition = new CountDownLatch(N) + + for(j in 1..N/2) { + futuresToWait.add(ApplicationManager.application.executeOnPooledThread { + ApplicationManager.application.runReadAction { + sameStartCondition.countDown() + sameStartCondition.await() + assert myFixture.getJavaFacade().findClass("Foo", GlobalSearchScope.fileScope(file)).node + } + }) + } + + for(j in 1..N/2) { + futuresToWait.add(ApplicationManager.application.executeOnPooledThread { + ApplicationManager.application.runReadAction { + sameStartCondition.countDown() + sameStartCondition.await() + assert myFixture.findClass("Foo" + i).node + } + }); + } + + for(future in futuresToWait) future.get(); + } + } } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureBaseTest.java b/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureBaseTest.java index 98312eee8e8a..c2ba39a70750 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureBaseTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureBaseTest.java @@ -46,28 +46,22 @@ public abstract class ChangeSignatureBaseTest extends LightRefactoringTestCase { @Nullable final String[] parameters, @Nullable final String[] exceptions, boolean delegate) { - GenParams genParams = parameters == null ? new SimpleParameterGen() : new GenParams() { - @Override - public ParameterInfoImpl[] genParams(PsiMethod method) throws IncorrectOperationException { - ParameterInfoImpl[] parameterInfos = new ParameterInfoImpl[parameters.length]; - for (int i = 0; i < parameters.length; i++) { - PsiType type = myFactory.createTypeFromText(parameters[i], method); - parameterInfos[i] = new ParameterInfoImpl(-1, "p" + (i + 1), type); - } - return parameterInfos; + GenParams genParams = parameters == null ? new SimpleParameterGen() : method -> { + ParameterInfoImpl[] parameterInfos = new ParameterInfoImpl[parameters.length]; + for (int i = 0; i < parameters.length; i++) { + PsiType type = myFactory.createTypeFromText(parameters[i], method); + parameterInfos[i] = new ParameterInfoImpl(-1, "p" + (i + 1), type); } + return parameterInfos; }; - GenExceptions genExceptions = exceptions == null ? new SimpleExceptionsGen() : new GenExceptions() { - @Override - public ThrownExceptionInfo[] genExceptions(PsiMethod method) throws IncorrectOperationException { - ThrownExceptionInfo[] exceptionInfos = new ThrownExceptionInfo[exceptions.length]; - for (int i = 0; i < exceptions.length; i++) { - PsiType type = myFactory.createTypeFromText(exceptions[i], method); - exceptionInfos[i] = new JavaThrownExceptionInfo(-1, (PsiClassType)type); - } - return exceptionInfos; + GenExceptions genExceptions = exceptions == null ? new SimpleExceptionsGen() : method -> { + ThrownExceptionInfo[] exceptionInfos = new ThrownExceptionInfo[exceptions.length]; + for (int i = 0; i < exceptions.length; i++) { + PsiType type = myFactory.createTypeFromText(exceptions[i], method); + exceptionInfos[i] = new JavaThrownExceptionInfo(-1, (PsiClassType)type); } + return exceptionInfos; }; doTest(null, null, returnType, genParams, genExceptions, delegate); diff --git a/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureGestureTest.java b/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureGestureTest.java index f34b14db5cb4..f4647486699d 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureGestureTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureGestureTest.java @@ -102,34 +102,28 @@ public class ChangeSignatureGestureTest extends LightCodeInsightFixtureTestCase } public void testOnAnotherMethod() { - doTest(new Runnable() { - @Override - public void run() { - myFixture.type("int param"); - final int nextMethodOffset = ((PsiJavaFile)myFixture.getFile()).getClasses()[0].getMethods()[1].getTextOffset(); - myFixture.getEditor().getCaretModel().moveToOffset(nextMethodOffset); - } + doTest(() -> { + myFixture.type("int param"); + final int nextMethodOffset = ((PsiJavaFile)myFixture.getFile()).getClasses()[0].getMethods()[1].getTextOffset(); + myFixture.getEditor().getCaretModel().moveToOffset(nextMethodOffset); }, false, ChangeSignatureDetectorAction.CHANGE_SIGNATURE); } public void testAddParamChangeReturnType() { - doTest(new Runnable() { - @Override - public void run() { - myFixture.type("int param"); - CaretModel model = myFixture.getEditor().getCaretModel(); - PsiElement element = myFixture.getElementAtCaret(); - PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class, false); - assertTrue(method != null); - PsiTypeElement returnTypeElement = method.getReturnTypeElement(); - assertTrue(returnTypeElement != null); - model.moveToOffset(returnTypeElement.getTextRange().getEndOffset()); - int i = returnTypeElement.getTextLength(); - while (i-- > 0) { - myFixture.type('\b'); - } - myFixture.type("boolean"); + doTest(() -> { + myFixture.type("int param"); + CaretModel model = myFixture.getEditor().getCaretModel(); + PsiElement element = myFixture.getElementAtCaret(); + PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class, false); + assertTrue(method != null); + PsiTypeElement returnTypeElement = method.getReturnTypeElement(); + assertTrue(returnTypeElement != null); + model.moveToOffset(returnTypeElement.getTextRange().getEndOffset()); + int i = returnTypeElement.getTextLength(); + while (i-- > 0) { + myFixture.type('\b'); } + myFixture.type("boolean"); }, true, ChangeSignatureDetectorAction.CHANGE_SIGNATURE); } @@ -154,12 +148,7 @@ public class ChangeSignatureGestureTest extends LightCodeInsightFixtureTestCase } private void doTypingTest(final String param, final String hint) { - doTest(new Runnable() { - @Override - public void run() { - myFixture.type(param); - } - }, true, hint); + doTest(() -> myFixture.type(param), true, hint); } public void testReturnValue() { @@ -175,12 +164,7 @@ public class ChangeSignatureGestureTest extends LightCodeInsightFixtureTestCase } private void doTypingNoBorderTest(final String param) { - doTest(new Runnable() { - @Override - public void run() { - myFixture.type(param); - } - }, false, ChangeSignatureDetectorAction.CHANGE_SIGNATURE); + doTest(() -> myFixture.type(param), false, ChangeSignatureDetectorAction.CHANGE_SIGNATURE); } public void testDeleteParamInSuperUsed() { @@ -188,17 +172,14 @@ public class ChangeSignatureGestureTest extends LightCodeInsightFixtureTestCase } private void doDeleteTest() { - doTest(new Runnable() { - @Override - public void run() { - final Editor editor = myFixture.getEditor(); - final Document document = editor.getDocument(); - final int selectionStart = editor.getSelectionModel().getSelectionStart(); - final int selectionEnd = editor.getSelectionModel().getSelectionEnd(); - CommandProcessor.getInstance().setCurrentCommandGroupId(EditorActionUtil.DELETE_COMMAND_GROUP); - document.deleteString(selectionStart, selectionEnd); - editor.getCaretModel().moveToOffset(selectionStart); - } + doTest(() -> { + final Editor editor = myFixture.getEditor(); + final Document document = editor.getDocument(); + final int selectionStart = editor.getSelectionModel().getSelectionStart(); + final int selectionEnd = editor.getSelectionModel().getSelectionEnd(); + CommandProcessor.getInstance().setCurrentCommandGroupId(EditorActionUtil.DELETE_COMMAND_GROUP); + document.deleteString(selectionStart, selectionEnd); + editor.getCaretModel().moveToOffset(selectionStart); }, true, ChangeSignatureDetectorAction.CHANGE_SIGNATURE); } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignaturePropagationTest.java b/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignaturePropagationTest.java index cf55a99acab0..1417f2a636cd 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignaturePropagationTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignaturePropagationTest.java @@ -34,7 +34,7 @@ public class ChangeSignaturePropagationTest extends LightRefactoringTestCase { public void testParamTypeSubst() throws Exception { final PsiMethod method = getPrimaryMethod(); - final HashSet methods = new HashSet(); + final HashSet methods = new HashSet<>(); for (PsiReference reference : ReferencesSearch.search(method)) { final PsiMethod psiMethod = PsiTreeUtil.getParentOfType(reference.getElement(), PsiMethod.class); if (psiMethod != null) { @@ -63,7 +63,7 @@ public class ChangeSignaturePropagationTest extends LightRefactoringTestCase { } private static HashSet collectNonPhysicalMethodsToPropagate(PsiMethod method) { - final HashSet methodsToPropagate = new HashSet(); + final HashSet methodsToPropagate = new HashSet<>(); final PsiReference[] references = MethodReferencesSearch.search(method, GlobalSearchScope.allScope(getProject()), true).toArray(PsiReference.EMPTY_ARRAY); for (PsiReference reference : references) { @@ -91,7 +91,7 @@ public class ChangeSignaturePropagationTest extends LightRefactoringTestCase { } private static HashSet collectDefaultConstructorsToPropagate(PsiMethod method) { - final HashSet methodsToPropagate = new HashSet(); + final HashSet methodsToPropagate = new HashSet<>(); for (PsiClass inheritor : ClassInheritorsSearch.search(method.getContainingClass())) { methodsToPropagate.add(inheritor.getConstructors()[0]); } @@ -105,7 +105,7 @@ public class ChangeSignaturePropagationTest extends LightRefactoringTestCase { private void parameterPropagationTest(final PsiClassType paramType) throws Exception { final PsiMethod method = getPrimaryMethod(); - parameterPropagationTest(method, new HashSet(Arrays.asList(method.getContainingClass().getMethods())), + parameterPropagationTest(method, new HashSet<>(Arrays.asList(method.getContainingClass().getMethods())), paramType); } @@ -116,7 +116,7 @@ public class ChangeSignaturePropagationTest extends LightRefactoringTestCase { private void exceptionPropagationTest() throws Exception { final PsiMethod method = getPrimaryMethod(); - exceptionPropagationTest(method, new HashSet(Arrays.asList(method.getContainingClass().getMethods()))); + exceptionPropagationTest(method, new HashSet<>(Arrays.asList(method.getContainingClass().getMethods()))); } private void exceptionPropagationTest(final PsiMethod method, final Set methodsToPropagateExceptions) throws Exception { diff --git a/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureTargetTest.java b/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureTargetTest.java index 9a860f98a786..5391cec1f45a 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureTargetTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureTargetTest.java @@ -51,6 +51,11 @@ public class ChangeSignatureTargetTest extends LightCodeInsightTestCase { doTest("A1"); } + public void testDisabledForEnum() throws Exception { + configureByFile("/refactoring/changeSignatureTarget/" + getTestName(true) + ".java"); + assertNull(new JavaChangeSignatureHandler().findTargetMember(getFile(), getEditor())); + } + private void doTest(String expectedMemberName) throws Exception { String basePath = "/refactoring/changeSignatureTarget/" + getTestName(true); @NonNls final String filePath = basePath + ".java"; diff --git a/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureTest.java b/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureTest.java index e9882d2c89e2..c0147110faca 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureTest.java @@ -54,38 +54,23 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest { } public void testGenericTypes() { - doTest(null, null, "T", new GenParams() { - @Override - public ParameterInfoImpl[] genParams(PsiMethod method) throws IncorrectOperationException { - return new ParameterInfoImpl[]{ - new ParameterInfoImpl(-1, "x", myFactory.createTypeFromText("T", method.getParameterList()), "null"), - new ParameterInfoImpl(-1, "y", myFactory.createTypeFromText("C", method.getParameterList()), "null") - }; - } + doTest(null, null, "T", method -> new ParameterInfoImpl[]{ + new ParameterInfoImpl(-1, "x", myFactory.createTypeFromText("T", method.getParameterList()), "null"), + new ParameterInfoImpl(-1, "y", myFactory.createTypeFromText("C", method.getParameterList()), "null") }, false); } public void testGenericTypesInOldParameters() { - doTest(null, null, null, new GenParams() { - @Override - public ParameterInfoImpl[] genParams(PsiMethod method) throws IncorrectOperationException { - return new ParameterInfoImpl[]{ - new ParameterInfoImpl(0, "t", myFactory.createTypeFromText("T", method), null) - }; - } + doTest(null, null, null, method -> new ParameterInfoImpl[]{ + new ParameterInfoImpl(0, "t", myFactory.createTypeFromText("T", method), null) }, false); } public void testTypeParametersInMethod() { - doTest(null, null, null, new GenParams() { - @Override - public ParameterInfoImpl[] genParams(PsiMethod method) throws IncorrectOperationException { - return new ParameterInfoImpl[]{ - new ParameterInfoImpl(-1, "t", myFactory.createTypeFromText("T", method.getParameterList()), "null"), - new ParameterInfoImpl(-1, "u", myFactory.createTypeFromText("U", method.getParameterList()), "null"), - new ParameterInfoImpl(-1, "cu", myFactory.createTypeFromText("C", method.getParameterList()), "null") - }; - } + doTest(null, null, null, method -> new ParameterInfoImpl[]{ + new ParameterInfoImpl(-1, "t", myFactory.createTypeFromText("T", method.getParameterList()), "null"), + new ParameterInfoImpl(-1, "u", myFactory.createTypeFromText("U", method.getParameterList()), "null"), + new ParameterInfoImpl(-1, "cu", myFactory.createTypeFromText("C", method.getParameterList()), "null") }, false); } @@ -215,35 +200,20 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest { } public void testUseAnyVariable() { - doTest(null, null, null, new GenParams() { - @Override - public ParameterInfoImpl[] genParams(PsiMethod method) throws IncorrectOperationException { - return new ParameterInfoImpl[]{ - new ParameterInfoImpl(-1, "l", myFactory.createTypeFromText("List", method), "null", true) - }; - } + doTest(null, null, null, method -> new ParameterInfoImpl[]{ + new ParameterInfoImpl(-1, "l", myFactory.createTypeFromText("List", method), "null", true) }, false); } public void testUseThisAsAnyVariable() { - doTest(null, null, null, new GenParams() { - @Override - public ParameterInfoImpl[] genParams(PsiMethod method) throws IncorrectOperationException { - return new ParameterInfoImpl[]{ - new ParameterInfoImpl(-1, "l", myFactory.createTypeFromText("List", method), "null", true) - }; - } + doTest(null, null, null, method -> new ParameterInfoImpl[]{ + new ParameterInfoImpl(-1, "l", myFactory.createTypeFromText("List", method), "null", true) }, false); } public void testUseAnyVariableAndDefault() { - doTest(null, null, null, new GenParams() { - @Override - public ParameterInfoImpl[] genParams(PsiMethod method) throws IncorrectOperationException { - return new ParameterInfoImpl[]{ - new ParameterInfoImpl(-1, "c", myFactory.createTypeFromText("C", method), "null", true) - }; - } + doTest(null, null, null, method -> new ParameterInfoImpl[]{ + new ParameterInfoImpl(-1, "c", myFactory.createTypeFromText("C", method), "null", true) }, false); } @@ -282,13 +252,10 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest { public void testAlreadyHandled() { doTest(null, null, null, new SimpleParameterGen(new ParameterInfoImpl[0]), - new GenExceptions() { - @Override - public ThrownExceptionInfo[] genExceptions(PsiMethod method) { - return new ThrownExceptionInfo[]{ - new JavaThrownExceptionInfo(-1, myFactory.createTypeByFQClassName("java.lang.Exception", method.getResolveScope())) - }; - } + method -> { + return new ThrownExceptionInfo[]{ + new JavaThrownExceptionInfo(-1, myFactory.createTypeByFQClassName("java.lang.Exception", method.getResolveScope())) + }; }, false ); @@ -296,13 +263,10 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest { public void testConstructorException() { doTest(null, null, null, new SimpleParameterGen(new ParameterInfoImpl[0]), - new GenExceptions() { - @Override - public ThrownExceptionInfo[] genExceptions(PsiMethod method) { - return new ThrownExceptionInfo[]{ - new JavaThrownExceptionInfo(-1, myFactory.createTypeByFQClassName("java.io.IOException", method.getResolveScope())) - }; - } + method -> { + return new ThrownExceptionInfo[]{ + new JavaThrownExceptionInfo(-1, myFactory.createTypeByFQClassName("java.io.IOException", method.getResolveScope())) + }; }, false ); @@ -310,13 +274,10 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest { public void testAddRuntimeException() { doTest(null, null, null, new SimpleParameterGen(new ParameterInfoImpl[0]), - new GenExceptions() { - @Override - public ThrownExceptionInfo[] genExceptions(PsiMethod method) { - return new ThrownExceptionInfo[]{ - new JavaThrownExceptionInfo(-1, myFactory.createTypeByFQClassName("java.lang.RuntimeException", method.getResolveScope())) - }; - } + method -> { + return new ThrownExceptionInfo[]{ + new JavaThrownExceptionInfo(-1, myFactory.createTypeByFQClassName("java.lang.RuntimeException", method.getResolveScope())) + }; }, false ); @@ -324,13 +285,10 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest { public void testAddException() { doTest(null, null, null, new SimpleParameterGen(new ParameterInfoImpl[0]), - new GenExceptions() { - @Override - public ThrownExceptionInfo[] genExceptions(PsiMethod method) { - return new ThrownExceptionInfo[]{ - new JavaThrownExceptionInfo(-1, myFactory.createTypeByFQClassName("java.lang.Exception", method.getResolveScope())) - }; - } + method -> { + return new ThrownExceptionInfo[]{ + new JavaThrownExceptionInfo(-1, myFactory.createTypeByFQClassName("java.lang.Exception", method.getResolveScope())) + }; }, false ); @@ -357,14 +315,9 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest { } public void testReplaceVarargWithArray() { - doTest(null, null, null, new GenParams() { - @Override - public ParameterInfoImpl[] genParams(PsiMethod method) throws IncorrectOperationException { - return new ParameterInfoImpl[]{ - new ParameterInfoImpl(1, "l", myFactory.createTypeFromText("List[]", method.getParameterList()), "null", false), - new ParameterInfoImpl(0, "s", myFactory.createTypeFromText("String", method.getParameterList())) - }; - } + doTest(null, null, null, method -> new ParameterInfoImpl[]{ + new ParameterInfoImpl(1, "l", myFactory.createTypeFromText("List[]", method.getParameterList()), "null", false), + new ParameterInfoImpl(0, "s", myFactory.createTypeFromText("String", method.getParameterList())) }, false); } @@ -405,7 +358,7 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest { final PsiMethod[] callers = containingClass.findMethodsByName("caller", false); assertTrue(callers.length > 0); final PsiMethod caller = callers[0]; - final HashSet propagateParametersMethods = new HashSet(); + final HashSet propagateParametersMethods = new HashSet<>(); propagateParametersMethods.add(caller); final PsiParameter[] parameters = method.getParameterList().getParameters(); new ChangeSignatureProcessor(getProject(), method, false, null, method.getName(), diff --git a/java/java-tests/testSrc/com/intellij/refactoring/CopyClassTest.java b/java/java-tests/testSrc/com/intellij/refactoring/CopyClassTest.java index 1d0751c4ddcf..4f3b34a328ff 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/CopyClassTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/CopyClassTest.java @@ -74,16 +74,10 @@ public class CopyClassTest extends CodeInsightTestCase { private PsiElement performAction(final String oldName, final String copyName) throws IncorrectOperationException { final PsiClass oldClass = JavaPsiFacade.getInstance(myProject).findClass(oldName, ProjectScope.getAllScope(myProject)); - return WriteCommandAction.runWriteCommandAction(null, new Computable(){ - @Override - public PsiElement compute() { - return CopyClassesHandler.doCopyClasses( - Collections.singletonMap(oldClass.getNavigationElement().getContainingFile(), new PsiClass[]{oldClass}), copyName, - myPsiManager.findDirectory(myRootDir), - myProject); - - } - }); + return WriteCommandAction.runWriteCommandAction(null, (Computable)() -> CopyClassesHandler.doCopyClasses( + Collections.singletonMap(oldClass.getNavigationElement().getContainingFile(), new PsiClass[]{oldClass}), copyName, + myPsiManager.findDirectory(myRootDir), + myProject)); } public void testPackageLocalClasses() throws Exception { @@ -101,7 +95,7 @@ public class CopyClassTest extends CodeInsightTestCase { PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17()); VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete); - final HashMap map = new HashMap(); + final HashMap map = new HashMap<>(); final VirtualFile sourceDir = rootDir.findChild("p1"); for (VirtualFile file : sourceDir.getChildren()) { final PsiFile psiFile = myPsiManager.findFile(file); diff --git a/java/java-tests/testSrc/com/intellij/refactoring/DndMoveTest.java b/java/java-tests/testSrc/com/intellij/refactoring/DndMoveTest.java index ee971c4e42e2..ebbf7b6ff199 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/DndMoveTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/DndMoveTest.java @@ -36,23 +36,11 @@ public class DndMoveTest extends CodeInsightTestCase { } public void testPublicJavaClass() throws Exception { - doTest("d", new Computable() { - @Nullable - @Override - public PsiElement compute() { - return getJavaFacade().findClass("d.MyClass"); - } - }, true); + doTest("d", () -> getJavaFacade().findClass("d.MyClass"), true); } public void testSecondJavaClass() throws Exception { - doTest("d", new Computable() { - @Nullable - @Override - public PsiElement compute() { - return getJavaFacade().findClass("d.Second"); - } - }, false); + doTest("d", () -> getJavaFacade().findClass("d.Second"), false); } private void doTest(final String targetDirName, final Computable source, final boolean expected) throws Exception { diff --git a/java/java-tests/testSrc/com/intellij/refactoring/EncapsulateFieldsTest.java b/java/java-tests/testSrc/com/intellij/refactoring/EncapsulateFieldsTest.java index 863e162eff6a..e8634380782b 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/EncapsulateFieldsTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/EncapsulateFieldsTest.java @@ -25,16 +25,11 @@ import com.intellij.codeInsight.generation.GenerateMembersUtil; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiField; import com.intellij.psi.PsiModifier; import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.psi.util.PropertyUtil; -import com.intellij.refactoring.encapsulateFields.EncapsulateFieldsDescriptor; -import com.intellij.refactoring.encapsulateFields.EncapsulateFieldsProcessor; -import com.intellij.refactoring.encapsulateFields.FieldDescriptor; -import com.intellij.refactoring.encapsulateFields.FieldDescriptorImpl; +import com.intellij.refactoring.encapsulateFields.*; import com.intellij.refactoring.util.DocCommentPolicy; import junit.framework.Assert; import org.jetbrains.annotations.NotNull; @@ -77,15 +72,20 @@ public class EncapsulateFieldsTest extends MultiFileTestCase{ } public void testMoveJavadocToGetter() throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception { - final PsiClass aClass = myJavaFacade.findClass("A", GlobalSearchScope.projectScope(myProject)); - assertNotNull("Tested class not found", aClass); - final PsiField field = aClass.findFieldByName("i", false); - assertNotNull(field); - doTest(aClass, field, null, true, true); - } + doTest((rootDir, rootAfter) -> { + final PsiClass aClass = myJavaFacade.findClass("A", GlobalSearchScope.projectScope(myProject)); + assertNotNull("Tested class not found", aClass); + final PsiField field = aClass.findFieldByName("i", false); + assertNotNull(field); + doTest(aClass, null, true, true, field); + }); + } + + public void testFilterEnumConstants() throws Exception { + doTest((rootDir, rootAfter) -> { + final PsiClass aClass = myJavaFacade.findClass("A", GlobalSearchScope.projectScope(myProject)); + assertNotNull("Tested class not found", aClass); + doTest(aClass, null, true, true, new JavaEncapsulateFieldHelper().getApplicableFields(aClass)); }); } @@ -106,37 +106,38 @@ public class EncapsulateFieldsTest extends MultiFileTestCase{ } private void doTest(final String fieldName, final String className, final String conflicts) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception { - PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.projectScope(myProject)); + doTest((rootDir, rootAfter) -> { + PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.projectScope(myProject)); - assertNotNull("Tested class not found", aClass); + assertNotNull("Tested class not found", aClass); - doTest(aClass, aClass.findFieldByName(fieldName, false), conflicts, true, true); - } + doTest(aClass, conflicts, true, true, aClass.findFieldByName(fieldName, false)); }); } private static void doTest(final PsiClass aClass, - final PsiField field, final String conflicts, final boolean generateGetters, - final boolean generateSetters) { + final boolean generateSetters, + final PsiField... fields) { try { final Project project = aClass.getProject(); EncapsulateFieldsProcessor processor = new EncapsulateFieldsProcessor(project, new EncapsulateFieldsDescriptor() { @Override public FieldDescriptor[] getSelectedFields() { - return new FieldDescriptor[]{new FieldDescriptorImpl( - field, - GenerateMembersUtil.suggestGetterName(field), - GenerateMembersUtil.suggestSetterName(field), - isToEncapsulateGet() ? GenerateMembersUtil.generateGetterPrototype(field) : null, - isToEncapsulateSet() ? GenerateMembersUtil.generateSetterPrototype(field) : null - )}; + final FieldDescriptor[] descriptors = new FieldDescriptor[fields.length]; + for (int i = 0; i < fields.length; i++) { + descriptors[i] = new FieldDescriptorImpl( + fields[i], + GenerateMembersUtil.suggestGetterName(fields[i]), + GenerateMembersUtil.suggestSetterName(fields[i]), + isToEncapsulateGet() ? GenerateMembersUtil.generateGetterPrototype(fields[i]) : null, + isToEncapsulateSet() ? GenerateMembersUtil.generateSetterPrototype(fields[i]) : null + ); + } + return descriptors; } @Override diff --git a/java/java-tests/testSrc/com/intellij/refactoring/ExtractClassTest.java b/java/java-tests/testSrc/com/intellij/refactoring/ExtractClassTest.java index 812b2ab0646f..e476963b1c3c 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/ExtractClassTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/ExtractClassTest.java @@ -67,18 +67,15 @@ public class ExtractClassTest extends MultiFileTestCase{ private void doTestMethod(final String methodName, final String conflicts, final String qualifiedName) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception { - PsiClass aClass = myJavaFacade.findClass(qualifiedName, GlobalSearchScope.projectScope(myProject)); + doTest((rootDir, rootAfter) -> { + PsiClass aClass = myJavaFacade.findClass(qualifiedName, GlobalSearchScope.projectScope(myProject)); - assertNotNull("Class Test not found", aClass); + assertNotNull("Class Test not found", aClass); - final ArrayList methods = new ArrayList(); - methods.add(aClass.findMethodsByName(methodName, false)[0]); - - doTest(aClass, methods, new ArrayList(), conflicts, false); - } + final ArrayList methods = new ArrayList<>(); + methods.add(aClass.findMethodsByName(methodName, false)[0]); + + doTest(aClass, methods, new ArrayList<>(), conflicts, false); }); } @@ -151,21 +148,18 @@ public class ExtractClassTest extends MultiFileTestCase{ } private void doTestFieldAndMethod(final String methodName) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception { - PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject)); + doTest((rootDir, rootAfter) -> { + PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject)); - assertNotNull("Class Test not found", aClass); + assertNotNull("Class Test not found", aClass); - final ArrayList methods = new ArrayList(); - methods.add(aClass.findMethodsByName(methodName, false)[0]); + final ArrayList methods = new ArrayList<>(); + methods.add(aClass.findMethodsByName(methodName, false)[0]); - final ArrayList fields = new ArrayList(); - fields.add(aClass.findFieldByName("myT", false)); + final ArrayList fields = new ArrayList<>(); + fields.add(aClass.findFieldByName("myT", false)); - doTest(aClass, methods, fields, null, false); - } + doTest(aClass, methods, fields, null, false); }); } @@ -174,27 +168,24 @@ public class ExtractClassTest extends MultiFileTestCase{ } private void doTestField(final String conflicts, final boolean generateGettersSetters) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception { - PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject)); + doTest((rootDir, rootAfter) -> { + PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject)); - assertNotNull("Class Test not found", aClass); + assertNotNull("Class Test not found", aClass); - final ArrayList methods = new ArrayList(); + final ArrayList methods = new ArrayList<>(); - final ArrayList fields = new ArrayList(); - fields.add(aClass.findFieldByName("myT", false)); + final ArrayList fields = new ArrayList<>(); + fields.add(aClass.findFieldByName("myT", false)); - doTest(aClass, methods, fields, conflicts, generateGettersSetters); - } + doTest(aClass, methods, fields, conflicts, generateGettersSetters); }); } private static void doTest(final PsiClass aClass, final ArrayList methods, final ArrayList fields, final String conflicts, boolean generateGettersSetters) { try { - ExtractClassProcessor processor = new ExtractClassProcessor(aClass, fields, methods, new ArrayList(), StringUtil.getPackageName(aClass.getQualifiedName()), null, + ExtractClassProcessor processor = new ExtractClassProcessor(aClass, fields, methods, new ArrayList<>(), StringUtil.getPackageName(aClass.getQualifiedName()), null, "Extracted", null, generateGettersSetters, Collections.emptyList()); processor.run(); LocalFileSystem.getInstance().refresh(false); @@ -233,39 +224,33 @@ public class ExtractClassTest extends MultiFileTestCase{ } public void testPublicFieldDelegation() throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception { - PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject)); + doTest((rootDir, rootAfter) -> { + PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject)); - assertNotNull("Class Test not found", aClass); + assertNotNull("Class Test not found", aClass); - final ArrayList fields = new ArrayList(); - fields.add(aClass.findFieldByName("myT", false)); + final ArrayList fields = new ArrayList<>(); + fields.add(aClass.findFieldByName("myT", false)); - ExtractClassProcessor processor = new ExtractClassProcessor(aClass, fields, new ArrayList(), new ArrayList(), "", "Extracted"); - processor.run(); - LocalFileSystem.getInstance().refresh(false); - FileDocumentManager.getInstance().saveAllDocuments(); - } + ExtractClassProcessor processor = new ExtractClassProcessor(aClass, fields, new ArrayList<>(), new ArrayList<>(), "", "Extracted"); + processor.run(); + LocalFileSystem.getInstance().refresh(false); + FileDocumentManager.getInstance().saveAllDocuments(); }); } private void doTestInnerClass() throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception { - PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject)); + doTest((rootDir, rootAfter) -> { + PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject)); - assertNotNull("Class Test not found", aClass); + assertNotNull("Class Test not found", aClass); - final ArrayList classes = new ArrayList(); - classes.add(aClass.findInnerClassByName("Inner", false)); - ExtractClassProcessor processor = new ExtractClassProcessor(aClass, new ArrayList(), new ArrayList(), classes, "", "Extracted"); - processor.run(); - LocalFileSystem.getInstance().refresh(false); - FileDocumentManager.getInstance().saveAllDocuments(); - } + final ArrayList classes = new ArrayList<>(); + classes.add(aClass.findInnerClassByName("Inner", false)); + ExtractClassProcessor processor = new ExtractClassProcessor(aClass, new ArrayList<>(), new ArrayList<>(), classes, "", "Extracted"); + processor.run(); + LocalFileSystem.getInstance().refresh(false); + FileDocumentManager.getInstance().saveAllDocuments(); }); } @@ -302,25 +287,22 @@ public class ExtractClassTest extends MultiFileTestCase{ } public void testPublicVisibility() throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception { - PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject)); + doTest((rootDir, rootAfter) -> { + PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject)); - assertNotNull("Class Test not found", aClass); + assertNotNull("Class Test not found", aClass); - final ArrayList methods = new ArrayList(); - methods.add(aClass.findMethodsByName("foos", false)[0]); + final ArrayList methods = new ArrayList<>(); + methods.add(aClass.findMethodsByName("foos", false)[0]); - final ArrayList fields = new ArrayList(); - fields.add(aClass.findFieldByName("myT", false)); + final ArrayList fields = new ArrayList<>(); + fields.add(aClass.findFieldByName("myT", false)); - final ExtractClassProcessor processor = - new ExtractClassProcessor(aClass, fields, methods, new ArrayList(), "", null, "Extracted", PsiModifier.PUBLIC, false, Collections.emptyList()); - processor.run(); - LocalFileSystem.getInstance().refresh(false); - FileDocumentManager.getInstance().saveAllDocuments(); - } + final ExtractClassProcessor processor = + new ExtractClassProcessor(aClass, fields, methods, new ArrayList<>(), "", null, "Extracted", PsiModifier.PUBLIC, false, Collections.emptyList()); + processor.run(); + LocalFileSystem.getInstance().refresh(false); + FileDocumentManager.getInstance().saveAllDocuments(); }); } } \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/refactoring/ExtractEnumTest.java b/java/java-tests/testSrc/com/intellij/refactoring/ExtractEnumTest.java index c6b811c693ba..174e6c554053 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/ExtractEnumTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/ExtractEnumTest.java @@ -144,53 +144,50 @@ public class ExtractEnumTest extends MultiFileTestCase { private void doTest(final String conflicts, final boolean generateAccessors, final RefactoringTestUtil.MemberDescriptor... memberDescriptors) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception { - final PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject)); - assertNotNull("Class Test not found", aClass); + doTest((rootDir, rootAfter) -> { + final PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject)); + assertNotNull("Class Test not found", aClass); - final ArrayList fields = new ArrayList(); - final ArrayList methods = new ArrayList(); - final List enumConstants = new ArrayList(); - for (MemberInfo memberInfo : RefactoringTestUtil.findMembers(aClass, memberDescriptors)) { - final PsiMember member = memberInfo.getMember(); - if (member instanceof PsiField) { - fields.add((PsiField)member); - if (member.hasModifierProperty(PsiModifier.STATIC) && member.hasModifierProperty(PsiModifier.FINAL) && ((PsiField)member).hasInitializer()) { - if (memberInfo.isToAbstract()) { - enumConstants.add(memberInfo); - memberInfo.setChecked(true); - } + final ArrayList fields = new ArrayList<>(); + final ArrayList methods = new ArrayList<>(); + final List enumConstants = new ArrayList<>(); + for (MemberInfo memberInfo : RefactoringTestUtil.findMembers(aClass, memberDescriptors)) { + final PsiMember member = memberInfo.getMember(); + if (member instanceof PsiField) { + fields.add((PsiField)member); + if (member.hasModifierProperty(PsiModifier.STATIC) && member.hasModifierProperty(PsiModifier.FINAL) && ((PsiField)member).hasInitializer()) { + if (memberInfo.isToAbstract()) { + enumConstants.add(memberInfo); + memberInfo.setChecked(true); } } - else if (member instanceof PsiMethod) { - methods.add((PsiMethod)member); - } } - try { - final ExtractClassProcessor processor = - new ExtractClassProcessor(aClass, fields, methods, new ArrayList(), "", null, "EEnum", - null, generateAccessors, enumConstants); + else if (member instanceof PsiMethod) { + methods.add((PsiMethod)member); + } + } + try { + final ExtractClassProcessor processor = + new ExtractClassProcessor(aClass, fields, methods, new ArrayList<>(), "", null, "EEnum", + null, generateAccessors, enumConstants); - processor.run(); - LocalFileSystem.getInstance().refresh(false); - FileDocumentManager.getInstance().saveAllDocuments(); - } - catch (BaseRefactoringProcessor.ConflictsInTestsException e) { - if (conflicts != null) { - TreeSet expectedConflictsSet = new TreeSet(Arrays.asList(conflicts.split("\n"))); - TreeSet actualConflictsSet = new TreeSet(Arrays.asList(e.getMessage().split("\n"))); - Assert.assertEquals(expectedConflictsSet, actualConflictsSet); - return; - } - else { - fail(e.getMessage()); - } - } + processor.run(); + LocalFileSystem.getInstance().refresh(false); + FileDocumentManager.getInstance().saveAllDocuments(); + } + catch (BaseRefactoringProcessor.ConflictsInTestsException e) { if (conflicts != null) { - fail("Conflicts were not detected: " + conflicts); + TreeSet expectedConflictsSet = new TreeSet(Arrays.asList(conflicts.split("\n"))); + TreeSet actualConflictsSet = new TreeSet(Arrays.asList(e.getMessage().split("\n"))); + Assert.assertEquals(expectedConflictsSet, actualConflictsSet); + return; } + else { + fail(e.getMessage()); + } + } + if (conflicts != null) { + fail("Conflicts were not detected: " + conflicts); } }); } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodObjectTest.java b/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodObjectTest.java index 994c4b66a211..e638a6207263 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodObjectTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodObjectTest.java @@ -41,10 +41,8 @@ public class ExtractMethodObjectTest extends LightRefactoringTestCase { extractProcessor.prepare(); extractProcessor.testPrepare(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - ExtractMethodObjectHandler.run(getProject(), getEditor(), processor, extractProcessor); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ExtractMethodObjectHandler.run(getProject(), getEditor(), processor, extractProcessor); }); diff --git a/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodObjectWithMultipleExitPointsTest.java b/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodObjectWithMultipleExitPointsTest.java index 0f1dd9f14b61..36af78daa0f6 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodObjectWithMultipleExitPointsTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodObjectWithMultipleExitPointsTest.java @@ -48,10 +48,8 @@ public class ExtractMethodObjectWithMultipleExitPointsTest extends LightRefactor processor.setCreateInnerClass(createInnerClass); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - ExtractMethodObjectHandler.run(getProject(), getEditor(), processor, extractProcessor); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ExtractMethodObjectHandler.run(getProject(), getEditor(), processor, extractProcessor); }); diff --git a/java/java-tests/testSrc/com/intellij/refactoring/ExtractSuperClassTest.java b/java/java-tests/testSrc/com/intellij/refactoring/ExtractSuperClassTest.java index 2d89d8cf4106..11a198d021e5 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/ExtractSuperClassTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/ExtractSuperClassTest.java @@ -174,7 +174,7 @@ public class ExtractSuperClassTest extends RefactoringTestCase { newClassName, psiClass, members, false, - new DocCommentPolicy(DocCommentPolicy.ASIS)); + new DocCommentPolicy<>(DocCommentPolicy.ASIS)); final PsiPackage targetPackage; if (targetDirectory != null) { targetPackage = JavaDirectoryService.getInstance().getPackage(targetDirectory); @@ -184,18 +184,14 @@ public class ExtractSuperClassTest extends RefactoringTestCase { } final PsiClass superClass = psiClass.getExtendsListTypes().length > 0 ? psiClass.getSuperClass() : null; final MultiMap conflictsMap = - PullUpConflictsUtil.checkConflicts(members, psiClass, superClass, targetPackage, targetDirectory, new InterfaceContainmentVerifier() { - @Override - public boolean checkedInterfacesContain(PsiMethod psiMethod) { - return PullUpProcessor.checkedInterfacesContain(Arrays.asList(members), psiMethod); - } - }, false); + PullUpConflictsUtil.checkConflicts(members, psiClass, superClass, targetPackage, targetDirectory, + psiMethod -> PullUpProcessor.checkedInterfacesContain(Arrays.asList(members), psiMethod), false); if (conflicts != null) { if (conflictsMap.isEmpty()) { fail("Conflicts were not detected"); } - final HashSet expectedConflicts = new HashSet(Arrays.asList(conflicts)); - final HashSet actualConflicts = new HashSet(conflictsMap.values()); + final HashSet expectedConflicts = new HashSet<>(Arrays.asList(conflicts)); + final HashSet actualConflicts = new HashSet<>(conflictsMap.values()); assertEquals(expectedConflicts.size(), actualConflicts.size()); for (String actualConflict : actualConflicts) { if (!expectedConflicts.contains(actualConflict)) { diff --git a/java/java-tests/testSrc/com/intellij/refactoring/FixMethodJavadocTest.java b/java/java-tests/testSrc/com/intellij/refactoring/FixMethodJavadocTest.java index 0a8937f7bcb0..80f3f498dea8 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/FixMethodJavadocTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/FixMethodJavadocTest.java @@ -32,7 +32,7 @@ public abstract class FixMethodJavadocTest extends FileSetTestCase { final PsiManager manager = PsiManager.getInstance(myProject); final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); final PsiMethod method = factory.createMethodFromText(data[0], null); - final HashSet newParameters = new HashSet(); + final HashSet newParameters = new HashSet<>(); if (data.length == 2) { final String[] strings = data[1].split("\\s+"); collectNewParameters(method, strings, newParameters); @@ -42,7 +42,7 @@ public abstract class FixMethodJavadocTest extends FileSetTestCase { } private void collectNewParameters(PsiMethod method, String[] names, Set newParameters) { - Set newNames = new HashSet(Arrays.asList(names)); + Set newNames = new HashSet<>(Arrays.asList(names)); final PsiParameter[] parameters = method.getParameterList().getParameters(); for (int i = 0; i < parameters.length; i++) { PsiParameter parameter = parameters[i]; diff --git a/java/java-tests/testSrc/com/intellij/refactoring/InheritanceToDelegationTest.java b/java/java-tests/testSrc/com/intellij/refactoring/InheritanceToDelegationTest.java index 01068325c9ee..0734348941b6 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/InheritanceToDelegationTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/InheritanceToDelegationTest.java @@ -139,30 +139,27 @@ public class InheritanceToDelegationTest extends MultiFileTestCase { final String className, final String fieldName, final String innerClassName, final String baseClassName, final int[] methodIndices, final String[] delegatedInterfaceNames, final boolean delegateOtherMembers, final boolean generateGetter) { - return new PerformAction() { - @Override - public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception { - PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.allScope(getProject())); - assertNotNull("Class " + className + " not found", aClass); - PsiClass baseClass = myJavaFacade.findClass(baseClassName, GlobalSearchScope.allScope(getProject())); - assertNotNull("Base class " + baseClassName + " not found", baseClass); - final PsiMethod[] methods = baseClass.getMethods(); - final PsiMethod[] delegatedMethods = new PsiMethod[methodIndices.length]; - for (int i = 0; i < methodIndices.length; i++) { - delegatedMethods[i] = methods[methodIndices[i]]; - } - final PsiClass[] delegatedInterfaces = new PsiClass[delegatedInterfaceNames.length]; - for (int i = 0; i < delegatedInterfaceNames.length; i++) { - String delegatedInterfaceName = delegatedInterfaceNames[i]; - PsiClass anInterface = myJavaFacade.findClass(delegatedInterfaceName, GlobalSearchScope.allScope(getProject())); - assertNotNull(anInterface); - delegatedInterfaces[i] = anInterface; - } - new InheritanceToDelegationProcessor( - myProject, - aClass, baseClass, fieldName, innerClassName, delegatedInterfaces, delegatedMethods, delegateOtherMembers, - generateGetter).run(); + return (rootDir, rootAfter) -> { + PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.allScope(getProject())); + assertNotNull("Class " + className + " not found", aClass); + PsiClass baseClass = myJavaFacade.findClass(baseClassName, GlobalSearchScope.allScope(getProject())); + assertNotNull("Base class " + baseClassName + " not found", baseClass); + final PsiMethod[] methods = baseClass.getMethods(); + final PsiMethod[] delegatedMethods = new PsiMethod[methodIndices.length]; + for (int i = 0; i < methodIndices.length; i++) { + delegatedMethods[i] = methods[methodIndices[i]]; } + final PsiClass[] delegatedInterfaces = new PsiClass[delegatedInterfaceNames.length]; + for (int i = 0; i < delegatedInterfaceNames.length; i++) { + String delegatedInterfaceName = delegatedInterfaceNames[i]; + PsiClass anInterface = myJavaFacade.findClass(delegatedInterfaceName, GlobalSearchScope.allScope(getProject())); + assertNotNull(anInterface); + delegatedInterfaces[i] = anInterface; + } + new InheritanceToDelegationProcessor( + myProject, + aClass, baseClass, fieldName, innerClassName, delegatedInterfaces, delegatedMethods, delegateOtherMembers, + generateGetter).run(); }; } @@ -170,34 +167,31 @@ public class InheritanceToDelegationTest extends MultiFileTestCase { final String className, final String fieldName, final String innerClassName, final String baseClassName, final String[] methodNames, final String[] delegatedInterfaceNames, final boolean delegateOtherMembers, final boolean generateGetter) { - return new PerformAction() { - @Override - public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception { - PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.allScope(getProject())); - assertNotNull("Class " + className + " not found", aClass); - PsiClass baseClass = myJavaFacade.findClass(baseClassName, GlobalSearchScope.allScope(getProject())); - assertNotNull("Base class " + baseClassName + " not found", baseClass); - final PsiMethod[] delegatedMethods; - final List methodsList = new ArrayList(); - for (String name : methodNames) { - final PsiMethod[] methodsByName = baseClass.findMethodsByName(name, false); - ContainerUtil.addAll(methodsList, methodsByName); - } - delegatedMethods = methodsList.toArray(new PsiMethod[methodsList.size()]); - - final PsiClass[] delegatedInterfaces = new PsiClass[delegatedInterfaceNames.length]; - for (int i = 0; i < delegatedInterfaceNames.length; i++) { - String delegatedInterfaceName = delegatedInterfaceNames[i]; - PsiClass anInterface = myJavaFacade.findClass(delegatedInterfaceName, GlobalSearchScope.allScope(getProject())); - assertNotNull(anInterface); - delegatedInterfaces[i] = anInterface; - } - new InheritanceToDelegationProcessor( - myProject, - aClass, baseClass, fieldName, innerClassName, delegatedInterfaces, delegatedMethods, delegateOtherMembers, - generateGetter).run(); - //FileDocumentManager.getInstance().saveAllDocuments(); + return (rootDir, rootAfter) -> { + PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.allScope(getProject())); + assertNotNull("Class " + className + " not found", aClass); + PsiClass baseClass = myJavaFacade.findClass(baseClassName, GlobalSearchScope.allScope(getProject())); + assertNotNull("Base class " + baseClassName + " not found", baseClass); + final PsiMethod[] delegatedMethods; + final List methodsList = new ArrayList<>(); + for (String name : methodNames) { + final PsiMethod[] methodsByName = baseClass.findMethodsByName(name, false); + ContainerUtil.addAll(methodsList, methodsByName); } + delegatedMethods = methodsList.toArray(new PsiMethod[methodsList.size()]); + + final PsiClass[] delegatedInterfaces = new PsiClass[delegatedInterfaceNames.length]; + for (int i = 0; i < delegatedInterfaceNames.length; i++) { + String delegatedInterfaceName = delegatedInterfaceNames[i]; + PsiClass anInterface = myJavaFacade.findClass(delegatedInterfaceName, GlobalSearchScope.allScope(getProject())); + assertNotNull(anInterface); + delegatedInterfaces[i] = anInterface; + } + new InheritanceToDelegationProcessor( + myProject, + aClass, baseClass, fieldName, innerClassName, delegatedInterfaces, delegatedMethods, delegateOtherMembers, + generateGetter).run(); + //FileDocumentManager.getInstance().saveAllDocuments(); }; } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/InlineSuperClassTest.java b/java/java-tests/testSrc/com/intellij/refactoring/InlineSuperClassTest.java index 701a967ad2a5..658f41934f9d 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/InlineSuperClassTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/InlineSuperClassTest.java @@ -77,18 +77,15 @@ public class InlineSuperClassTest extends MultiFileTestCase { private void doTest(boolean fail, final boolean inlineOne) { try { - doTest(new PerformAction() { - @Override - public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception { - GlobalSearchScope scope = GlobalSearchScope.allScope(myProject); - PsiClass aClass = myJavaFacade.findClass("Test", scope); - if (aClass == null) aClass = myJavaFacade.findClass("p.Test", scope); - assertNotNull("Class Test not found", aClass); - PsiClass superClass = myJavaFacade.findClass("Super", scope); - if (superClass == null) superClass = myJavaFacade.findClass("p1.Super", scope); - assertNotNull("Class Super not found", superClass); - new InlineSuperClassRefactoringProcessor(myProject, inlineOne ? aClass : null, superClass, DocCommentPolicy.ASIS, aClass).run(); - } + doTest((rootDir, rootAfter) -> { + GlobalSearchScope scope = GlobalSearchScope.allScope(myProject); + PsiClass aClass = myJavaFacade.findClass("Test", scope); + if (aClass == null) aClass = myJavaFacade.findClass("p.Test", scope); + assertNotNull("Class Test not found", aClass); + PsiClass superClass = myJavaFacade.findClass("Super", scope); + if (superClass == null) superClass = myJavaFacade.findClass("p1.Super", scope); + assertNotNull("Class Super not found", superClass); + new InlineSuperClassRefactoringProcessor(myProject, inlineOne ? aClass : null, superClass, DocCommentPolicy.ASIS, aClass).run(); }); } catch (BaseRefactoringProcessor.ConflictsInTestsException e) { @@ -105,17 +102,14 @@ public class InlineSuperClassTest extends MultiFileTestCase { } private void doTestMultipleSubclasses() { - doTest(new PerformAction() { - @Override - public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception { - GlobalSearchScope scope = GlobalSearchScope.allScope(myProject); - PsiClass superClass = myJavaFacade.findClass("Super", scope); - if (superClass == null) superClass = myJavaFacade.findClass("p1.Super", scope); - assertNotNull("Class Super not found", superClass); - PsiClass target1 = myJavaFacade.findClass("Test", scope); - PsiClass target2 = myJavaFacade.findClass("Test1", scope); - new InlineSuperClassRefactoringProcessor(myProject, null, superClass, DocCommentPolicy.ASIS, target1, target2).run(); - } + doTest((rootDir, rootAfter) -> { + GlobalSearchScope scope = GlobalSearchScope.allScope(myProject); + PsiClass superClass = myJavaFacade.findClass("Super", scope); + if (superClass == null) superClass = myJavaFacade.findClass("p1.Super", scope); + assertNotNull("Class Super not found", superClass); + PsiClass target1 = myJavaFacade.findClass("Test", scope); + PsiClass target2 = myJavaFacade.findClass("Test1", scope); + new InlineSuperClassRefactoringProcessor(myProject, null, superClass, DocCommentPolicy.ASIS, target1, target2).run(); }); } } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/IntroduceParameterObjectTest.java b/java/java-tests/testSrc/com/intellij/refactoring/IntroduceParameterObjectTest.java index 387424a4ffd3..5496b11074e9 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/IntroduceParameterObjectTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/IntroduceParameterObjectTest.java @@ -23,7 +23,6 @@ package com.intellij.refactoring; import com.intellij.JavaTestUtil; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.refactoring.introduceparameterobject.IntroduceParameterObjectProcessor; @@ -48,31 +47,23 @@ public class IntroduceParameterObjectTest extends MultiFileTestCase{ } private void doTest(final boolean delegate, final boolean createInner) throws Exception { - doTest(delegate, createInner, new Function() { - @Override - public VariableData[] fun(PsiMethod psiMethod) { - return generateParams(psiMethod); - } - }); + doTest(delegate, createInner, IntroduceParameterObjectTest::generateParams); } private void doTest(final boolean delegate, final boolean createInner, final Function function) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception { - PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(getProject())); + doTest((rootDir, rootAfter) -> { + PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(getProject())); - assertNotNull("Class Test not found", aClass); + assertNotNull("Class Test not found", aClass); - final PsiMethod method = aClass.findMethodsByName("foo", false)[0]; - final VariableData[] datas = function.fun(method); + final PsiMethod method = aClass.findMethodsByName("foo", false)[0]; + final VariableData[] datas = function.fun(method); - IntroduceParameterObjectProcessor processor = new IntroduceParameterObjectProcessor("Param", "", null, method, datas, delegate, false, - createInner, null, false); - processor.run(); - } + IntroduceParameterObjectProcessor processor = new IntroduceParameterObjectProcessor("Param", "", null, method, datas, delegate, false, + createInner, null, false); + processor.run(); }); } @@ -134,53 +125,44 @@ public class IntroduceParameterObjectTest extends MultiFileTestCase{ } public void testSameTypeAndVarargs() throws Exception { - doTest(false, false, new Function() { - @Override - public VariableData[] fun(PsiMethod method) { - final PsiParameter[] parameters = method.getParameterList().getParameters(); + doTest(false, false, method -> { + final PsiParameter[] parameters = method.getParameterList().getParameters(); - final VariableData[] datas = new VariableData[parameters.length - 1]; - for (int i = 0; i < parameters.length - 1; i++) { - PsiParameter parameter = parameters[i]; - datas[i] = new VariableData(parameter); - datas[i].name = parameter.getName(); - datas[i].passAsParameter = true; - } - return datas; + final VariableData[] datas = new VariableData[parameters.length - 1]; + for (int i = 0; i < parameters.length - 1; i++) { + PsiParameter parameter = parameters[i]; + datas[i] = new VariableData(parameter); + datas[i].name = parameter.getName(); + datas[i].passAsParameter = true; } + return datas; }); } public void testCopyJavadoc1() throws Exception { - doTest(false, true, new Function() { - @Override - public VariableData[] fun(PsiMethod method) { - final PsiParameter[] parameters = method.getParameterList().getParameters(); + doTest(false, true, method -> { + final PsiParameter[] parameters = method.getParameterList().getParameters(); - final VariableData[] datas = new VariableData[parameters.length - 1]; - for (int i = 0; i < parameters.length - 1; i++) { - PsiParameter parameter = parameters[i]; - datas[i] = new VariableData(parameter); - datas[i].name = parameter.getName(); - datas[i].passAsParameter = true; - } - return datas; + final VariableData[] datas = new VariableData[parameters.length - 1]; + for (int i = 0; i < parameters.length - 1; i++) { + PsiParameter parameter = parameters[i]; + datas[i] = new VariableData(parameter); + datas[i].name = parameter.getName(); + datas[i].passAsParameter = true; } + return datas; }); } public void testTypeParametersWithChosenSubtype() throws Exception { - doTest(false, true, new Function() { - @Override - public VariableData[] fun(PsiMethod psiMethod) { - final PsiParameter parameter = psiMethod.getParameterList().getParameters()[0]; - final PsiClass collectionClass = getJavaFacade().findClass(CommonClassNames.JAVA_UTIL_COLLECTION); - final VariableData variableData = - new VariableData(parameter, JavaPsiFacade.getElementFactory(getProject()).createType(collectionClass)); - variableData.name = parameter.getName(); - variableData.passAsParameter = true; - return new VariableData[]{variableData}; - } + doTest(false, true, psiMethod -> { + final PsiParameter parameter = psiMethod.getParameterList().getParameters()[0]; + final PsiClass collectionClass = getJavaFacade().findClass(CommonClassNames.JAVA_UTIL_COLLECTION); + final VariableData variableData = + new VariableData(parameter, JavaPsiFacade.getElementFactory(getProject()).createType(collectionClass)); + variableData.name = parameter.getName(); + variableData.passAsParameter = true; + return new VariableData[]{variableData}; }); } @@ -198,23 +180,20 @@ public class IntroduceParameterObjectTest extends MultiFileTestCase{ private void doTestExistingClass(final String existingClassName, final String existingClassPackage, final boolean generateAccessors, final String newVisibility) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception { - PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(getProject())); - if (aClass == null) { - aClass = myJavaFacade.findClass("p2.Test", GlobalSearchScope.projectScope(getProject())); - } - assertNotNull("Class Test not found", aClass); - - final PsiMethod method = aClass.findMethodsByName("foo", false)[0]; - IntroduceParameterObjectProcessor processor = new IntroduceParameterObjectProcessor(existingClassName, existingClassPackage, null, method, - generateParams(method), false, true, - false, newVisibility, generateAccessors); - processor.run(); - LocalFileSystem.getInstance().refresh(false); - FileDocumentManager.getInstance().saveAllDocuments(); + doTest((rootDir, rootAfter) -> { + PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(getProject())); + if (aClass == null) { + aClass = myJavaFacade.findClass("p2.Test", GlobalSearchScope.projectScope(getProject())); } + assertNotNull("Class Test not found", aClass); + + final PsiMethod method = aClass.findMethodsByName("foo", false)[0]; + IntroduceParameterObjectProcessor processor = new IntroduceParameterObjectProcessor(existingClassName, existingClassPackage, null, method, + generateParams(method), false, true, + false, newVisibility, generateAccessors); + processor.run(); + LocalFileSystem.getInstance().refresh(false); + FileDocumentManager.getInstance().saveAllDocuments(); }); } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableMultifileTest.java b/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableMultifileTest.java index b200906a58ef..74f7496ce24f 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableMultifileTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableMultifileTest.java @@ -94,20 +94,17 @@ public class IntroduceVariableMultifileTest extends MultiFileTestCase { } PerformAction createAction(final String className, final IntroduceVariableBase testMe) { - return new PerformAction() { - @Override - public void performAction(VirtualFile vroot, VirtualFile rootAfter) { - final JavaPsiFacade psiManager = getJavaFacade(); - final PsiClass aClass = psiManager.findClass(className, GlobalSearchScope.allScope(myProject)); - assertTrue(className + " class not found", aClass != null); - final PsiFile containingFile = aClass.getContainingFile(); - final VirtualFile virtualFile = containingFile.getVirtualFile(); - assertTrue(virtualFile != null); - final Editor editor = createEditor(virtualFile); - setupCursorAndSelection(editor); - testMe.invoke(myProject, editor, containingFile, null); - FileDocumentManager.getInstance().saveAllDocuments(); - } + return (vroot, rootAfter) -> { + final JavaPsiFacade psiManager = getJavaFacade(); + final PsiClass aClass = psiManager.findClass(className, GlobalSearchScope.allScope(myProject)); + assertTrue(className + " class not found", aClass != null); + final PsiFile containingFile = aClass.getContainingFile(); + final VirtualFile virtualFile = containingFile.getVirtualFile(); + assertTrue(virtualFile != null); + final Editor editor = createEditor(virtualFile); + setupCursorAndSelection(editor); + testMe.invoke(myProject, editor, containingFile, null); + FileDocumentManager.getInstance().saveAllDocuments(); }; } } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/LightRefactoringParameterizedTestCase.java b/java/java-tests/testSrc/com/intellij/refactoring/LightRefactoringParameterizedTestCase.java index b822a6684373..8802f68156c4 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/LightRefactoringParameterizedTestCase.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/LightRefactoringParameterizedTestCase.java @@ -51,57 +51,44 @@ public abstract class LightRefactoringParameterizedTestCase extends LightRefacto public void runSingle() throws Throwable { final Throwable[] throwables = new Throwable[1]; - final Runnable runnable = new Runnable() { - @Override - public void run() { + final Runnable runnable = () -> { + try { + final String filePath = getBeforeFile(myFileSuffix); + configureByFile(filePath); + + final File testDir = new File(getTestDataPath(), filePath).getParentFile(); + final String afterName = getAfterFile(myFileSuffix); + final boolean conflictShouldBeFound = !new File(testDir, afterName).exists(); try { - final String filePath = getBeforeFile(myFileSuffix); - configureByFile(filePath); - - final File testDir = new File(getTestDataPath(), filePath).getParentFile(); - final String afterName = getAfterFile(myFileSuffix); - final boolean conflictShouldBeFound = !new File(testDir, afterName).exists(); - try { - perform(); - if (conflictShouldBeFound) { - fail("Conflict expected."); - } + perform(); + if (conflictShouldBeFound) { + fail("Conflict expected."); } - catch (BaseRefactoringProcessor.ConflictsInTestsException exception) { - if (!conflictShouldBeFound) { - fail("Conflict not expected"); - } else { - final File conflicts = new File(testDir, FileUtilRt.getNameWithoutExtension(myFileSuffix) + CONFLICTS_SUFFIX); - if (!conflicts.exists()) { - fail("Conflict file " + conflicts.getPath() + " not found"); - } - final VirtualFile conflictsFile = VfsUtil.findFileByIoFile(conflicts, false); - assertNotNull(conflictsFile); - assertEquals(LoadTextUtil.loadText(conflictsFile).toString(), exception.getMessage()); - } - } - + } + catch (BaseRefactoringProcessor.ConflictsInTestsException exception) { if (!conflictShouldBeFound) { - checkResultByFile(getAfterFile(myFileSuffix)); + fail("Conflict not expected"); + } else { + final File conflicts = new File(testDir, FileUtilRt.getNameWithoutExtension(myFileSuffix) + CONFLICTS_SUFFIX); + if (!conflicts.exists()) { + fail("Conflict file " + conflicts.getPath() + " not found"); + } + final VirtualFile conflictsFile = VfsUtil.findFileByIoFile(conflicts, false); + assertNotNull(conflictsFile); + assertEquals(LoadTextUtil.loadText(conflictsFile).toString(), exception.getMessage()); } } - catch (Throwable e) { - throwables[0] = e; + + if (!conflictShouldBeFound) { + checkResultByFile(getAfterFile(myFileSuffix)); } } + catch (Throwable e) { + throwables[0] = e; + } }; - invokeTestRunnable(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - runnable.run(); - } - }, "", null); - } - }); + invokeTestRunnable(() -> CommandProcessor.getInstance().executeCommand(getProject(), runnable::run, "", null)); if (throwables[0] != null) { throw throwables[0]; diff --git a/java/java-tests/testSrc/com/intellij/refactoring/MakeClassStaticTest.java b/java/java-tests/testSrc/com/intellij/refactoring/MakeClassStaticTest.java index e9b48dffb6ea..ba225e2ab864 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/MakeClassStaticTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/MakeClassStaticTest.java @@ -83,7 +83,7 @@ public class MakeClassStaticTest extends LightRefactoringTestCase { PsiElement element = TargetElementUtil.findTargetElement(myEditor, TargetElementUtil.ELEMENT_NAME_ACCEPTED); assertTrue(element instanceof PsiClass); PsiClass aClass = (PsiClass)element; - final ArrayList parametersForFields = new ArrayList(); + final ArrayList parametersForFields = new ArrayList<>(); final boolean addClassParameter = MakeStaticUtil.buildVariableData(aClass, parametersForFields); new MakeClassStaticProcessor( diff --git a/java/java-tests/testSrc/com/intellij/refactoring/MakeMethodStaticTest.java b/java/java-tests/testSrc/com/intellij/refactoring/MakeMethodStaticTest.java index eb82932852c3..77ef51199ab3 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/MakeMethodStaticTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/MakeMethodStaticTest.java @@ -248,7 +248,7 @@ public class MakeMethodStaticTest extends LightRefactoringTestCase { PsiElement element = TargetElementUtil.findTargetElement(myEditor, TargetElementUtil.ELEMENT_NAME_ACCEPTED); assertTrue(element instanceof PsiMethod); PsiMethod method = (PsiMethod) element; - final ArrayList parametersForFields = new ArrayList(); + final ArrayList parametersForFields = new ArrayList<>(); final boolean addClassParameter = MakeStaticUtil.buildVariableData(method, parametersForFields); new MakeMethodStaticProcessor( diff --git a/java/java-tests/testSrc/com/intellij/refactoring/MoveMembersTest.java b/java/java-tests/testSrc/com/intellij/refactoring/MoveMembersTest.java index b34486fcf110..e1e66c483fc4 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/MoveMembersTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/MoveMembersTest.java @@ -222,11 +222,8 @@ public class MoveMembersTest extends MultiFileTestCase { final String defaultVisibility, final int... memberIndices) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception { - MoveMembersTest.this.performAction(sourceClassName, targetClassName, memberIndices, defaultVisibility); - } + doTest((rootDir, rootAfter) -> { + MoveMembersTest.this.performAction(sourceClassName, targetClassName, memberIndices, defaultVisibility); }, lowercaseFirstLetter); } @@ -237,14 +234,14 @@ public class MoveMembersTest extends MultiFileTestCase { assertNotNull("Class " + targetClassName + " not found", targetClass); PsiElement[] children = sourceClass.getChildren(); - ArrayList members = new ArrayList(); + ArrayList members = new ArrayList<>(); for (PsiElement child : children) { if (child instanceof PsiMember) { members.add(((PsiMember) child)); } } - LinkedHashSet memberSet = new LinkedHashSet(); + LinkedHashSet memberSet = new LinkedHashSet<>(); for (int index : memberIndices) { PsiMember member = members.get(index); assertTrue(member.hasModifierProperty(PsiModifier.STATIC)); diff --git a/java/java-tests/testSrc/com/intellij/refactoring/MovePackageAsDirectoryTest.java b/java/java-tests/testSrc/com/intellij/refactoring/MovePackageAsDirectoryTest.java index 63e92871ccf5..3e611124a549 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/MovePackageAsDirectoryTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/MovePackageAsDirectoryTest.java @@ -52,16 +52,13 @@ public class MovePackageAsDirectoryTest extends MultiFileTestCase { } public void testRenamePackage() throws Exception { - final PerformAction action = new PerformAction() { - @Override - public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception { - final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(myProject); - final PsiPackage sourcePackage = psiFacade.findPackage("pack1"); - assertNotNull(sourcePackage); - - RenamePsiPackageProcessor.createRenameMoveProcessor("pack1.pack2", sourcePackage, false, false).run(); - FileDocumentManager.getInstance().saveAllDocuments(); - } + final PerformAction action = (rootDir, rootAfter) -> { + final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(myProject); + final PsiPackage sourcePackage = psiFacade.findPackage("pack1"); + assertNotNull(sourcePackage); + + RenamePsiPackageProcessor.createRenameMoveProcessor("pack1.pack2", sourcePackage, false, false).run(); + FileDocumentManager.getInstance().saveAllDocuments(); }; doTest(action); } @@ -105,21 +102,15 @@ public class MovePackageAsDirectoryTest extends MultiFileTestCase { protected void preprocessSrcDir(PsiDirectory srcDirectory) { final PsiFile empty = srcDirectory.findFile(EMPTY_TXT); assert empty != null; - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - public void run() { - empty.delete(); - } - }); + WriteCommandAction.runWriteCommandAction(null, empty::delete); } @Override protected void postProcessTargetDir(PsiDirectory targetDirectory) { final PsiDirectory subdirectory = targetDirectory.findSubdirectory(packageName); assert subdirectory != null; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - subdirectory.createFile(EMPTY_TXT); - } + ApplicationManager.getApplication().runWriteAction(() -> { + subdirectory.createFile(EMPTY_TXT); }); } }); @@ -133,11 +124,7 @@ public class MovePackageAsDirectoryTest extends MultiFileTestCase { protected void preprocessSrcDir(PsiDirectory srcDirectory) { final PsiClass empty = JavaPsiFacade.getInstance(getProject()).findClass(FOO, GlobalSearchScope.projectScope(getProject())); assert empty != null; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - empty.delete(); - } - }); + ApplicationManager.getApplication().runWriteAction(empty::delete); } @Override @@ -146,10 +133,8 @@ public class MovePackageAsDirectoryTest extends MultiFileTestCase { assert subdirectory != null; final PsiDirectory emptyDir = subdirectory.findSubdirectory("subPack"); assert emptyDir != null; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - emptyDir.createFile(EMPTY_TXT); - } + ApplicationManager.getApplication().runWriteAction(() -> { + emptyDir.createFile(EMPTY_TXT); }); } }); @@ -182,12 +167,8 @@ public class MovePackageAsDirectoryTest extends MultiFileTestCase { @Override public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception { final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(myProject); - final Comparator directoryComparator = new Comparator() { - @Override - public int compare(PsiDirectory o1, PsiDirectory o2) { - return o1.getVirtualFile().getPresentableUrl().compareTo(o2.getVirtualFile().getPresentableUrl()); - } - }; + final Comparator directoryComparator = + (o1, o2) -> o1.getVirtualFile().getPresentableUrl().compareTo(o2.getVirtualFile().getPresentableUrl()); final PsiPackage sourcePackage = psiFacade.findPackage(myPackageName); assertNotNull(sourcePackage); diff --git a/java/java-tests/testSrc/com/intellij/refactoring/MovePackageMultirootTest.java b/java/java-tests/testSrc/com/intellij/refactoring/MovePackageMultirootTest.java index 1ae0af9a8016..15083af219bb 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/MovePackageMultirootTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/MovePackageMultirootTest.java @@ -51,23 +51,20 @@ public class MovePackageMultirootTest extends MultiFileTestCase { } private PerformAction createAction(final String[] packageNames, final String targetPackageName) { - return new PerformAction() { - @Override - public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception { - final PsiManager manager = PsiManager.getInstance(myProject); - PsiPackage[] sourcePackages = new PsiPackage[packageNames.length]; - for (int i = 0; i < packageNames.length; i++) { - String packageName = packageNames[i]; - sourcePackages[i] = JavaPsiFacade.getInstance(manager.getProject()).findPackage(packageName); - assertNotNull(sourcePackages[i]); - } - PsiPackage targetPackage = JavaPsiFacade.getInstance(manager.getProject()).findPackage(targetPackageName); - assertNotNull(targetPackage); - new MoveClassesOrPackagesProcessor(myProject, sourcePackages, - new MultipleRootsMoveDestination(new PackageWrapper(targetPackage)), - true, true, null).run(); - FileDocumentManager.getInstance().saveAllDocuments(); + return (rootDir, rootAfter) -> { + final PsiManager manager = PsiManager.getInstance(myProject); + PsiPackage[] sourcePackages = new PsiPackage[packageNames.length]; + for (int i = 0; i < packageNames.length; i++) { + String packageName = packageNames[i]; + sourcePackages[i] = JavaPsiFacade.getInstance(manager.getProject()).findPackage(packageName); + assertNotNull(sourcePackages[i]); } + PsiPackage targetPackage = JavaPsiFacade.getInstance(manager.getProject()).findPackage(targetPackageName); + assertNotNull(targetPackage); + new MoveClassesOrPackagesProcessor(myProject, sourcePackages, + new MultipleRootsMoveDestination(new PackageWrapper(targetPackage)), + true, true, null).run(); + FileDocumentManager.getInstance().saveAllDocuments(); }; } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/MovePackageTest.java b/java/java-tests/testSrc/com/intellij/refactoring/MovePackageTest.java index 19296b0152d9..cdcec6de4806 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/MovePackageTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/MovePackageTest.java @@ -56,12 +56,7 @@ public class MovePackageTest extends MultiFileTestCase { } private void doTest(final String[] packageNames, final String newPackageName) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception { - MovePackageTest.this.performAction(packageNames, newPackageName); - } - }); + doTest((rootDir, rootAfter) -> MovePackageTest.this.performAction(packageNames, newPackageName)); } private void performAction(String[] packageNames, String newPackageName) throws Exception { diff --git a/java/java-tests/testSrc/com/intellij/refactoring/PullUpMultifileTest.java b/java/java-tests/testSrc/com/intellij/refactoring/PullUpMultifileTest.java index 195f91ad62a5..a4961a253095 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/PullUpMultifileTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/PullUpMultifileTest.java @@ -21,13 +21,11 @@ package com.intellij.refactoring; import com.intellij.JavaTestUtil; -import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.refactoring.memberPullUp.PullUpConflictsUtil; import com.intellij.refactoring.memberPullUp.PullUpProcessor; import com.intellij.refactoring.util.DocCommentPolicy; -import com.intellij.refactoring.util.classMembers.InterfaceContainmentVerifier; import com.intellij.refactoring.util.classMembers.MemberInfo; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.NotNull; @@ -49,42 +47,35 @@ public class PullUpMultifileTest extends MultiFileTestCase { } private void doTest(final String... conflicts) throws Exception { - final MultiMap conflictsMap = new MultiMap(); - doTest(new PerformAction() { - @Override - public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception { - final PsiClass srcClass = myJavaFacade.findClass("a.A", GlobalSearchScope.allScope(myProject)); - assertTrue("Source class not found", srcClass != null); + final MultiMap conflictsMap = new MultiMap<>(); + doTest((rootDir, rootAfter) -> { + final PsiClass srcClass = myJavaFacade.findClass("a.A", GlobalSearchScope.allScope(myProject)); + assertTrue("Source class not found", srcClass != null); - final PsiClass targetClass = myJavaFacade.findClass("b.B", GlobalSearchScope.allScope(myProject)); - assertTrue("Target class not found", targetClass != null); + final PsiClass targetClass = myJavaFacade.findClass("b.B", GlobalSearchScope.allScope(myProject)); + assertTrue("Target class not found", targetClass != null); - final PsiMethod[] methods = srcClass.getMethods(); - assertTrue("No methods found", methods.length > 0); - final MemberInfo[] membersToMove = new MemberInfo[1]; - final MemberInfo memberInfo = new MemberInfo(methods[0]); - memberInfo.setChecked(true); - membersToMove[0] = memberInfo; + final PsiMethod[] methods = srcClass.getMethods(); + assertTrue("No methods found", methods.length > 0); + final MemberInfo[] membersToMove = new MemberInfo[1]; + final MemberInfo memberInfo = new MemberInfo(methods[0]); + memberInfo.setChecked(true); + membersToMove[0] = memberInfo; - final PsiDirectory targetDirectory = targetClass.getContainingFile().getContainingDirectory(); - final PsiPackage targetPackage = targetDirectory != null ? JavaDirectoryService.getInstance().getPackage(targetDirectory) : null; - conflictsMap.putAllValues( - PullUpConflictsUtil.checkConflicts(membersToMove, srcClass, targetClass, targetPackage, targetDirectory, new InterfaceContainmentVerifier() { - @Override - public boolean checkedInterfacesContain(PsiMethod psiMethod) { - return PullUpProcessor.checkedInterfacesContain(Arrays.asList(membersToMove), psiMethod); - } - })); + final PsiDirectory targetDirectory = targetClass.getContainingFile().getContainingDirectory(); + final PsiPackage targetPackage = targetDirectory != null ? JavaDirectoryService.getInstance().getPackage(targetDirectory) : null; + conflictsMap.putAllValues( + PullUpConflictsUtil.checkConflicts(membersToMove, srcClass, targetClass, targetPackage, targetDirectory, + psiMethod -> PullUpProcessor.checkedInterfacesContain(Arrays.asList(membersToMove), psiMethod))); - new PullUpProcessor(srcClass, targetClass, membersToMove, new DocCommentPolicy(DocCommentPolicy.ASIS)).run(); - } + new PullUpProcessor(srcClass, targetClass, membersToMove, new DocCommentPolicy(DocCommentPolicy.ASIS)).run(); }); if (conflicts.length != 0 && conflictsMap.isEmpty()) { fail("Conflict was not detected"); } - final HashSet values = new HashSet(conflictsMap.values()); - final HashSet expected = new HashSet(Arrays.asList(conflicts)); + final HashSet values = new HashSet<>(conflictsMap.values()); + final HashSet expected = new HashSet<>(Arrays.asList(conflicts)); assertEquals(expected.size(), values.size()); for (String value : values) { diff --git a/java/java-tests/testSrc/com/intellij/refactoring/PullUpTest.java b/java/java-tests/testSrc/com/intellij/refactoring/PullUpTest.java index a4060729835e..df5f293dc6d3 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/PullUpTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/PullUpTest.java @@ -189,7 +189,7 @@ public class PullUpTest extends LightRefactoringTestCase { private void doTest(final boolean checkMembersMovedCount, String conflictMessage, RefactoringTestUtil.MemberDescriptor... membersToFind) { - final MultiMap conflictsMap = new MultiMap(); + final MultiMap conflictsMap = new MultiMap<>(); configureByFile(BASE_PATH + getTestName(false) + ".java"); PsiElement elementAt = getFile().findElementAt(getEditor().getCaretModel().getOffset()); final PsiClass sourceClass = PsiTreeUtil.getParentOfType(elementAt, PsiClass.class); @@ -206,24 +206,17 @@ public class PullUpTest extends LightRefactoringTestCase { final MemberInfo[] infos = RefactoringTestUtil.findMembers(sourceClass, membersToFind); final int[] countMoved = {0}; - final MoveMemberListener listener = new MoveMemberListener() { - @Override - public void memberMoved(PsiClass aClass, PsiMember member) { - assertEquals(sourceClass, aClass); - countMoved[0]++; - } + final MoveMemberListener listener = (aClass, member) -> { + assertEquals(sourceClass, aClass); + countMoved[0]++; }; JavaRefactoringListenerManager.getInstance(getProject()).addMoveMembersListener(listener); final PsiDirectory targetDirectory = targetClass.getContainingFile().getContainingDirectory(); final PsiPackage targetPackage = targetDirectory != null ? JavaDirectoryService.getInstance().getPackage(targetDirectory) : null; conflictsMap.putAllValues( PullUpConflictsUtil - .checkConflicts(infos, sourceClass, targetClass, targetPackage, targetDirectory, new InterfaceContainmentVerifier() { - @Override - public boolean checkedInterfacesContain(PsiMethod psiMethod) { - return PullUpProcessor.checkedInterfacesContain(Arrays.asList(infos), psiMethod); - } - }) + .checkConflicts(infos, sourceClass, targetClass, targetPackage, targetDirectory, + psiMethod -> PullUpProcessor.checkedInterfacesContain(Arrays.asList(infos), psiMethod)) ); final PullUpProcessor helper = new PullUpProcessor(sourceClass, targetClass, infos, new DocCommentPolicy(DocCommentPolicy.ASIS)); helper.run(); diff --git a/java/java-tests/testSrc/com/intellij/refactoring/PushDownMultifileTest.java b/java/java-tests/testSrc/com/intellij/refactoring/PushDownMultifileTest.java index 1119144e887b..d046e5932cbb 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/PushDownMultifileTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/PushDownMultifileTest.java @@ -54,28 +54,25 @@ public class PushDownMultifileTest extends MultiFileTestCase { private void doTest(final boolean fail, final String sourceClassName, final String targetClassName) throws Exception { try { - doTest(new PerformAction() { - @Override - public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception { - final PsiClass srcClass = myJavaFacade.findClass(sourceClassName, GlobalSearchScope.allScope(myProject)); - assertTrue("Source class not found", srcClass != null); + doTest((rootDir, rootAfter) -> { + final PsiClass srcClass = myJavaFacade.findClass(sourceClassName, GlobalSearchScope.allScope(myProject)); + assertTrue("Source class not found", srcClass != null); - final PsiClass targetClass = myJavaFacade.findClass(targetClassName, GlobalSearchScope.allScope(myProject)); - assertTrue("Target class not found", targetClass != null); + final PsiClass targetClass = myJavaFacade.findClass(targetClassName, GlobalSearchScope.allScope(myProject)); + assertTrue("Target class not found", targetClass != null); - final PsiMethod[] methods = srcClass.getMethods(); - assertTrue("No methods found", methods.length > 0); - final MemberInfo[] membersToMove = new MemberInfo[1]; - final MemberInfo memberInfo = new MemberInfo(methods[0]); - memberInfo.setChecked(true); - membersToMove[0] = memberInfo; + final PsiMethod[] methods = srcClass.getMethods(); + assertTrue("No methods found", methods.length > 0); + final MemberInfo[] membersToMove = new MemberInfo[1]; + final MemberInfo memberInfo = new MemberInfo(methods[0]); + memberInfo.setChecked(true); + membersToMove[0] = memberInfo; - new PushDownProcessor(getProject(), membersToMove, srcClass, new DocCommentPolicy(DocCommentPolicy.ASIS)).run(); + new PushDownProcessor(getProject(), membersToMove, srcClass, new DocCommentPolicy(DocCommentPolicy.ASIS)).run(); - //LocalFileSystem.getInstance().refresh(false); - //FileDocumentManager.getInstance().saveAllDocuments(); - } + //LocalFileSystem.getInstance().refresh(false); + //FileDocumentManager.getInstance().saveAllDocuments(); }); } catch (BaseRefactoringProcessor.ConflictsInTestsException e) { @@ -110,28 +107,25 @@ public class PushDownMultifileTest extends MultiFileTestCase { public void testUsagesInXml() throws Exception { try { - doTest(new PerformAction() { - @Override - public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception { - final PsiClass srcClass = myJavaFacade.findClass("a.A", GlobalSearchScope.allScope(myProject)); - assertTrue("Source class not found", srcClass != null); + doTest((rootDir, rootAfter) -> { + final PsiClass srcClass = myJavaFacade.findClass("a.A", GlobalSearchScope.allScope(myProject)); + assertTrue("Source class not found", srcClass != null); - final PsiClass targetClass = myJavaFacade.findClass("b.B", GlobalSearchScope.allScope(myProject)); - assertTrue("Target class not found", targetClass != null); + final PsiClass targetClass = myJavaFacade.findClass("b.B", GlobalSearchScope.allScope(myProject)); + assertTrue("Target class not found", targetClass != null); - final PsiField[] fields = srcClass.getFields(); - assertTrue("No methods found", fields.length > 0); - final MemberInfo[] membersToMove = new MemberInfo[1]; - final MemberInfo memberInfo = new MemberInfo(fields[0]); - memberInfo.setChecked(true); - membersToMove[0] = memberInfo; + final PsiField[] fields = srcClass.getFields(); + assertTrue("No methods found", fields.length > 0); + final MemberInfo[] membersToMove = new MemberInfo[1]; + final MemberInfo memberInfo = new MemberInfo(fields[0]); + memberInfo.setChecked(true); + membersToMove[0] = memberInfo; - new PushDownProcessor(getProject(), membersToMove, srcClass, new DocCommentPolicy(DocCommentPolicy.ASIS)).run(); + new PushDownProcessor(getProject(), membersToMove, srcClass, new DocCommentPolicy(DocCommentPolicy.ASIS)).run(); - //LocalFileSystem.getInstance().refresh(false); - //FileDocumentManager.getInstance().saveAllDocuments(); - } + //LocalFileSystem.getInstance().refresh(false); + //FileDocumentManager.getInstance().saveAllDocuments(); }); } catch (BaseRefactoringProcessor.ConflictsInTestsException e) { diff --git a/java/java-tests/testSrc/com/intellij/refactoring/PushDownTest.java b/java/java-tests/testSrc/com/intellij/refactoring/PushDownTest.java index ed6cc2cbb1db..c828fffffd9f 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/PushDownTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/PushDownTest.java @@ -78,7 +78,7 @@ public class PushDownTest extends LightRefactoringTestCase { assert currentClass != null; - final List membersToMove = new ArrayList(); + final List membersToMove = new ArrayList<>(); final PsiField fieldByName = currentClass.findFieldByName("fieldToMove", false); if (fieldByName != null) { @@ -109,12 +109,7 @@ public class PushDownTest extends LightRefactoringTestCase { configureByFile(BASE_PATH + getTestName(false) + ".java"); PsiClass currentClass = JavaPsiFacade.getInstance(getProject()).findClass("Test", GlobalSearchScope.projectScope(getProject())); - MemberInfoStorage memberInfoStorage = new MemberInfoStorage(currentClass, new MemberInfo.Filter() { - @Override - public boolean includeMember(PsiMember element) { - return true; - } - }); + MemberInfoStorage memberInfoStorage = new MemberInfoStorage(currentClass, element -> true); List members = memberInfoStorage.getClassMemberInfos(currentClass); for (MemberInfo member : members) { member.setChecked(true); diff --git a/java/java-tests/testSrc/com/intellij/refactoring/RemoveMiddleManTest.java b/java/java-tests/testSrc/com/intellij/refactoring/RemoveMiddleManTest.java index 8966302e9898..e44d0051d445 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/RemoveMiddleManTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/RemoveMiddleManTest.java @@ -50,34 +50,31 @@ public class RemoveMiddleManTest extends MultiFileTestCase{ } private void doTest(final String conflict) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception { - PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.allScope(getProject())); + doTest((rootDir, rootAfter) -> { + PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.allScope(getProject())); - if (aClass == null) aClass = myJavaFacade.findClass("p.Test", GlobalSearchScope.allScope(getProject())); - assertNotNull("Class Test not found", aClass); + if (aClass == null) aClass = myJavaFacade.findClass("p.Test", GlobalSearchScope.allScope(getProject())); + assertNotNull("Class Test not found", aClass); - final PsiField field = aClass.findFieldByName("myField", false); - final Set methods = DelegationUtils.getDelegatingMethodsForField(field); - List infos = new ArrayList(); - for (PsiMethod method : methods) { - final MemberInfo info = new MemberInfo(method); - info.setChecked(true); - info.setToAbstract(true); - infos.add(info); - } - try { - RemoveMiddlemanProcessor processor = new RemoveMiddlemanProcessor(field, infos); - processor.run(); - LocalFileSystem.getInstance().refresh(false); - FileDocumentManager.getInstance().saveAllDocuments(); - if (conflict != null) fail("Conflict expected"); - } - catch (BaseRefactoringProcessor.ConflictsInTestsException e) { - if (conflict == null) throw e; - assertEquals(conflict, e.getMessage()); - } + final PsiField field = aClass.findFieldByName("myField", false); + final Set methods = DelegationUtils.getDelegatingMethodsForField(field); + List infos = new ArrayList<>(); + for (PsiMethod method : methods) { + final MemberInfo info = new MemberInfo(method); + info.setChecked(true); + info.setToAbstract(true); + infos.add(info); + } + try { + RemoveMiddlemanProcessor processor = new RemoveMiddlemanProcessor(field, infos); + processor.run(); + LocalFileSystem.getInstance().refresh(false); + FileDocumentManager.getInstance().saveAllDocuments(); + if (conflict != null) fail("Conflict expected"); + } + catch (BaseRefactoringProcessor.ConflictsInTestsException e) { + if (conflict == null) throw e; + assertEquals(conflict, e.getMessage()); } }); } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/RenameClassTest.java b/java/java-tests/testSrc/com/intellij/refactoring/RenameClassTest.java index 272b8d6e7918..dd50af9065a6 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/RenameClassTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/RenameClassTest.java @@ -75,20 +75,17 @@ public class RenameClassTest extends MultiFileTestCase { } private void doRenameClass(final String className, final String newName) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception { - PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.allScope(getProject())); - assertNotNull("Class XX not found", aClass); + doTest((rootDir, rootAfter) -> { + PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.allScope(getProject())); + assertNotNull("Class XX not found", aClass); - final RenameProcessor processor = new RenameProcessor(myProject, aClass, newName, true, true); - for (AutomaticRenamerFactory factory : Extensions.getExtensions(AutomaticRenamerFactory.EP_NAME)) { - processor.addRenamerFactory(factory); - } - processor.run(); - PsiDocumentManager.getInstance(myProject).commitAllDocuments(); - FileDocumentManager.getInstance().saveAllDocuments(); + final RenameProcessor processor = new RenameProcessor(myProject, aClass, newName, true, true); + for (AutomaticRenamerFactory factory : Extensions.getExtensions(AutomaticRenamerFactory.EP_NAME)) { + processor.addRenamerFactory(factory); } + processor.run(); + PsiDocumentManager.getInstance(myProject).commitAllDocuments(); + FileDocumentManager.getInstance().saveAllDocuments(); }); } @@ -101,12 +98,7 @@ public class RenameClassTest extends MultiFileTestCase { } private void doTest(@NonNls final String qClassName, @NonNls final String newName) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception { - RenameClassTest.this.performAction(qClassName, newName); - } - }); + doTest((rootDir, rootAfter) -> RenameClassTest.this.performAction(qClassName, newName)); } private void performAction(String qClassName, String newName) throws Exception { diff --git a/java/java-tests/testSrc/com/intellij/refactoring/RenameCollisionsTest.java b/java/java-tests/testSrc/com/intellij/refactoring/RenameCollisionsTest.java index 46c79e410e73..ff25480f187a 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/RenameCollisionsTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/RenameCollisionsTest.java @@ -283,7 +283,7 @@ public class RenameCollisionsTest extends LightRefactoringTestCase { PsiElement element = TargetElementUtil .findTargetElement(myEditor, TargetElementUtil.ELEMENT_NAME_ACCEPTED | TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED); assertNotNull(element); - final UsageInfo[] usageInfos = RenameUtil.findUsages(element, "newName", true, true, new HashMap()); + final UsageInfo[] usageInfos = RenameUtil.findUsages(element, "newName", true, true, new HashMap<>()); assertSize(1, usageInfos); for (UsageInfo usageInfo : usageInfos) { assertTrue(usageInfo instanceof MoveRenameUsageInfo); diff --git a/java/java-tests/testSrc/com/intellij/refactoring/RenameLocalTest.java b/java/java-tests/testSrc/com/intellij/refactoring/RenameLocalTest.java index c8c0f781582f..590c2e41f1d4 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/RenameLocalTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/RenameLocalTest.java @@ -62,7 +62,7 @@ public class RenameLocalTest extends LightRefactoringTestCase { PsiElement element = TargetElementUtil .findTargetElement(myEditor, TargetElementUtil.ELEMENT_NAME_ACCEPTED | TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED); assertNotNull(element); - final HashSet result = new HashSet(); + final HashSet result = new HashSet<>(); new JavaNameSuggestionProvider().getSuggestedNames(element, getFile(), result); assertTrue(result.toString(), result.contains("window")); } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/RenameMembersInplaceTest.java b/java/java-tests/testSrc/com/intellij/refactoring/RenameMembersInplaceTest.java index 937fee47025f..952b410d9661 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/RenameMembersInplaceTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/RenameMembersInplaceTest.java @@ -90,7 +90,7 @@ public class RenameMembersInplaceTest extends LightCodeInsightTestCase { final PsiElement element = TargetElementUtil.findTargetElement(myEditor, TargetElementUtil.getInstance().getAllAccepted()); assertNotNull(element); - final Set result = new LinkedHashSet(); + final Set result = new LinkedHashSet<>(); new JavaNameSuggestionProvider().getSuggestedNames(element, getFile(), result); CodeInsightTestUtil.doInlineRename(new MemberInplaceRenameHandler(), result.iterator().next(), getEditor(), element); diff --git a/java/java-tests/testSrc/com/intellij/refactoring/RenameMethodMultiTest.java b/java/java-tests/testSrc/com/intellij/refactoring/RenameMethodMultiTest.java index 0bd3fc0ff24c..3befcf254d24 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/RenameMethodMultiTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/RenameMethodMultiTest.java @@ -99,41 +99,35 @@ public class RenameMethodMultiTest extends MultiFileTestCase { } private void doTest(final String className, final String methodSignature, final String newName) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception { - final JavaPsiFacade manager = getJavaFacade(); - final PsiClass aClass = manager.findClass(className, GlobalSearchScope.moduleScope(myModule)); - assertNotNull(aClass); - final PsiMethod methodBySignature = aClass.findMethodBySignature(manager.getElementFactory().createMethodFromText( - methodSignature + "{}", null), false); - assertNotNull(methodBySignature); - final RenameProcessor renameProcessor = new RenameProcessor(myProject, methodBySignature, newName, false, false); - renameProcessor.run(); - FileDocumentManager.getInstance().saveAllDocuments(); - } + doTest((rootDir, rootAfter) -> { + final JavaPsiFacade manager = getJavaFacade(); + final PsiClass aClass = manager.findClass(className, GlobalSearchScope.moduleScope(myModule)); + assertNotNull(aClass); + final PsiMethod methodBySignature = aClass.findMethodBySignature(manager.getElementFactory().createMethodFromText( + methodSignature + "{}", null), false); + assertNotNull(methodBySignature); + final RenameProcessor renameProcessor = new RenameProcessor(myProject, methodBySignature, newName, false, false); + renameProcessor.run(); + FileDocumentManager.getInstance().saveAllDocuments(); }); } private void doAutomaticRenameMethod(final String className, final String methodSignature, final String newName) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception { - final JavaPsiFacade manager = getJavaFacade(); - final PsiClass aClass = manager.findClass(className, GlobalSearchScope.moduleScope(myModule)); - assertNotNull(aClass); - final PsiMethod methodBySignature = aClass.findMethodBySignature(manager.getElementFactory().createMethodFromText( - methodSignature + "{}", null), false); - assertNotNull(methodBySignature); + doTest((rootDir, rootAfter) -> { + final JavaPsiFacade manager = getJavaFacade(); + final PsiClass aClass = manager.findClass(className, GlobalSearchScope.moduleScope(myModule)); + assertNotNull(aClass); + final PsiMethod methodBySignature = aClass.findMethodBySignature(manager.getElementFactory().createMethodFromText( + methodSignature + "{}", null), false); + assertNotNull(methodBySignature); - final RenameProcessor processor = new RenameProcessor(myProject, methodBySignature, newName, false, false); - for (AutomaticRenamerFactory factory : Extensions.getExtensions(AutomaticRenamerFactory.EP_NAME)) { - processor.addRenamerFactory(factory); - } - processor.run(); - PsiDocumentManager.getInstance(myProject).commitAllDocuments(); - FileDocumentManager.getInstance().saveAllDocuments(); + final RenameProcessor processor = new RenameProcessor(myProject, methodBySignature, newName, false, false); + for (AutomaticRenamerFactory factory : Extensions.getExtensions(AutomaticRenamerFactory.EP_NAME)) { + processor.addRenamerFactory(factory); } + processor.run(); + PsiDocumentManager.getInstance(myProject).commitAllDocuments(); + FileDocumentManager.getInstance().saveAllDocuments(); }); } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/ReplaceConstructorWithBuilderTest.java b/java/java-tests/testSrc/com/intellij/refactoring/ReplaceConstructorWithBuilderTest.java index 8ecd54441f6a..8c4be9cd0ec8 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/ReplaceConstructorWithBuilderTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/ReplaceConstructorWithBuilderTest.java @@ -62,13 +62,13 @@ public class ReplaceConstructorWithBuilderTest extends MultiFileTestCase { } public void testConstructorChain() throws Exception { - final HashMap defaults = new HashMap(); + final HashMap defaults = new HashMap<>(); defaults.put("i", "2"); doTest(true, defaults); } public void testConstructorChainWithoutDefaults() throws Exception { - final HashMap defaults = new HashMap(); + final HashMap defaults = new HashMap<>(); defaults.put("i", "2"); defaults.put("j", null); doTest(true, defaults); @@ -102,39 +102,36 @@ public class ReplaceConstructorWithBuilderTest extends MultiFileTestCase { final Map expectedDefaults, final String conflicts, final String packageName) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception { - final PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(getProject())); - assertNotNull("Class Test not found", aClass); + doTest((rootDir, rootAfter) -> { + final PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(getProject())); + assertNotNull("Class Test not found", aClass); - final LinkedHashMap map = new LinkedHashMap(); - final PsiMethod[] constructors = aClass.getConstructors(); - for (PsiMethod constructor : constructors) { - ParameterData.createFromConstructor(constructor, "set", map); - } - if (expectedDefaults != null) { - for (Map.Entry entry : expectedDefaults.entrySet()) { - final ParameterData parameterData = map.get(entry.getKey()); - assertNotNull(parameterData); - assertEquals(entry.getValue(), parameterData.getDefaultValue()); - } - } - try { - new ReplaceConstructorWithBuilderProcessor(getProject(), constructors, map, "Builder", packageName, null, createNewBuilderClass).run(); - if (conflicts != null) { - fail("Conflicts were not detected:" + conflicts); - } - } - catch (BaseRefactoringProcessor.ConflictsInTestsException e) { - - if (conflicts == null) { - fail("Conflict detected:" + e.getMessage()); - } - } - LocalFileSystem.getInstance().refresh(false); - FileDocumentManager.getInstance().saveAllDocuments(); + final LinkedHashMap map = new LinkedHashMap<>(); + final PsiMethod[] constructors = aClass.getConstructors(); + for (PsiMethod constructor : constructors) { + ParameterData.createFromConstructor(constructor, "set", map); } + if (expectedDefaults != null) { + for (Map.Entry entry : expectedDefaults.entrySet()) { + final ParameterData parameterData = map.get(entry.getKey()); + assertNotNull(parameterData); + assertEquals(entry.getValue(), parameterData.getDefaultValue()); + } + } + try { + new ReplaceConstructorWithBuilderProcessor(getProject(), constructors, map, "Builder", packageName, null, createNewBuilderClass).run(); + if (conflicts != null) { + fail("Conflicts were not detected:" + conflicts); + } + } + catch (BaseRefactoringProcessor.ConflictsInTestsException e) { + + if (conflicts == null) { + fail("Conflict detected:" + e.getMessage()); + } + } + LocalFileSystem.getInstance().refresh(false); + FileDocumentManager.getInstance().saveAllDocuments(); }); } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/SafeDeleteTest.java b/java/java-tests/testSrc/com/intellij/refactoring/SafeDeleteTest.java index 98a72b4e989e..f9a4701a02c6 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/SafeDeleteTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/SafeDeleteTest.java @@ -278,11 +278,8 @@ public class SafeDeleteTest extends MultiFileTestCase { } private void doTest(@NonNls final String qClassName) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception { - SafeDeleteTest.this.performAction(qClassName); - } + doTest((rootDir, rootAfter) -> { + SafeDeleteTest.this.performAction(qClassName); }); } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/TurnRefsToSuperTest.java b/java/java-tests/testSrc/com/intellij/refactoring/TurnRefsToSuperTest.java index 7fef2e73b6cc..017f5a7e1a72 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/TurnRefsToSuperTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/TurnRefsToSuperTest.java @@ -67,11 +67,8 @@ public class TurnRefsToSuperTest extends MultiFileTestCase { //public void testForEach2() throws Exception { doTest("Test.MyIterableImpl", "Test.MyIterable", false); } private void doTest(@NonNls final String className, @NonNls final String superClassName, final boolean replaceInstanceOf) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception { - TurnRefsToSuperTest.this.performAction(className, superClassName, replaceInstanceOf); - } + doTest((rootDir, rootAfter) -> { + TurnRefsToSuperTest.this.performAction(className, superClassName, replaceInstanceOf); }, true); } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/TypeCookTest.java b/java/java-tests/testSrc/com/intellij/refactoring/TypeCookTest.java index 5cfefaa3a065..861c5ef62b1d 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/TypeCookTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/TypeCookTest.java @@ -672,12 +672,7 @@ public class TypeCookTest extends MultiFileTestCase { } public void start(final boolean cookObjects) throws Exception { - doTest(new PerformAction() { - @Override - public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception { - TypeCookTest.this.performAction("Test", rootDir.getName(), cookObjects); - } - }); + doTest((rootDir, rootAfter) -> TypeCookTest.this.performAction("Test", rootDir.getName(), cookObjects)); } private void performAction(String className, String rootDir, final boolean cookObjects) throws Exception { diff --git a/java/java-tests/testSrc/com/intellij/refactoring/WrapReturnValueTest.java b/java/java-tests/testSrc/com/intellij/refactoring/WrapReturnValueTest.java index a6e362073bb9..c189f9bb850a 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/WrapReturnValueTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/WrapReturnValueTest.java @@ -70,18 +70,15 @@ public class WrapReturnValueTest extends MultiFileTestCase { private void doTest(final boolean existing, String exceptionMessage, final boolean createInnerClass) { try { - doTest(new PerformAction() { - @Override - public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) { - PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(getProject())); - assertNotNull("Class Test not found", aClass); - PsiMethod method = aClass.findMethodsByName("foo", false)[0]; - String wrapperClassName = "Wrapper"; - PsiClass wrapperClass = myJavaFacade.findClass(wrapperClassName, GlobalSearchScope.projectScope(getProject())); - assertTrue(!existing || wrapperClass != null); - PsiField delegateField = existing ? wrapperClass.findFieldByName("myField", false) : null; - new WrapReturnValueProcessor(wrapperClassName, "", null, method, existing, createInnerClass, delegateField).run(); - } + doTest((rootDir, rootAfter) -> { + PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(getProject())); + assertNotNull("Class Test not found", aClass); + PsiMethod method = aClass.findMethodsByName("foo", false)[0]; + String wrapperClassName = "Wrapper"; + PsiClass wrapperClass = myJavaFacade.findClass(wrapperClassName, GlobalSearchScope.projectScope(getProject())); + assertTrue(!existing || wrapperClass != null); + PsiField delegateField = existing ? wrapperClass.findFieldByName("myField", false) : null; + new WrapReturnValueProcessor(wrapperClassName, "", null, method, existing, createInnerClass, delegateField).run(); }); } catch (BaseRefactoringProcessor.ConflictsInTestsException e) { diff --git a/java/java-tests/testSrc/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureTest.java b/java/java-tests/testSrc/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureTest.java index 9bc39948badf..3a2ee0b0e318 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureTest.java @@ -22,120 +22,65 @@ public class ChangeClassSignatureTest extends LightRefactoringTestCase { } public void testNoParams() throws Exception { - doTest(new GenParams() { - @Override - public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException { - return new TypeParameterInfo[]{ - new TypeParameterInfo(aClass, "T", "java.lang.String") - }; - } + doTest(aClass -> new TypeParameterInfo[]{ + new TypeParameterInfo(aClass, "T", "java.lang.String") }); } public void testInstanceOf() throws Exception { - doTest(new GenParams() { - @Override - public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException { - return new TypeParameterInfo[]{ - new TypeParameterInfo(aClass, "T", "java.lang.String") - }; - } + doTest(aClass -> new TypeParameterInfo[]{ + new TypeParameterInfo(aClass, "T", "java.lang.String") }); } public void testSubstituteParamInsideClass() throws Exception { - doTest(new GenParams() { - @Override - public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException { - return new TypeParameterInfo[0]; - } - }); + doTest(aClass -> new TypeParameterInfo[0]); } public void testRemoveAllParams() throws Exception { - doTest(new GenParams() { - @Override - public TypeParameterInfo[] gen(PsiClass aClass) { - return new TypeParameterInfo[0]; - } - }); + doTest(aClass -> new TypeParameterInfo[0]); } public void testReorderParams() throws Exception { - doTest(new GenParams() { - @Override - public TypeParameterInfo[] gen(PsiClass aClass) { - return new TypeParameterInfo[] { - new TypeParameterInfo(1), - new TypeParameterInfo(0) - }; - } + doTest(aClass -> new TypeParameterInfo[] { + new TypeParameterInfo(1), + new TypeParameterInfo(0) }); } public void testAddParam() throws Exception { - doTest(new GenParams() { - @Override - public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException { - return new TypeParameterInfo[] { - new TypeParameterInfo(0), - new TypeParameterInfo(aClass, "E", "L") - }; - } + doTest(aClass -> new TypeParameterInfo[] { + new TypeParameterInfo(0), + new TypeParameterInfo(aClass, "E", "L") }); } public void testAddParamDiamond() throws Exception { - doTest(new GenParams() { - @Override - public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException { - return new TypeParameterInfo[] { - new TypeParameterInfo(0), - new TypeParameterInfo(aClass, "I", "Integer") - }; - } + doTest(aClass -> new TypeParameterInfo[] { + new TypeParameterInfo(0), + new TypeParameterInfo(aClass, "I", "Integer") }); } public void testAddOneFirst() throws Exception { - doTest(new GenParams() { - @Override - public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException { - return new TypeParameterInfo[]{ - new TypeParameterInfo(aClass, "T", "java.lang.String") - }; - } + doTest(aClass -> new TypeParameterInfo[]{ + new TypeParameterInfo(aClass, "T", "java.lang.String") }, "Zero.java", "OneString.java"); } public void testAddManyFirst() throws Exception { - doTest(new GenParams() { - @Override - public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException { - return new TypeParameterInfo[]{ - new TypeParameterInfo(aClass, "U", "SubjectFace"), - new TypeParameterInfo(aClass, "V", "java.util.Set") - }; - } + doTest(aClass -> new TypeParameterInfo[]{ + new TypeParameterInfo(aClass, "U", "SubjectFace"), + new TypeParameterInfo(aClass, "V", "java.util.Set") }, "Zero.java", "TwoSubjectFaceSetObject.java"); } public void testRemoveOneLast() throws Exception { - doTest(new GenParams() { - @Override - public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException { - return new TypeParameterInfo[0]; - } - }, "OneString.java", "Zero.java"); + doTest(aClass -> new TypeParameterInfo[0], "OneString.java", "Zero.java"); } public void testRemoveManyLast() throws Exception { - doTest(new GenParams() { - @Override - public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException { - return new TypeParameterInfo[0]; - } - }, "TwoSubjectFaceSetObject.java", "Zero.java"); + doTest(aClass -> new TypeParameterInfo[0], "TwoSubjectFaceSetObject.java", "Zero.java"); } private void doTest(GenParams gen) throws Exception { diff --git a/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineLibraryMethodTest.java b/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineLibraryMethodTest.java index 541d75d42109..65cd549ecd3f 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineLibraryMethodTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineLibraryMethodTest.java @@ -51,14 +51,12 @@ public class InlineLibraryMethodTest extends RefactoringTestCase { PsiClass fileClass = getJavaFacade().findClass("mycompany.File"); assertNotNull(fileClass); final PsiFile file = fileClass.getContainingFile(); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - public void run() { - try { - ((VirtualFileSystemEntry)file.getVirtualFile()).setWritable(false); - } - catch (IOException e) { - throw new RuntimeException(e); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + try { + ((VirtualFileSystemEntry)file.getVirtualFile()).setWritable(false); + } + catch (IOException e) { + throw new RuntimeException(e); } }); diff --git a/java/java-tests/testSrc/com/intellij/refactoring/migration/MigrationTest.java b/java/java-tests/testSrc/com/intellij/refactoring/migration/MigrationTest.java index 91349d6f3fec..76488a4f7780 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/migration/MigrationTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/migration/MigrationTest.java @@ -57,12 +57,9 @@ public class MigrationTest extends MultiFileTestCase { } private MultiFileTestCase.PerformAction createAction(final MigrationMap migrationMap) { - return new MultiFileTestCase.PerformAction() { - @Override - public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception { - new MigrationProcessor(myProject, migrationMap).run(); - FileDocumentManager.getInstance().saveAllDocuments(); - } + return (rootDir, rootAfter) -> { + new MigrationProcessor(myProject, migrationMap).run(); + FileDocumentManager.getInstance().saveAllDocuments(); }; } diff --git a/java/testFramework/src/com/intellij/debugger/ExecutionWithDebuggerToolsTestCase.java b/java/testFramework/src/com/intellij/debugger/ExecutionWithDebuggerToolsTestCase.java index 615ed5c65193..e1ab9ff4e3cf 100644 --- a/java/testFramework/src/com/intellij/debugger/ExecutionWithDebuggerToolsTestCase.java +++ b/java/testFramework/src/com/intellij/debugger/ExecutionWithDebuggerToolsTestCase.java @@ -138,6 +138,7 @@ public abstract class ExecutionWithDebuggerToolsTestCase extends ExecutionTestCa } catch (AssertionError e) { addException(e); + paused(suspendContext); } if (myScriptRunnables.isEmpty()) { diff --git a/lib/serviceMessages.jar b/lib/serviceMessages.jar index 3f8884a5888f..d76027403d53 100644 Binary files a/lib/serviceMessages.jar and b/lib/serviceMessages.jar differ diff --git a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/FileStatusMap.java b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/FileStatusMap.java index f25ee9a6b264..2b96628fa861 100644 --- a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/FileStatusMap.java +++ b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/FileStatusMap.java @@ -351,6 +351,11 @@ public class FileStatusMap implements Disposable { public void putUserData(@NotNull Key key, @Nullable T value) { throw new UnsupportedOperationException(); } + + @Override + public String toString() { + return "WHOLE_FILE"; + } }; // logging diff --git a/platform/annotations/common/src/org/intellij/lang/annotations/Flow.java b/platform/annotations/common/src/org/intellij/lang/annotations/Flow.java index 1854d4c2297e..537a3cb3287a 100644 --- a/platform/annotations/common/src/org/intellij/lang/annotations/Flow.java +++ b/platform/annotations/common/src/org/intellij/lang/annotations/Flow.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * 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. @@ -60,7 +60,7 @@ public @interface Flow { * * */ - String source() default org.intellij.lang.annotations.Flow.DEFAULT_SOURCE; + String source() default Flow.DEFAULT_SOURCE; String DEFAULT_SOURCE = "The method argument (if parameter was annotated) or this container (if instance method was annotated)"; String THIS_SOURCE = "this"; @@ -109,7 +109,7 @@ public @interface Flow { * * */ - String target() default org.intellij.lang.annotations.Flow.DEFAULT_TARGET; + String target() default Flow.DEFAULT_TARGET; String DEFAULT_TARGET = "This container (if the parameter was annotated) or the return value (if instance method was annotated)"; String RETURN_METHOD_TARGET = "The return value of this method"; String THIS_TARGET = "this"; diff --git a/platform/built-in-server/src/org/jetbrains/builtInWebServer/BuiltInWebBrowserUrlProvider.java b/platform/built-in-server/src/org/jetbrains/builtInWebServer/BuiltInWebBrowserUrlProvider.java index b79781923d04..6c1163cb27bb 100644 --- a/platform/built-in-server/src/org/jetbrains/builtInWebServer/BuiltInWebBrowserUrlProvider.java +++ b/platform/built-in-server/src/org/jetbrains/builtInWebServer/BuiltInWebBrowserUrlProvider.java @@ -59,7 +59,7 @@ public class BuiltInWebBrowserUrlProvider extends WebBrowserUrlProvider implemen } public static boolean compareAuthority(@Nullable String currentAuthority) { - if (currentAuthority == null) { + if (StringUtil.isEmpty(currentAuthority)) { return false; } diff --git a/platform/core-api/src/com/intellij/openapi/application/ApplicationInfo.java b/platform/core-api/src/com/intellij/openapi/application/ApplicationInfo.java index 1bc67e24bceb..9a289c40ee9b 100644 --- a/platform/core-api/src/com/intellij/openapi/application/ApplicationInfo.java +++ b/platform/core-api/src/com/intellij/openapi/application/ApplicationInfo.java @@ -35,6 +35,7 @@ public abstract class ApplicationInfo { public abstract String getCompanyURL(); public abstract String getThirdPartySoftwareURL(); public abstract String getJetbrainsTvUrl(); + public abstract String getEvalLicenseUrl(); public abstract Rectangle getAboutLogoRect(); public abstract boolean hasHelp(); diff --git a/platform/core-api/src/com/intellij/openapi/vfs/VfsUtilCore.java b/platform/core-api/src/com/intellij/openapi/vfs/VfsUtilCore.java index 54dc3d9b73cc..0567e18f1153 100644 --- a/platform/core-api/src/com/intellij/openapi/vfs/VfsUtilCore.java +++ b/platform/core-api/src/com/intellij/openapi/vfs/VfsUtilCore.java @@ -418,7 +418,7 @@ public class VfsUtilCore { return prefix + ":///" + suffix; } } - else if (url.charAt(index + 3) == '/' && SystemInfoRt.isWindows && url.regionMatches(0, StandardFileSystems.FILE_PROTOCOL_PREFIX, 0, StandardFileSystems.FILE_PROTOCOL_PREFIX.length())) { + else if (SystemInfoRt.isWindows && (index + 3) < url.length() && url.charAt(index + 3) == '/' && url.regionMatches(0, StandardFileSystems.FILE_PROTOCOL_PREFIX, 0, StandardFileSystems.FILE_PROTOCOL_PREFIX.length())) { // file:///C:/test/file.js -> file://C:/test/file.js for (int i = index + 4; i < url.length(); i++) { char c = url.charAt(i); diff --git a/platform/core-impl/src/com/intellij/openapi/application/impl/ApplicationInfoImpl.java b/platform/core-impl/src/com/intellij/openapi/application/impl/ApplicationInfoImpl.java index 86cc7a21d40a..e408b2dc5676 100644 --- a/platform/core-impl/src/com/intellij/openapi/application/impl/ApplicationInfoImpl.java +++ b/platform/core-impl/src/com/intellij/openapi/application/impl/ApplicationInfoImpl.java @@ -100,6 +100,7 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern private String myStatisticsServiceKey; private String myThirdPartySoftwareUrl; private String myJetbrainsTvUrl; + private String myEvalLicenseUrl = "https://www.jetbrains.com/company/useterms.html"; private Rectangle myAboutLogoRect; @@ -172,6 +173,8 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern private static final String ELEMENT_JB_TV = "jetbrains-tv"; private static final String CUSTOMIZE_IDE_WIZARD_STEPS = "customize-ide-wizard"; private static final String STEPS_PROVIDER = "provider"; + private static final String ELEMENT_EVALUATION = "evaluation"; + private static final String ATTRIBUTE_EVAL_LICENSE_URL = "license-url"; private static final String DEFAULT_PLUGINS_HOST = "http://plugins.jetbrains.com"; @@ -488,6 +491,11 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern return myJetbrainsTvUrl; } + @Override + public String getEvalLicenseUrl() { + return myEvalLicenseUrl; + } + @Override public Rectangle getAboutLogoRect() { return myAboutLogoRect; @@ -764,6 +772,15 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern if (tvElement != null) { myJetbrainsTvUrl = tvElement.getAttributeValue(ATTRIBUTE_URL); } + + Element evaluationElement = parentNode.getChild(ELEMENT_EVALUATION); + if (evaluationElement != null) { + final String url = evaluationElement.getAttributeValue(ATTRIBUTE_EVAL_LICENSE_URL); + if (url != null && !url.isEmpty()) { + myEvalLicenseUrl = url; + } + } + } private static void setBuildNumber(String apiVersion, String buildNumber) { diff --git a/platform/core-impl/src/com/intellij/openapi/progress/impl/CoreProgressManager.java b/platform/core-impl/src/com/intellij/openapi/progress/impl/CoreProgressManager.java index f32466655ba6..969b9dc7d360 100644 --- a/platform/core-impl/src/com/intellij/openapi/progress/impl/CoreProgressManager.java +++ b/platform/core-impl/src/com/intellij/openapi/progress/impl/CoreProgressManager.java @@ -64,7 +64,7 @@ public class CoreProgressManager extends ProgressManager implements Disposable { private static volatile boolean thereIsProcessUnderCanceledIndicator; // active (i.e. which have executeProcessUnderProgress() method running) indicators which are not inherited from StandardProgressIndicator. - // for them an extra processing thread (see myCheckCancelledFuture) has to be run to call their non-standard checkCanceled() method + // for them an extra processing thread (see myCheckCancelledFuture) has to be run to call their non-standard checkCanceled() method periodically. private static final Collection nonStandardIndicators = ConcurrentHashMultiset.create(); public CoreProgressManager() { diff --git a/platform/core-impl/src/com/intellij/psi/SingleRootFileViewProvider.java b/platform/core-impl/src/com/intellij/psi/SingleRootFileViewProvider.java index 2752d06b31d4..f4eca37a558e 100644 --- a/platform/core-impl/src/com/intellij/psi/SingleRootFileViewProvider.java +++ b/platform/core-impl/src/com/intellij/psi/SingleRootFileViewProvider.java @@ -241,8 +241,8 @@ public class SingleRootFileViewProvider extends UserDataHolderBase implements Fi @NotNull public FileElement[] getKnownTreeRoots() { PsiFile psiFile = getCachedPsi(myBaseLanguage); - if (psiFile == null || !(psiFile instanceof PsiFileImpl)) return new FileElement[0]; - if (((PsiFileImpl)psiFile).getTreeElement() == null) return new FileElement[0]; + if (!(psiFile instanceof PsiFileImpl)) return FileElement.EMPTY_ARRAY; + if (((PsiFileImpl)psiFile).getTreeElement() == null) return FileElement.EMPTY_ARRAY; return new FileElement[]{(FileElement)psiFile.getNode()}; } @@ -528,9 +528,7 @@ public class SingleRootFileViewProvider extends UserDataHolderBase implements Fi if (document == null) { return LoadTextUtil.loadText(virtualFile); } - else { - return getLastCommittedText(document); - } + return getLastCommittedText(document); } @Override @@ -546,9 +544,7 @@ public class SingleRootFileViewProvider extends UserDataHolderBase implements Fi if (document == null) { return virtualFile.getModificationStamp(); } - else { - return getLastCommittedStamp(document); - } + return getLastCommittedStamp(document); } @NonNls @@ -567,7 +563,7 @@ public class SingleRootFileViewProvider extends UserDataHolderBase implements Fi private class PsiFileContent implements Content { private final PsiFileImpl myFile; - private volatile String myContent = null; + private volatile String myContent; private final long myModificationStamp; @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") diff --git a/platform/core-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerManagerImpl.java b/platform/core-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerManagerImpl.java index b47aaac7a786..eea7b5c6e356 100644 --- a/platform/core-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerManagerImpl.java +++ b/platform/core-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerManagerImpl.java @@ -29,7 +29,7 @@ import com.intellij.psi.impl.PsiManagerEx; import com.intellij.psi.impl.source.tree.MarkersHolderFileViewProvider; import com.intellij.psi.util.PsiUtilCore; import com.intellij.reference.SoftReference; -import com.intellij.util.containers.ContainerUtil; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; @@ -37,10 +37,6 @@ import org.jetbrains.annotations.TestOnly; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Set; public class SmartPointerManagerImpl extends SmartPointerManager { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.smartPointers.SmartPointerManagerImpl"); @@ -54,7 +50,7 @@ public class SmartPointerManagerImpl extends SmartPointerManager { }); private final Project myProject; - private final Key> POINTERS_KEY; + private final Key POINTERS_KEY; private final Key POINTERS_ARE_FASTENED_KEY; public SmartPointerManagerImpl(Project project) { @@ -68,7 +64,7 @@ public class SmartPointerManagerImpl extends SmartPointerManager { PointerReference reference = (PointerReference)ourQueue.poll(); if (reference == null) break; synchronized (lock) { - Set pointers = reference.file.getUserData(reference.key); + FilePointersList pointers = reference.file.getUserData(reference.key); if (pointers != null) { pointers.remove(reference); if (pointers.isEmpty()) { @@ -83,13 +79,15 @@ public class SmartPointerManagerImpl extends SmartPointerManager { ApplicationManager.getApplication().assertIsDispatchThread(); processQueue(); synchronized (lock) { - List pointers = getStrongPointers(file); - if (pointers.isEmpty()) return; - if (getAndFasten(file)) return; - - for (SmartPointerEx pointer : pointers) { - pointer.fastenBelt(offset, cachedRangeMarkers); + FilePointersList pointers = getPointers(file); + if (pointers != null && !pointers.isEmpty()) { + for (PointerReference ref : pointers.references) { + SmartPointerEx pointer = SoftReference.dereference(ref); + if (pointer != null) { + pointer.fastenBelt(offset, cachedRangeMarkers); + } + } } PsiFile psiFile = ((PsiManagerEx)PsiManager.getInstance(myProject)).getFileManager().getCachedPsiFile(file); @@ -124,13 +122,16 @@ public class SmartPointerManagerImpl extends SmartPointerManager { ApplicationManager.getApplication().assertIsDispatchThread(); processQueue(); synchronized (lock) { - List pointers = getStrongPointers(file); - if (pointers.isEmpty()) return; + FilePointersList pointers = getPointers(file); + if (pointers == null || pointers.isEmpty()) return; if (!getAndUnfasten(file)) return; - for (SmartPointerEx pointer : pointers) { - pointer.unfastenBelt(offset); + for (PointerReference ref : pointers.references) { + SmartPointerEx pointer = SoftReference.dereference(ref); + if (pointer != null) { + pointer.unfastenBelt(offset); + } } PsiFile psiFile = ((PsiManagerEx)PsiManager.getInstance(myProject)).getFileManager().getCachedPsiFile(file); @@ -211,9 +212,9 @@ public class SmartPointerManagerImpl extends SmartPointerManager { private void initPointer(@NotNull SmartPsiElementPointerImpl pointer, @NotNull VirtualFile containingFile) { synchronized (lock) { - Set pointers = getPointers(containingFile); + FilePointersList pointers = getPointers(containingFile); if (pointers == null) { - pointers = ContainerUtil.newTroveSet(); // we synchronise access anyway + pointers = new FilePointersList(); // we synchronise access anyway containingFile.putUserData(POINTERS_KEY, pointers); } if (areBeltsFastened(containingFile)) { @@ -244,45 +245,29 @@ public class SmartPointerManagerImpl extends SmartPointerManager { if (containingFile == null) return false; VirtualFile vFile = containingFile.getViewProvider().getVirtualFile(); - Set pointers = getPointers(vFile); + FilePointersList pointers = getPointers(vFile); if (pointers == null) return false; - - - for (Iterator iterator = pointers.iterator(); iterator.hasNext(); ) { - if (pointer == iterator.next().get()) { - iterator.remove(); - if (pointers.isEmpty()) { - vFile.putUserData(POINTERS_KEY, null); - } - return true; - } + boolean result = pointers.remove(pointer); + if (pointers.isEmpty()) { + vFile.putUserData(POINTERS_KEY, null); } + return result; } } return false; } @Nullable - private Set getPointers(@NotNull VirtualFile containingFile) { + private FilePointersList getPointers(@NotNull VirtualFile containingFile) { return containingFile.getUserData(POINTERS_KEY); } - @NotNull - private List getStrongPointers(@NotNull VirtualFile containingFile) { - Set refs = getPointers(containingFile); - if (refs == null) return Collections.emptyList(); - - List result = ContainerUtil.newArrayList(); - for (PointerReference reference : refs) { - ContainerUtil.addIfNotNull(result, reference.get()); - } - return result; - } - @TestOnly public int getPointersNumber(@NotNull PsiFile containingFile) { synchronized (lock) { - return getStrongPointers(containingFile.getViewProvider().getVirtualFile()).size(); + VirtualFile file = containingFile.getViewProvider().getVirtualFile(); + FilePointersList pointers = getPointers(file); + return pointers == null ? 0 : pointers.size; } } @@ -306,17 +291,66 @@ public class SmartPointerManagerImpl extends SmartPointerManager { } private static class PointerReference extends WeakReference { - private final VirtualFile file; - private final Key> key; + @NotNull private final VirtualFile file; + @NotNull private final Key key; - public PointerReference(SmartPointerEx pointer, - VirtualFile containingFile, - ReferenceQueue queue, - Key> key) { + private PointerReference(@NotNull SmartPointerEx pointer, + @NotNull VirtualFile containingFile, + @NotNull ReferenceQueue queue, + @NotNull Key key) { super(pointer, queue); file = containingFile; this.key = key; } } + private static class FilePointersList { + private int nextAvailableIndex; + private int size; + private PointerReference[] references = new PointerReference[10]; + + private void add(@NotNull PointerReference reference) { + if (nextAvailableIndex >= references.length || nextAvailableIndex > size*2) { // overflow or too many dead refs + int newCapacity = nextAvailableIndex >= references.length ? references.length * 3/2 +1 : size * 3/2+1; + PointerReference[] newReferences = new PointerReference[newCapacity]; + + int o = 0; + for (PointerReference oldRef : references) { + if (SoftReference.dereference(oldRef) != null) { + newReferences[o++] = oldRef; + } + } + references = newReferences; + size = nextAvailableIndex = o; + } + references[nextAvailableIndex++] = reference; + size++; + } + + private void remove(@NotNull PointerReference reference) { + int index = ArrayUtil.indexOf(references, reference); + if (index != -1) { + references[index] = null; + size--; + } + } + + private boolean remove(@NotNull SmartPsiElementPointer smartPointer) { + boolean result = false; + for (int i = 0; i < references.length; i++) { + PointerReference reference = references[i]; + if (reference != null && reference.get() == smartPointer) { + references[i] = null; + result = true; + break; + } + } + size--; + return result; + } + + private boolean isEmpty() { + return size == 0; + } + } } diff --git a/platform/core-impl/src/com/intellij/psi/impl/source/tree/FileElement.java b/platform/core-impl/src/com/intellij/psi/impl/source/tree/FileElement.java index 894d0295870c..ff2a0f8cef15 100644 --- a/platform/core-impl/src/com/intellij/psi/impl/source/tree/FileElement.java +++ b/platform/core-impl/src/com/intellij/psi/impl/source/tree/FileElement.java @@ -30,6 +30,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class FileElement extends LazyParseableElement implements FileASTNode, Getter { + public static final FileElement[] EMPTY_ARRAY = new FileElement[0]; private volatile CharTable myCharTable = new CharTableImpl(); private volatile boolean myDetached; diff --git a/platform/diff-impl/src/com/intellij/diff/util/DiffUtil.java b/platform/diff-impl/src/com/intellij/diff/util/DiffUtil.java index d634a57b7612..709db25a0160 100644 --- a/platform/diff-impl/src/com/intellij/diff/util/DiffUtil.java +++ b/platform/diff-impl/src/com/intellij/diff/util/DiffUtil.java @@ -52,7 +52,6 @@ import com.intellij.openapi.editor.ex.EditorMarkupModel; import com.intellij.openapi.editor.ex.util.EmptyEditorHighlighter; import com.intellij.openapi.editor.highlighter.EditorHighlighter; import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory; -import com.intellij.openapi.editor.impl.softwrap.SoftWrapAppliancePlaces; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.progress.ProgressIndicator; @@ -165,7 +164,6 @@ public class DiffUtil { EditorEx editor = (EditorEx)(isViewer ? factory.createViewer(document, project) : factory.createEditor(document, project)); editor.putUserData(DiffManagerImpl.EDITOR_IS_DIFF_KEY, Boolean.TRUE); - editor.setSoftWrapAppliancePlace(SoftWrapAppliancePlaces.VCS_DIFF); editor.getSettings().setLineNumbersShown(true); ((EditorMarkupModel)editor.getMarkupModel()).setErrorStripeVisible(true); diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java index f39878760a89..ce0511dcf3d3 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java @@ -130,7 +130,7 @@ public class InspectionResultsView extends JPanel implements Disposable, Occuren myBrowser = new Browser(this); - mySplitter = new Splitter(false, AnalysisUIOptions.getInstance(myProject).SPLITTER_PROPORTION); + mySplitter = new OnePixelSplitter(false, AnalysisUIOptions.getInstance(myProject).SPLITTER_PROPORTION); mySplitter.setFirstComponent(ScrollPaneFactory.createScrollPane(myTree, SideBorder.LEFT | SideBorder.RIGHT)); mySplitter.setSecondComponent(myBrowser); diff --git a/platform/lang-impl/src/com/intellij/execution/impl/ConfigurationSettingsEditorWrapper.java b/platform/lang-impl/src/com/intellij/execution/impl/ConfigurationSettingsEditorWrapper.java index a1cb7b8c23f3..9d097a5dabfb 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/ConfigurationSettingsEditorWrapper.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/ConfigurationSettingsEditorWrapper.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.intellij.execution.impl; import com.intellij.execution.BeforeRunTask; @@ -44,8 +43,9 @@ import java.util.List; */ public class ConfigurationSettingsEditorWrapper extends SettingsEditor implements BeforeRunStepsPanel.StepsBeforeRunListener { - public static DataKey CONFIGURATION_EDITOR_KEY = DataKey.create("ConfigurationSettingsEditor"); + public static final DataKey CONFIGURATION_EDITOR_KEY = DataKey.create("ConfigurationSettingsEditor"); @NonNls private static final String EXPAND_PROPERTY_KEY = "ExpandBeforeRunStepsPanel"; + private JPanel myComponentPlace; private JPanel myWholePanel; @@ -79,6 +79,7 @@ public class ConfigurationSettingsEditorWrapper extends SettingsEditor tasks, boolean addEnabledTemplateTasksIfAbsent) { + assertDispatchThread(); String existingId = findExistingConfigurationId(settings); String newId = settings.getUniqueID(); RunnerAndConfigurationSettings existingSettings = null; @@ -416,6 +425,7 @@ public class RunManagerImpl extends RunManagerEx implements PersistentStateCompo @Override public void removeConfiguration(@Nullable RunnerAndConfigurationSettings settings) { + assertDispatchThread(); if (settings == null) return; for (Iterator it = getSortedConfigurations().iterator(); it.hasNext(); ) { @@ -684,8 +694,6 @@ public class RunManagerImpl extends RunManagerEx implements PersistentStateCompo @Override public void loadState(Element parentNode) { - clear(false); - List children = parentNode.getChildren(CONFIGURATION); Element[] sortedElements = children.toArray(new Element[children.size()]); // ensure templates are loaded first @@ -810,6 +818,7 @@ public class RunManagerImpl extends RunManagerEx implements PersistentStateCompo } private void clear(boolean allConfigurations) { + assertDispatchThread(); List configurations; if (allConfigurations) { myConfigurations.clear(); @@ -1138,6 +1147,7 @@ public class RunManagerImpl extends RunManagerEx implements PersistentStateCompo @NotNull @Override public List getBeforeRunTasks(RunConfiguration settings, Key taskProviderID) { + assertDispatchThread(); if (settings instanceof WrappingRunConfiguration) { return getBeforeRunTasks(((WrappingRunConfiguration)settings).getPeer(), taskProviderID); } @@ -1159,6 +1169,7 @@ public class RunManagerImpl extends RunManagerEx implements PersistentStateCompo @Override @NotNull public List getBeforeRunTasks(final RunConfiguration settings) { + assertDispatchThread(); if (settings instanceof WrappingRunConfiguration) { return getBeforeRunTasks(((WrappingRunConfiguration)settings).getPeer()); } @@ -1214,6 +1225,7 @@ public class RunManagerImpl extends RunManagerEx implements PersistentStateCompo @Override public final void setBeforeRunTasks(final RunConfiguration runConfiguration, @NotNull List tasks, boolean addEnabledTemplateTasksIfAbsent) { + assertDispatchThread(); List result = new SmartList(tasks); if (addEnabledTemplateTasksIfAbsent) { List templates = getTemplateBeforeRunTasks(runConfiguration); @@ -1234,6 +1246,7 @@ public class RunManagerImpl extends RunManagerEx implements PersistentStateCompo } public final void resetBeforeRunTasks(final RunConfiguration runConfiguration) { + assertDispatchThread(); myConfigurationToBeforeTasksMap.remove(runConfiguration); fireBeforeRunTasksUpdated(); } diff --git a/platform/lang-impl/src/com/intellij/formatting/contextConfiguration/ConfigureCodeStyleOnSelectedFragment.java b/platform/lang-impl/src/com/intellij/formatting/contextConfiguration/ConfigureCodeStyleOnSelectedFragment.java index 7fd57f41b66d..0c62f173b7ea 100644 --- a/platform/lang-impl/src/com/intellij/formatting/contextConfiguration/ConfigureCodeStyleOnSelectedFragment.java +++ b/platform/lang-impl/src/com/intellij/formatting/contextConfiguration/ConfigureCodeStyleOnSelectedFragment.java @@ -15,6 +15,7 @@ */ package com.intellij.formatting.contextConfiguration; +import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.lang.Language; import com.intellij.openapi.diagnostic.Logger; @@ -28,6 +29,7 @@ import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.TextRange; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsCodeFragmentFilter; @@ -50,7 +52,7 @@ public class ConfigureCodeStyleOnSelectedFragment implements IntentionAction { @NotNull @Override public String getText() { - return "Configure code style"; + return CodeInsightBundle.message("configure.code.style.on.fragment.dialog.title"); } @Nls @@ -108,7 +110,9 @@ public class ConfigureCodeStyleOnSelectedFragment implements IntentionAction { myEditor = editor; myDocument = editor.getDocument(); - setTitle("Configure Code Style Settings: " + language.getDisplayName()); + + String title = CodeInsightBundle.message("configure.code.style.on.fragment.dialog.title"); + setTitle(StringUtil.capitalizeWords(title, true) + ": " + language.getDisplayName()); setOKButtonText("Save"); setInitialLocationCallback(new Computable() { diff --git a/platform/lang-impl/src/com/intellij/ide/actions/CreateFileFromTemplateDialog.java b/platform/lang-impl/src/com/intellij/ide/actions/CreateFileFromTemplateDialog.java index 0579a25c6602..b287e578aee9 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/CreateFileFromTemplateDialog.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/CreateFileFromTemplateDialog.java @@ -96,7 +96,7 @@ public class CreateFileFromTemplateDialog extends DialogWrapper { @Override protected void doOKAction() { - if (myCreator.tryCreate(getEnteredName()).length == 0) { + if (myCreator != null && myCreator.tryCreate(getEnteredName()).length == 0) { return; } super.doOKAction(); diff --git a/platform/lang-impl/src/com/intellij/internal/statistic/editor/EditorSettingsStatisticsCollector.java b/platform/lang-impl/src/com/intellij/internal/statistic/editor/EditorSettingsStatisticsCollector.java index 62d3943420e7..b5175578f9ab 100644 --- a/platform/lang-impl/src/com/intellij/internal/statistic/editor/EditorSettingsStatisticsCollector.java +++ b/platform/lang-impl/src/com/intellij/internal/statistic/editor/EditorSettingsStatisticsCollector.java @@ -63,7 +63,7 @@ class EditorSettingsStatisticsCollector extends UsagesCollector { addIfDiffers(set, es.isWhitespacesShown() && es.isTrailingWhitespacesShown(), false, "showTrailingWhitespace"); addIfDiffers(set, es.isIndentGuidesShown(), true, "noIndentGuides"); addIfDiffers(set, es.isSmoothScrolling(), true, "noAnimatedScroll"); - addIfDiffers(set, es.isDndEnabled(), false, "dragNDrop"); + addIfDiffers(set, es.isDndEnabled(), true, "noDragNDrop"); addIfDiffers(set, es.isWheelFontChangeEnabled(), false, "wheelZoom"); addIfDiffers(set, es.isMouseClickSelectionHonorsCamelWords(), true, "mouseNoCamel"); addIfDiffers(set, es.isVariableInplaceRenameEnabled(), true, "noInplaceRename"); diff --git a/platform/lang-impl/src/com/intellij/psi/codeStyle/CodeStyleSettingsCodeFragmentFilter.java b/platform/lang-impl/src/com/intellij/psi/codeStyle/CodeStyleSettingsCodeFragmentFilter.java index 93975d7947f0..98445d3d9145 100644 --- a/platform/lang-impl/src/com/intellij/psi/codeStyle/CodeStyleSettingsCodeFragmentFilter.java +++ b/platform/lang-impl/src/com/intellij/psi/codeStyle/CodeStyleSettingsCodeFragmentFilter.java @@ -68,7 +68,8 @@ public class CodeStyleSettingsCodeFragmentFilter { try { codeStyleSettingsManager.setTemporarySettings(clonedSettings); - SequentialModalProgressTask progressTask = new SequentialModalProgressTask(myProject, CodeInsightBundle.message("configure.code.style.on.fragment.dialog.title")); + String title = CodeInsightBundle.message("configure.code.style.on.fragment.dialog.title"); + SequentialModalProgressTask progressTask = new SequentialModalProgressTask(myProject, StringUtil.capitalizeWords(title, true)); progressTask.setCancelText(CodeInsightBundle.message("configure.code.style.on.fragment.dialog.cancel")); CompositeSequentialTask compositeTask = new CompositeSequentialTask(progressTask); compositeTask.setProgressText(CodeInsightBundle.message("configure.code.style.on.fragment.dialog.progress.text")); diff --git a/platform/lang-impl/src/com/intellij/util/indexing/MemoryIndexStorage.java b/platform/lang-impl/src/com/intellij/util/indexing/MemoryIndexStorage.java index c29692985d88..9a410b2f615c 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/MemoryIndexStorage.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/MemoryIndexStorage.java @@ -190,11 +190,9 @@ public class MemoryIndexStorage implements IndexStorage @Override @NotNull public ValueContainer read(final Key key) throws StorageException { - if (myBufferingEnabled) { - final ValueContainer valueContainer = myMap.get(key); - if (valueContainer != null) { - return valueContainer; - } + final ValueContainer valueContainer = myMap.get(key); + if (valueContainer != null) { + return valueContainer; } return myBackendStorage.read(key); diff --git a/platform/platform-api/src/com/intellij/openapi/actionSystem/CommonShortcuts.java b/platform/platform-api/src/com/intellij/openapi/actionSystem/CommonShortcuts.java index 5a3063d631fb..6bebdd091055 100644 --- a/platform/platform-api/src/com/intellij/openapi/actionSystem/CommonShortcuts.java +++ b/platform/platform-api/src/com/intellij/openapi/actionSystem/CommonShortcuts.java @@ -96,11 +96,14 @@ public class CommonShortcuts { return shortcutsById(IdeActions.ACTION_NEW_ELEMENT); } + public static ShortcutSet getDuplicate() { + return shortcutsById(IdeActions.ACTION_EDITOR_DUPLICATE); + } + public static ShortcutSet getMove() { return shortcutsById(IdeActions.ACTION_MOVE); } - public static ShortcutSet getRename() { return shortcutsById(IdeActions.ACTION_RENAME); } diff --git a/platform/platform-impl/src/com/intellij/ide/RecentProjectsManagerBase.java b/platform/platform-impl/src/com/intellij/ide/RecentProjectsManagerBase.java index 892f949e5897..7a1b2a1fe485 100644 --- a/platform/platform-impl/src/com/intellij/ide/RecentProjectsManagerBase.java +++ b/platform/platform-impl/src/com/intellij/ide/RecentProjectsManagerBase.java @@ -15,11 +15,11 @@ */ package com.intellij.ide; -import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.Separator; import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; @@ -27,6 +27,7 @@ import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerListener; import com.intellij.openapi.project.impl.ProjectImpl; import com.intellij.openapi.ui.Messages; +import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.SystemInfo; @@ -36,10 +37,12 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.wm.impl.SystemDock; import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame; +import com.intellij.util.IconUtil; import com.intellij.util.ImageLoader; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBus; +import com.intellij.util.ui.EmptyIcon; import com.intellij.util.ui.ImageUtil; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; @@ -63,6 +66,7 @@ import java.util.List; */ public abstract class RecentProjectsManagerBase extends RecentProjectsManager implements ProjectManagerListener, PersistentStateComponent { private static final Map ourProjectIcons = new HashMap(); + private static Icon ourSmallAppIcon; public static RecentProjectsManagerBase getInstanceEx() { return (RecentProjectsManagerBase)RecentProjectsManager.getInstance(); @@ -215,6 +219,11 @@ public abstract class RecentProjectsManagerBase extends RecentProjectsManager im @NotNull public static Icon createIcon(File file) { final BufferedImage image = loadAndScaleImage(file); + return toRetinaAwareIcon(image); + } + + @NotNull + protected static Icon toRetinaAwareIcon(final BufferedImage image) { return new Icon() { @Override public void paintIcon(Component c, Graphics g, int x, int y) { @@ -245,10 +254,9 @@ public abstract class RecentProjectsManagerBase extends RecentProjectsManager im private static BufferedImage loadAndScaleImage(File file) { try { Image img = ImageLoader.loadFromUrl(file.toURL()); - return Scalr.resize(ImageUtil.toBufferedImage(img), Scalr.Method.ULTRA_QUALITY, UIUtil.isRetina() ? 32 : JBUI.scale(16), null); + return Scalr.resize(ImageUtil.toBufferedImage(img), Scalr.Method.ULTRA_QUALITY, UIUtil.isRetina() ? 32 : JBUI.scale(16)); } - catch (MalformedURLException e) { - e.printStackTrace(); + catch (MalformedURLException e) {// } return null; } @@ -267,8 +275,32 @@ public abstract class RecentProjectsManagerBase extends RecentProjectsManager im } } + return getSmallApplicationIcon(); + } - return AllIcons.Nodes.IdeaProject; + protected static Icon getSmallApplicationIcon() { + if (ourSmallAppIcon == null) { + try { + Icon appIcon = IconLoader.findIcon(ApplicationInfoEx.getInstanceEx().getIconUrl()); + + if (appIcon != null) { + if (appIcon.getIconWidth() == JBUI.scale(16) && appIcon.getIconHeight() == JBUI.scale(16)) { + ourSmallAppIcon = appIcon; + } else { + BufferedImage image = ImageUtil.toBufferedImage(IconUtil.toImage(appIcon)); + image = Scalr.resize(image, Scalr.Method.ULTRA_QUALITY, UIUtil.isRetina() ? 32 : JBUI.scale(16)); + ourSmallAppIcon = toRetinaAwareIcon(image); + } + } + } + catch (Exception e) {// + } + if (ourSmallAppIcon == null) { + ourSmallAppIcon = EmptyIcon.ICON_16; + } + } + + return ourSmallAppIcon; } private Set getDuplicateProjectNames(Set openedPaths, Set recentPaths) { diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/IntelliJLaf.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/IntelliJLaf.java index 07f6726ce928..363e46d03ffa 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/laf/IntelliJLaf.java +++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/IntelliJLaf.java @@ -56,5 +56,11 @@ public class IntelliJLaf extends DarculaLaf { defaults.put("Label.font", font); defaults.put("CheckBox.font", font); defaults.put("RadioButton.font", font); + defaults.put("ComboBox.font", font); + } + + public static boolean isGraphite() { + Color c = UIManager.getColor("controlHighlight"); + return c != null && c.getBlue() < 150; } } diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/DarculaLaf.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/DarculaLaf.java index eaa05f15b711..1f729b7d1ae3 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/DarculaLaf.java +++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/DarculaLaf.java @@ -437,4 +437,8 @@ public class DarculaLaf extends BasicLookAndFeel { public boolean getSupportsWindowDecorations() { return true; } + + public static Icon loadIcon(String path) { + return IconLoader.findIcon(path, DarculaLaf.class, true); + } } diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxLeft.png b/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxLeft.png new file mode 100644 index 000000000000..7398d6ba8257 Binary files /dev/null and b/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxLeft.png differ diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxLeft@2x.png b/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxLeft@2x.png new file mode 100644 index 000000000000..30cabeb7189b Binary files /dev/null and b/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxLeft@2x.png differ diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxMac.png b/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxMac.png new file mode 100644 index 000000000000..868e624dc27c Binary files /dev/null and b/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxMac.png differ diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxMac@2x.png b/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxMac@2x.png new file mode 100644 index 000000000000..ada5559df968 Binary files /dev/null and b/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxMac@2x.png differ diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxTopBottom.png b/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxTopBottom.png new file mode 100644 index 000000000000..a46f331fac44 Binary files /dev/null and b/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxTopBottom.png differ diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxTopBottom@2x.png b/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxTopBottom@2x.png new file mode 100644 index 000000000000..b2478426c5d4 Binary files /dev/null and b/platform/platform-impl/src/com/intellij/ide/ui/laf/icons/comboboxTopBottom@2x.png differ diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/intellij/MacIntelliJCheckBoxUI.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/intellij/MacIntelliJCheckBoxUI.java index db7cbcd21d36..077a788f0e79 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/laf/intellij/MacIntelliJCheckBoxUI.java +++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/intellij/MacIntelliJCheckBoxUI.java @@ -15,7 +15,7 @@ */ package com.intellij.ide.ui.laf.intellij; -import com.intellij.openapi.util.IconLoader; +import com.intellij.ide.ui.laf.darcula.DarculaLaf; import com.intellij.util.ui.EmptyIcon; import javax.swing.*; @@ -27,6 +27,8 @@ import java.awt.*; */ public class MacIntelliJCheckBoxUI extends IntelliJCheckBoxUI { public static final Icon DEFAULT_ICON = EmptyIcon.create(14); + public static final Icon CHECKED_ICON = DarculaLaf.loadIcon("/com/intellij/ide/ui/laf/icons/checkboxSelectedMac.png"); + public static final Icon UNCHECKED_ICON = DarculaLaf.loadIcon("/com/intellij/ide/ui/laf/icons/checkboxMac.png"); @SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"}) public static ComponentUI createUI(JComponent c) { @@ -35,23 +37,15 @@ public class MacIntelliJCheckBoxUI extends IntelliJCheckBoxUI { @Override protected void drawCheckIcon(JComponent c, Graphics2D g, JCheckBox b, Rectangle iconRect, boolean selected, boolean enabled) { - Icon icon; - if (selected) { - icon = IconLoader.findIcon("/com/intellij/ide/ui/laf/icons/checkboxSelectedMac.png", MacIntelliJCheckBoxUI.class, true); - } else { - icon = IconLoader.findIcon("/com/intellij/ide/ui/laf/icons/checkboxMac.png", MacIntelliJCheckBoxUI.class, true); - } - if (icon != null) { - icon.paintIcon(c, g, iconRect.x, iconRect.y); - } + getIcon(selected).paintIcon(c, g, iconRect.x, iconRect.y); + } + + private Icon getIcon(boolean selected) { + return selected ? CHECKED_ICON : UNCHECKED_ICON; } @Override public Icon getDefaultIcon() { return DEFAULT_ICON; } - - private static boolean isGraphite() { - return false; - } } diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/intellij/MacIntelliJComboBoxUI.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/intellij/MacIntelliJComboBoxUI.java new file mode 100644 index 000000000000..4a48ffdcfe82 --- /dev/null +++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/intellij/MacIntelliJComboBoxUI.java @@ -0,0 +1,284 @@ +/* + * 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. + */ +package com.intellij.ide.ui.laf.intellij; + +import com.intellij.ide.ui.laf.darcula.DarculaLaf; +import com.intellij.openapi.util.IconLoader; +import com.intellij.util.ui.JBUI; + +import javax.swing.*; +import javax.swing.border.Border; +import javax.swing.plaf.ComponentUI; +import javax.swing.plaf.UIResource; +import javax.swing.plaf.basic.BasicArrowButton; +import javax.swing.plaf.basic.BasicComboBoxEditor; +import javax.swing.plaf.basic.BasicComboBoxUI; +import java.awt.*; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; + +/** + * @author Konstantin Bulenkov + */ +public class MacIntelliJComboBoxUI extends BasicComboBoxUI implements Border, UIResource { + private static final Icon COMBOBOX = DarculaLaf.loadIcon("/com/intellij/ide/ui/laf/icons/comboboxMac.png"); + private static final Icon COMBOBOX_LEFT = DarculaLaf.loadIcon("/com/intellij/ide/ui/laf/icons/comboboxLeft.png"); + private static final Icon COMBOBOX_TOP_BOTTOM = DarculaLaf.loadIcon("/com/intellij/ide/ui/laf/icons/comboboxTopBottom.png"); + private final JComboBox myComboBox; + + public MacIntelliJComboBoxUI(JComboBox comboBox) { + myComboBox = comboBox; + myComboBox.setBorder(this); + currentValuePane = new CellRendererPane() { + @Override + public void paintComponent(Graphics g, Component c, Container p, int x, int y, int w, int h, boolean shouldValidate) { + c.setBackground(Color.WHITE); + super.paintComponent(g, c, p, x, y, w, h, shouldValidate); + } + }; + } + + @SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"}) + public static ComponentUI createUI(JComponent c) { + return new MacIntelliJComboBoxUI((JComboBox)c); + } + + @Override + protected JButton createArrowButton() { + final Color bg = myComboBox.getBackground(); + final Color fg = myComboBox.getForeground(); + JButton button = new BasicArrowButton(SwingConstants.SOUTH, bg, fg, fg, fg) { + + @Override + public void paint(Graphics g2) { + Icon icon = myComboBox.isEnabled() ? COMBOBOX : IconLoader.getDisabledIcon(COMBOBOX); + icon.paintIcon(this, g2, 0, 0); + } + + @Override + public Dimension getPreferredSize() { + return JBUI.size(COMBOBOX.getIconWidth(), COMBOBOX.getIconWidth()); + } + }; + button.setBorder(BorderFactory.createEmptyBorder()); + button.setOpaque(false); + return button; + } + + @Override + public Dimension getMinimumSize(JComponent c) { + return getSizeWithIcon(super.getMinimumSize(c)); + } + + private Dimension getSizeWithIcon(Dimension d) { + Insets insets = getBorderInsets(myComboBox); + return new Dimension(Math.max(d.width + insets.left + insets.right, COMBOBOX.getIconWidth()), Math.max(d.height, + COMBOBOX.getIconHeight())); + } + + @Override + public Dimension getPreferredSize(JComponent c) { + return getSizeWithIcon(super.getPreferredSize(c)); + } + + @Override + public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { + + } + + @Override + protected ComboBoxEditor createEditor() { + final ComboBoxEditor comboBoxEditor = new BasicComboBoxEditor.UIResource() { + @Override + protected JTextField createEditorComponent() { + return new JTextField() { + { + setOpaque(false); + setBorder(new Border() { + @Override + public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { + } + + @Override + public Insets getBorderInsets(Component c) { + return JBUI.insets(2, 6, 2, 6); + } + + @Override + public boolean isBorderOpaque() { + return false; + } + }); + } + + public void setText(String s) { + if (getText().equals(s)) { + return; + } + super.setText(s); + } + + public void setBorder(Border b) { + super.setBorder(b); + } + + @Override + public Dimension getPreferredSize() { + Dimension size = super.getPreferredSize(); + return new Dimension(size.width, COMBOBOX.getIconHeight() - 2); + } + }; + } + }; + if (comboBoxEditor.getEditorComponent() != null) { + comboBoxEditor.getEditorComponent().addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + process(e); + } + + @Override + public void keyReleased(KeyEvent e) { + process(e); + } + + private void process(KeyEvent e) { + final int code = e.getKeyCode(); + if ((code == KeyEvent.VK_UP || code == KeyEvent.VK_DOWN) && e.getModifiers() == 0) { + comboBox.dispatchEvent(e); + } + } + }); + comboBoxEditor.getEditorComponent().addFocusListener(new FocusAdapter() { + @Override + public void focusGained(FocusEvent e) { + update(); + } + + @Override + public void focusLost(FocusEvent e) { + update(); + } + + void update() { + if (comboBox != null) { + comboBox.revalidate(); + comboBox.repaint(); + } + } + }); + } + return comboBoxEditor; + } + + @Override + protected Rectangle rectangleForCurrentValue() { + Rectangle rect = super.rectangleForCurrentValue(); + rect.y+=2; + rect.x+=5; + rect.height-=4; + return rect; + } + + @Override + public Insets getBorderInsets(Component c) { + return JBUI.insets(0, 5, 0, 0); + } + + @Override + protected LayoutManager createLayoutManager() { + return new LayoutManager() { + @Override + public void addLayoutComponent(String name, Component comp) { + + } + + @Override + public void removeLayoutComponent(Component comp) { + + } + + @Override + public Dimension preferredLayoutSize(Container parent) { + return null; + } + + @Override + public Dimension minimumLayoutSize(Container parent) { + return null; + } + + @Override + public void layoutContainer(Container parent) { + JComboBox cb = (JComboBox)parent; + int width = cb.getWidth(); + int height = cb.getHeight(); + + Insets insets = getInsets(); + int buttonHeight = height - (insets.top + insets.bottom); + int buttonWidth = buttonHeight; + if (arrowButton != null) { + Insets arrowInsets = arrowButton.getInsets(); + buttonWidth = arrowButton.getPreferredSize().width + arrowInsets.left + arrowInsets.right; + } + Rectangle cvb; + + if (arrowButton != null) { + arrowButton.setBounds(width - (insets.right + buttonWidth), + insets.top, buttonWidth, buttonHeight); + } + if ( editor != null ) { + cvb = rectangleForCurrentValue(); + editor.setBounds(cvb); + } + + } + }; + } + + @Override + public void paintCurrentValueBackground(Graphics g, Rectangle bounds, boolean hasFocus) { + g.setColor(Color.WHITE); + g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height); + } + + + @Override + public void paint(Graphics g, JComponent c) { + super.paint(g, c); + + int stop = arrowButton.getBounds().x; + g.setClip(0,0, stop, COMBOBOX.getIconHeight()); + COMBOBOX_LEFT.paintIcon(c,g,0,0); + int x = COMBOBOX_LEFT.getIconWidth(); + while (x < stop) { + COMBOBOX_TOP_BOTTOM.paintIcon(c, g, x, 0); + x+=COMBOBOX_TOP_BOTTOM.getIconWidth(); + } + ((Graphics2D)g).scale(0.5d, 0.5d); + g.setColor(Color.WHITE); + g.drawLine(COMBOBOX_LEFT.getIconWidth() * 2, 3, stop * 2, 3); + g.drawLine(COMBOBOX_LEFT.getIconWidth() * 2, 40, stop * 2, 40); + ((Graphics2D)g).scale(2d, 2d); + } + + @Override + public boolean isBorderOpaque() { + return false; + } +} diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/intellijlaf_mac.properties b/platform/platform-impl/src/com/intellij/ide/ui/laf/intellijlaf_mac.properties index 63c3c43f8653..a193b504a3f4 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/laf/intellijlaf_mac.properties +++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/intellijlaf_mac.properties @@ -8,5 +8,7 @@ PopupMenu.translucentBackground=ececec Spinner.background=ececec Spinner.darcula.disabledButtonColor=ececec +ComboBoxUI=com.intellij.ide.ui.laf.intellij.MacIntelliJComboBoxUI + SplitPane.highlight=ececec diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffUtil.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffUtil.java index 79146f9a3870..290c59241e4e 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffUtil.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * 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. @@ -30,7 +30,6 @@ import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.ex.EditorEx; -import com.intellij.openapi.editor.impl.softwrap.SoftWrapAppliancePlaces; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.project.Project; @@ -93,7 +92,6 @@ public class DiffUtil { EditorFactory factory = EditorFactory.getInstance(); EditorEx editor = (EditorEx)(isViewer ? factory.createViewer(document, project) : factory.createEditor(document, project)); editor.putUserData(DiffManagerImpl.EDITOR_IS_DIFF_KEY, Boolean.TRUE); - editor.setSoftWrapAppliancePlace(SoftWrapAppliancePlaces.VCS_DIFF); editor.getGutterComponentEx().revalidateMarkup(); if (fileType != null && project != null && !project.isDisposed()) { diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/ex/EditorEx.java b/platform/platform-impl/src/com/intellij/openapi/editor/ex/EditorEx.java index 7813c171cca2..bd8db84994dc 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/ex/EditorEx.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/ex/EditorEx.java @@ -261,11 +261,13 @@ public interface EditorEx extends Editor { /** * We often re-use the logic encapsulated at the editor. For example, every time we show editor fragment (folding, preview etc) we * create a dedicated graphics object and ask the editor to paint into it. - *

+ *

* The thing is that the editor itself may change its state if any postponed operation is triggered by the painting request * (e.g. soft wraps recalculation is triggered by the paint request and newly calculated soft wraps cause caret to change its position). - *

+ *

* This method allows to inform the editor that all subsequent painting request should not change the editor state. + *

+ * In 'pure painting mode' editor also behaves as if soft wraps were not enabled. * * @param enabled 'pure painting mode' status to use */ diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/ex/EditorSettingsExternalizable.java b/platform/platform-impl/src/com/intellij/openapi/editor/ex/EditorSettingsExternalizable.java index 55bb9b3db064..e0cd5310b1dd 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/ex/EditorSettingsExternalizable.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/ex/EditorSettingsExternalizable.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * 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. @@ -143,10 +143,6 @@ public class EditorSettingsExternalizable implements PersistentStateComponent= textLength) return new VisualPosition(line, EditorUtil.columnsNumber(p.x, plainSpaceSize)); + if (offset >= textLength) return new VisualPosition(line, EditorUtil.columnsNumber(px, plainSpaceSize)); // There is a possible case that starting logical line is split by soft-wraps and it's part after the split should be drawn. // We mark that we're under such circumstances then. @@ -1261,7 +1263,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi + "to offset %d (end offset). State: %s", p, line, line, 0, logicalPosition, offset, line + 1, 0, endLogicalPosition, endOffset, dumpState() )); - return new VisualPosition(line, EditorUtil.columnsNumber(p.x, plainSpaceSize)); + return new VisualPosition(line, EditorUtil.columnsNumber(px, plainSpaceSize)); } IterationState state = new IterationState(this, offset, endOffset, false); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/SoftWrapModelImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/SoftWrapModelImpl.java index 564ff777f6fa..683814400d75 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/SoftWrapModelImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/SoftWrapModelImpl.java @@ -83,7 +83,6 @@ public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentLi */ private final List myDeferredFoldRegions = new ArrayList(); - private final SoftWrapFoldBasedApplianceStrategy myFoldBasedApplianceStrategy; private final CachingSoftWrapDataMapper myDataMapper; private final SoftWrapsStorage myStorage; private SoftWrapPainter myPainter; @@ -138,7 +137,6 @@ public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentLi myEditorTextRepresentationHelper = new DefaultEditorTextRepresentationHelper(editor); myDataMapper = new CachingSoftWrapDataMapper(editor, myStorage); myApplianceManager = new SoftWrapApplianceManager(myStorage, editor, myPainter, myDataMapper); - myFoldBasedApplianceStrategy = new SoftWrapFoldBasedApplianceStrategy(editor); myVisualSizeManager = new SoftWrapAwareVisualSizeManager(myPainter); myApplianceManager.addListener(myVisualSizeManager); @@ -434,8 +432,7 @@ public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentLi * @return true if soft wraps-aware processing should be used; false otherwise */ private boolean prepareToMapping() { - boolean useSoftWraps = myActive <= 0 && isSoftWrappingEnabled() && myEditor.getDocument().getTextLength() > 0 - && myFoldBasedApplianceStrategy.processSoftWraps(); + boolean useSoftWraps = myActive <= 0 && isSoftWrappingEnabled() && myEditor.getDocument().getTextLength() > 0; if (!useSoftWraps) { return false; @@ -536,10 +533,6 @@ public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentLi caretModel.moveToVisualPosition(visualCaretPosition); } - public void setPlace(@NotNull SoftWrapAppliancePlaces place) { - myFoldBasedApplianceStrategy.setCurrentPlace(place); - } - @Override public boolean addSoftWrapChangeListener(@NotNull SoftWrapChangeListener listener) { mySoftWrapListeners.add(listener); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/SoftWrapAppliancePlaces.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/SoftWrapAppliancePlaces.java index 59d1a49cc692..f18ef153755a 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/SoftWrapAppliancePlaces.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/SoftWrapAppliancePlaces.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * 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. @@ -25,5 +25,5 @@ package com.intellij.openapi.editor.impl.softwrap; * @since 9/30/10 7:32 PM */ public enum SoftWrapAppliancePlaces { - MAIN_EDITOR, CONSOLE, VCS_DIFF + MAIN_EDITOR, CONSOLE } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/SoftWrapFoldBasedApplianceStrategy.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/SoftWrapFoldBasedApplianceStrategy.java deleted file mode 100644 index e9602db1d3b3..000000000000 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/SoftWrapFoldBasedApplianceStrategy.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2000-2010 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.openapi.editor.impl.softwrap; - -import com.intellij.openapi.editor.ex.EditorEx; -import org.jetbrains.annotations.NotNull; - -/** - * This {@link SoftWrapApplianceStrategy} implementation operates on current fold processing state (enabled/disabled) and - * {@link SoftWrapAppliancePlaces soft wrap appliance place}. - *

- * Rationale: IJ editor toggles folding processing periodically (e.g. during showing collapsed fold region contents). - * Hence, we don't need to use soft wraps processing there (because soft wraps data cache stores fold regions-related information). - * However, there is a possible case that the folding is disabled at all, e.g. that is the case for VCS 'diff window'. Hence, - * we need to distinguish between those situations. - *

- * Not thread-safe. - * - * @author Denis Zhdanov - * @since 10/6/10 8:09 AM - */ -public class SoftWrapFoldBasedApplianceStrategy implements SoftWrapApplianceStrategy { - - private final EditorEx myEditor; - private SoftWrapAppliancePlaces myPlace = SoftWrapAppliancePlaces.MAIN_EDITOR; - - public SoftWrapFoldBasedApplianceStrategy(EditorEx editor) { - myEditor = editor; - } - - @Override - public boolean processSoftWraps() { - return myEditor.getFoldingModel().isFoldingEnabled() || myPlace == SoftWrapAppliancePlaces.VCS_DIFF; - } - - /** - * Instructs current strategy about place where soft wraps-aware editor is used. - *

- * {@link SoftWrapAppliancePlaces#MAIN_EDITOR} is used by default. - * - * @param place place where soft wraps-aware editor is used - */ - public void setCurrentPlace(@NotNull SoftWrapAppliancePlaces place) { - myPlace = place; - } -} diff --git a/platform/platform-impl/src/com/intellij/openapi/project/CacheUpdateRunner.java b/platform/platform-impl/src/com/intellij/openapi/project/CacheUpdateRunner.java index 8c2c2248b10f..912c1291040f 100644 --- a/platform/platform-impl/src/com/intellij/openapi/project/CacheUpdateRunner.java +++ b/platform/platform-impl/src/com/intellij/openapi/project/CacheUpdateRunner.java @@ -67,7 +67,7 @@ public class CacheUpdateRunner { synchronized (processed) { boolean added = processed.add(virtualFile); indicator.setFraction(processed.size() / total); - if (!added || virtualFile.getLength() > FILE_SIZE_TO_SHOW_THRESHOLD) { + if (!added || (virtualFile.isValid() && virtualFile.getLength() > FILE_SIZE_TO_SHOW_THRESHOLD)) { indicator.setText2(virtualFile.getPresentableUrl()); fileNameWasShown = true; } else if (fileNameWasShown) { diff --git a/platform/platform-impl/src/com/intellij/util/UrlImpl.java b/platform/platform-impl/src/com/intellij/util/UrlImpl.java index ee2340db5a89..023865164405 100644 --- a/platform/platform-impl/src/com/intellij/util/UrlImpl.java +++ b/platform/platform-impl/src/com/intellij/util/UrlImpl.java @@ -33,7 +33,7 @@ public final class UrlImpl implements Url { private String externalForm; private UrlImpl withoutParameters; - public UrlImpl(@Nullable String path) { + public UrlImpl(@NotNull String path) { this(null, null, path, null); } @@ -43,8 +43,8 @@ public final class UrlImpl implements Url { public UrlImpl(@Nullable String scheme, @Nullable String authority, @Nullable String path, @Nullable String parameters) { this.scheme = scheme; - this.authority = StringUtil.nullize(authority); - this.path = StringUtil.isEmpty(path) ? "/" : path; + this.authority = authority; + this.path = StringUtil.isEmpty(path) && !StringUtil.isEmpty(authority) ? "/" : StringUtil.notNullize(path); this.parameters = StringUtil.nullize(parameters); } @@ -85,11 +85,11 @@ public final class UrlImpl implements Url { StringBuilder builder = new StringBuilder(); if (scheme != null) { builder.append(scheme); - if (authority != null || isInLocalFileSystem()) { - builder.append(URLUtil.SCHEME_SEPARATOR); + if (authority == null) { + builder.append(':'); } else { - builder.append(':'); + builder.append(URLUtil.SCHEME_SEPARATOR); } if (authority != null) { @@ -111,7 +111,7 @@ public final class UrlImpl implements Url { } // relative path - special url, encoding is not required - // authority is null in case of URI or file URL + // authority is null in case of URI if ((path.charAt(0) != '/' || authority == null) && !isInLocalFileSystem()) { return toDecodedForm(); } diff --git a/platform/platform-impl/src/com/intellij/util/Urls.java b/platform/platform-impl/src/com/intellij/util/Urls.java index abe4c5ae75b2..0deb412f3f1e 100644 --- a/platform/platform-impl/src/com/intellij/util/Urls.java +++ b/platform/platform-impl/src/com/intellij/util/Urls.java @@ -141,15 +141,21 @@ public final class Urls { } String authority = StringUtil.nullize(matcher.group(3)); - String path = StringUtil.nullize(matcher.group(4)); - if (path != null) { - path = FileUtil.toCanonicalUriPath(path); + boolean hasUrlSeparator = !StringUtil.isEmpty(matcher.group(2)); + if (authority == null) { + if (hasUrlSeparator) { + authority = ""; + } + } + else if (StandardFileSystems.FILE_PROTOCOL.equals(scheme) || !hasUrlSeparator) { + path = path == null ? authority : (authority + path); + authority = hasUrlSeparator ? "" : null; } - if (authority != null && (StandardFileSystems.FILE_PROTOCOL.equals(scheme) || StringUtil.isEmpty(matcher.group(2)))) { - path = path == null ? authority : (authority + path); - authority = null; + // canonicalize only if authority is not empty or file url - we should not canonicalize URL with unknown scheme (webpack:///./modules/flux-orion-plugin/fluxPlugin.ts) + if (path != null && (!StringUtil.isEmpty(authority) || StandardFileSystems.FILE_PROTOCOL.equals(scheme))) { + path = FileUtil.toCanonicalUriPath(path); } return new UrlImpl(scheme, authority, path, matcher.group(5)); } diff --git a/platform/platform-resources-en/src/messages/CodeInsightBundle.properties b/platform/platform-resources-en/src/messages/CodeInsightBundle.properties index 8c7ef4149f5e..e7e912f14560 100644 --- a/platform/platform-resources-en/src/messages/CodeInsightBundle.properties +++ b/platform/platform-resources-en/src/messages/CodeInsightBundle.properties @@ -19,7 +19,7 @@ reformat.option.vcs.changed.region=Only &VCS changed text reformat.progress.file.with.known.name.text=Reformatting {0} reformat.and.optimize.progress.common.text=Preparing imports... reformat.progress.common.text=Reformatting code... -configure.code.style.on.fragment.dialog.title=Configure Code Style +configure.code.style.on.fragment.dialog.title=Adjust code style settings configure.code.style.on.fragment.dialog.cancel=Skip configure.code.style.on.fragment.dialog.progress.text=Filtering settings affecting selected code fragment... configure.code.style.on.fragment.dialog.progress.text.under=Press 'Skip' to show all settings diff --git a/platform/platform-tests/testSrc/com/intellij/idea/LockSupportTest.java b/platform/platform-tests/testSrc/com/intellij/idea/LockSupportTest.java index b1e6c3b558d4..928c4fb3a663 100644 --- a/platform/platform-tests/testSrc/com/intellij/idea/LockSupportTest.java +++ b/platform/platform-tests/testSrc/com/intellij/idea/LockSupportTest.java @@ -27,7 +27,7 @@ import java.util.List; /** * @author mike */ -@Bombed(day = 10, month = Calendar.JUNE) +@Bombed(day = 20, month = Calendar.JUNE) public class LockSupportTest extends TestCase { public void testLock() throws Exception { final SocketLock lock = new SocketLock(); diff --git a/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/CloudAgentLoggingHandler.java b/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/CloudAgentLoggingHandler.java index 14041a85b62d..33613616c403 100644 --- a/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/CloudAgentLoggingHandler.java +++ b/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/CloudAgentLoggingHandler.java @@ -17,6 +17,7 @@ package com.intellij.remoteServer.agent.util; import com.intellij.remoteServer.agent.util.log.LogListener; +import java.io.InputStream; import java.io.OutputStream; /** @@ -31,4 +32,8 @@ public interface CloudAgentLoggingHandler { LogListener getOrCreateEmptyLogListener(String pipeName); LogListener createConsole(String pipeName, OutputStream consoleInput); + + boolean isTtySupported(); + + void createTerminal(String pipeName, OutputStream terminalInput, InputStream terminalOutput); } diff --git a/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/LogAgentManager.java b/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/LogAgentManager.java index d55aa52ae683..f989f4ab8b99 100644 --- a/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/LogAgentManager.java +++ b/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/LogAgentManager.java @@ -25,7 +25,7 @@ import java.util.Map; */ public class LogAgentManager { - private Map> myDeploymentName2ActiveLogPipes = new HashMap>(); + private Map> myDeploymentName2ActiveLogPipes = new HashMap>(); public void startListeningLog(String deploymentName, LogPipeProvider provider) { stopListeningLog(deploymentName); @@ -39,9 +39,9 @@ public class LogAgentManager { } private void doStartListeningLog(String deploymentName, LogPipeProvider provider) { - ArrayList pipes = new ArrayList(provider.createLogPipes(deploymentName)); + ArrayList pipes = new ArrayList(provider.createLogPipes(deploymentName)); myDeploymentName2ActiveLogPipes.put(deploymentName, pipes); - for (LogPipe pipe : pipes) { + for (LogPipeBase pipe : pipes) { pipe.open(); } } @@ -53,9 +53,9 @@ public class LogAgentManager { } public void stopListeningLog(String deploymentName) { - List pipes = myDeploymentName2ActiveLogPipes.remove(deploymentName); + List pipes = myDeploymentName2ActiveLogPipes.remove(deploymentName); if (pipes != null) { - for (LogPipe pipe : pipes) { + for (LogPipeBase pipe : pipes) { pipe.close(); } } diff --git a/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/LogPipe.java b/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/LogPipe.java index 6356fb60eab9..7b5f435dfd02 100644 --- a/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/LogPipe.java +++ b/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/LogPipe.java @@ -26,7 +26,7 @@ import java.io.InputStreamReader; /** * @author michael.golubev */ -public abstract class LogPipe { +public abstract class LogPipe extends LogPipeBase { private final String myDeploymentName; private final String myLogPipeName; diff --git a/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/LogPipeBase.java b/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/LogPipeBase.java new file mode 100644 index 000000000000..085ae1f2d34b --- /dev/null +++ b/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/LogPipeBase.java @@ -0,0 +1,23 @@ +/* + * 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. + */ +package com.intellij.remoteServer.agent.util.log; + +public abstract class LogPipeBase { + + public abstract void open(); + + public abstract void close(); +} diff --git a/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/LogPipeProvider.java b/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/LogPipeProvider.java index 993d7603a3df..a234913eff48 100644 --- a/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/LogPipeProvider.java +++ b/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/LogPipeProvider.java @@ -22,5 +22,5 @@ import java.util.List; */ public interface LogPipeProvider { - List createLogPipes(String deploymentName); + List createLogPipes(String deploymentName); } diff --git a/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/TerminalPipe.java b/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/TerminalPipe.java new file mode 100644 index 000000000000..9802bc61d12c --- /dev/null +++ b/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/util/log/TerminalPipe.java @@ -0,0 +1,46 @@ +/* + * 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. + */ +package com.intellij.remoteServer.agent.util.log; + +import com.intellij.remoteServer.agent.util.CloudAgentLoggingHandler; + +import java.io.InputStream; +import java.io.OutputStream; + +public abstract class TerminalPipe extends LogPipeBase { + + private final String myLogPipeName; + private final CloudAgentLoggingHandler myLoggingHandler; + + public TerminalPipe(String logPipeName, CloudAgentLoggingHandler loggingHandler) { + myLogPipeName = logPipeName; + myLoggingHandler = loggingHandler; + } + + @Override + public void open() { + myLoggingHandler.createTerminal(myLogPipeName, getOutputStream(), getInputStream()); + } + + @Override + public void close() { + + } + + protected abstract OutputStream getOutputStream(); + + protected abstract InputStream getInputStream(); +} diff --git a/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/deployment/DeploymentLogManager.java b/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/deployment/DeploymentLogManager.java index becf25c5cdb8..d04f7d1bdb19 100644 --- a/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/deployment/DeploymentLogManager.java +++ b/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/deployment/DeploymentLogManager.java @@ -18,6 +18,9 @@ package com.intellij.remoteServer.runtime.deployment; import com.intellij.remoteServer.runtime.log.LoggingHandler; import org.jetbrains.annotations.NotNull; +import java.io.InputStream; +import java.io.OutputStream; + /** * @author nik */ @@ -27,4 +30,8 @@ public interface DeploymentLogManager { @NotNull LoggingHandler addAdditionalLog(@NotNull String presentableName); + + boolean isTtySupported(); + + void addTerminal(@NotNull String presentableName, InputStream terminalOutput, OutputStream terminalInput); } diff --git a/platform/remote-servers/impl/src/META-INF/RemoteServers.xml b/platform/remote-servers/impl/src/META-INF/RemoteServers.xml index 80994381a28b..9f6674d443fd 100644 --- a/platform/remote-servers/impl/src/META-INF/RemoteServers.xml +++ b/platform/remote-servers/impl/src/META-INF/RemoteServers.xml @@ -6,6 +6,9 @@ + + diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/CloudTerminalProvider.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/CloudTerminalProvider.java new file mode 100644 index 000000000000..ed2b1259a30a --- /dev/null +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/CloudTerminalProvider.java @@ -0,0 +1,35 @@ +/* + * 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. + */ +package com.intellij.remoteServer.impl.runtime.log; + +import com.intellij.openapi.extensions.ExtensionPointName; +import com.intellij.openapi.project.Project; +import org.jetbrains.annotations.NotNull; + +import java.io.InputStream; +import java.io.OutputStream; + +public interface CloudTerminalProvider { + + ExtensionPointName EP_NAME = ExtensionPointName.create("com.intellij.remoteServer.CloudTerminalProvider"); + + LoggingHandlerBase createTerminal(@NotNull String presentableName, + @NotNull Project project, + @NotNull InputStream terminalOutput, + @NotNull OutputStream terminalInput); + + boolean isTtySupported(); +} diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/ConsoleTerminalHandlerImpl.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/ConsoleTerminalHandlerImpl.java new file mode 100644 index 000000000000..da41e8d0e820 --- /dev/null +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/ConsoleTerminalHandlerImpl.java @@ -0,0 +1,116 @@ +/* + * 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. + */ +package com.intellij.remoteServer.impl.runtime.log; + +import com.intellij.execution.process.ProcessHandler; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Disposer; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; +import java.io.*; + +public class ConsoleTerminalHandlerImpl extends LoggingHandlerBase { + + private static final Logger LOG = Logger.getInstance("#" + ConsoleTerminalHandlerImpl.class.getName()); + + public static final CloudTerminalProvider PROVIDER = new CloudTerminalProvider() { + + @Override + public LoggingHandlerBase createTerminal(@NotNull String presentableName, + @NotNull Project project, + @NotNull InputStream terminalOutput, + @NotNull OutputStream terminalInput) { + return new ConsoleTerminalHandlerImpl(presentableName, project, terminalOutput, terminalInput); + } + + @Override + public boolean isTtySupported() { + return false; + } + }; + + private final LoggingHandlerImpl myLoggingHandler; + + public ConsoleTerminalHandlerImpl(String presentableName, + Project project, + final InputStream terminalOutput, + final OutputStream terminalInput) { + super(presentableName); + + myLoggingHandler = new LoggingHandlerImpl(presentableName, project); + myLoggingHandler.attachToProcess(new ProcessHandler() { + @Override + protected void destroyProcessImpl() { + + } + + @Override + protected void detachProcessImpl() { + + } + + @Override + public boolean detachIsDefault() { + return false; + } + + @Nullable + @Override + public OutputStream getProcessInput() { + return terminalInput; + } + }); + + Disposer.register(this, myLoggingHandler); + + ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { + + @Override + public void run() { + BufferedReader outputReader = new BufferedReader(new InputStreamReader(terminalOutput)); + try { + while (true) { + String line = outputReader.readLine(); + if (line == null) { + break; + } + myLoggingHandler.print(line + "\n"); + } + } + catch (IOException e) { + LOG.debug(e); + } + finally { + try { + outputReader.close(); + } + catch (IOException ignored) { + + } + } + } + }); + } + + @Override + public JComponent getComponent() { + return myLoggingHandler.getComponent(); + } +} diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/DeploymentLogManagerImpl.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/DeploymentLogManagerImpl.java index c753977f3460..ebc1a39c5ef3 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/DeploymentLogManagerImpl.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/DeploymentLogManagerImpl.java @@ -20,10 +20,13 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.remoteServer.runtime.deployment.DeploymentLogManager; import com.intellij.remoteServer.runtime.log.LoggingHandler; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NotNull; -import java.util.HashMap; -import java.util.Map; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; /** @@ -32,7 +35,7 @@ import java.util.concurrent.atomic.AtomicBoolean; public class DeploymentLogManagerImpl implements DeploymentLogManager { private final LoggingHandlerImpl myMainLoggingHandler; private final Project myProject; - private final Map myAdditionalLoggingHandlers = new HashMap(); + private final List myAdditionalLoggingHandlers = new ArrayList(); private final Runnable myChangeListener; private final AtomicBoolean myLogsDisposed = new AtomicBoolean(false); @@ -42,7 +45,7 @@ public class DeploymentLogManagerImpl implements DeploymentLogManager { public DeploymentLogManagerImpl(@NotNull Project project, @NotNull Runnable changeListener) { myProject = project; myChangeListener = changeListener; - myMainLoggingHandler = new LoggingHandlerImpl(project); + myMainLoggingHandler = new LoggingHandlerImpl(null, project); myLogsDisposable = Disposer.newDisposable(); Disposer.register(myLogsDisposable, myMainLoggingHandler); Disposer.register(project, new Disposable() { @@ -71,20 +74,40 @@ public class DeploymentLogManagerImpl implements DeploymentLogManager { @NotNull @Override public LoggingHandler addAdditionalLog(@NotNull String presentableName) { - LoggingHandlerImpl handler = new LoggingHandlerImpl(myProject); - Disposer.register(myLogsDisposable, handler); - synchronized (myAdditionalLoggingHandlers) { - myAdditionalLoggingHandlers.put(presentableName, handler); - } - myChangeListener.run(); + LoggingHandlerImpl handler = new LoggingHandlerImpl(presentableName, myProject); + addAdditionalLoggingHandler(handler); return handler; } - @NotNull - public Map getAdditionalLoggingHandlers() { - HashMap result; + @Override + public void addTerminal(@NotNull final String presentableName, InputStream terminalOutput, OutputStream terminalInput) { + LoggingHandlerBase handler = getTerminalProvider().createTerminal(presentableName, myProject, terminalOutput, terminalInput); + addAdditionalLoggingHandler(handler); + } + + private static CloudTerminalProvider getTerminalProvider() { + CloudTerminalProvider terminalProvider = ArrayUtil.getFirstElement(CloudTerminalProvider.EP_NAME.getExtensions()); + return terminalProvider != null ? terminalProvider : ConsoleTerminalHandlerImpl.PROVIDER; + } + + @Override + public boolean isTtySupported() { + return getTerminalProvider().isTtySupported(); + } + + private void addAdditionalLoggingHandler(LoggingHandlerBase loggingHandler) { + Disposer.register(myLogsDisposable, loggingHandler); synchronized (myAdditionalLoggingHandlers) { - result = new HashMap(myAdditionalLoggingHandlers); + myAdditionalLoggingHandlers.add(loggingHandler); + } + myChangeListener.run(); + } + + @NotNull + public List getAdditionalLoggingHandlers() { + List result; + synchronized (myAdditionalLoggingHandlers) { + result = new ArrayList(myAdditionalLoggingHandlers); } return result; } diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/LoggingHandlerBase.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/LoggingHandlerBase.java new file mode 100644 index 000000000000..71be3380b3f0 --- /dev/null +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/LoggingHandlerBase.java @@ -0,0 +1,40 @@ +/* + * 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. + */ +package com.intellij.remoteServer.impl.runtime.log; + +import com.intellij.openapi.Disposable; + +import javax.swing.*; + +public abstract class LoggingHandlerBase implements Disposable { + + private final String myPresentableName; + + public LoggingHandlerBase(String presentableName) { + myPresentableName = presentableName; + } + + public String getPresentableName() { + return myPresentableName; + } + + public abstract JComponent getComponent(); + + @Override + public void dispose() { + + } +} diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/LoggingHandlerImpl.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/LoggingHandlerImpl.java index 0e5491103067..5fb9b88b6e0e 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/LoggingHandlerImpl.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/LoggingHandlerImpl.java @@ -6,23 +6,30 @@ import com.intellij.execution.filters.TextConsoleBuilderFactory; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.ui.ConsoleView; import com.intellij.execution.ui.ConsoleViewContentType; -import com.intellij.openapi.Disposable; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.remoteServer.runtime.log.LoggingHandler; import org.jetbrains.annotations.NotNull; +import javax.swing.*; + /** * @author nik */ -public class LoggingHandlerImpl implements LoggingHandler, Disposable { +public class LoggingHandlerImpl extends LoggingHandlerBase implements LoggingHandler { private final ConsoleView myConsole; - public LoggingHandlerImpl(@NotNull Project project) { + public LoggingHandlerImpl(String presentableName, @NotNull Project project) { + super(presentableName); myConsole = TextConsoleBuilderFactory.getInstance().createBuilder(project).getConsole(); Disposer.register(this, myConsole); } + @Override + public JComponent getComponent() { + return myConsole.getComponent(); + } + @NotNull public ConsoleView getConsole() { return myConsole; @@ -56,9 +63,4 @@ public class LoggingHandlerImpl implements LoggingHandler, Disposable { public void clear() { myConsole.clear(); } - - @Override - public void dispose() { - - } } diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/ServersToolWindowContent.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/ServersToolWindowContent.java index a5d062dfd563..88107cdc83fd 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/ServersToolWindowContent.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/ServersToolWindowContent.java @@ -136,11 +136,10 @@ public class ServersToolWindowContent extends JPanel implements Disposable { myLastSelection = node; if (node instanceof ServersTreeStructure.LogProvidingNode) { ServersTreeStructure.LogProvidingNode logNode = (ServersTreeStructure.LogProvidingNode)node; - LoggingHandlerImpl loggingHandler = logNode.getLoggingHandler(); - if (loggingHandler != null) { + JComponent logComponent = logNode.getComponent(); + if (logComponent != null) { String cardName = logNode.getLogId(); JComponent oldComponent = myLogComponents.get(cardName); - JComponent logComponent = loggingHandler.getConsole().getComponent(); if (!logComponent.equals(oldComponent)) { myLogComponents.put(cardName, logComponent); if (oldComponent != null) { @@ -316,7 +315,7 @@ public class ServersToolWindowContent extends JPanel implements Disposable { AbstractTreeNode parent = node.getParent(); return parent instanceof ServersTreeStructure.DeploymentNodeImpl && isDeploymentNodeMatch((ServersTreeStructure.DeploymentNodeImpl)parent, connection, deploymentName) - && node.getValue().second.equals(logName); + && node.getValue().getPresentableName().equals(logName); } }, null, false); } diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/tree/ServersTreeStructure.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/tree/ServersTreeStructure.java index 29c02383df32..1a63a41f6cbe 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/tree/ServersTreeStructure.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/tree/ServersTreeStructure.java @@ -20,7 +20,6 @@ import com.intellij.openapi.ui.popup.ListPopup; import com.intellij.openapi.ui.popup.PopupStep; import com.intellij.openapi.ui.popup.util.BaseListPopupStep; import com.intellij.openapi.util.Condition; -import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.remoteServer.ServerType; import com.intellij.remoteServer.configuration.RemoteServer; @@ -31,7 +30,7 @@ import com.intellij.remoteServer.impl.configuration.SingleRemoteServerConfigurab import com.intellij.remoteServer.impl.configuration.deployment.DeployToServerRunConfiguration; import com.intellij.remoteServer.impl.runtime.deployment.DeploymentTaskImpl; import com.intellij.remoteServer.impl.runtime.log.DeploymentLogManagerImpl; -import com.intellij.remoteServer.impl.runtime.log.LoggingHandlerImpl; +import com.intellij.remoteServer.impl.runtime.log.LoggingHandlerBase; import com.intellij.remoteServer.impl.runtime.ui.RemoteServersViewContributor; import com.intellij.remoteServer.runtime.ConnectionStatus; import com.intellij.remoteServer.runtime.Deployment; @@ -49,7 +48,10 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.event.MouseEvent; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; /** * @author michael.golubev @@ -104,9 +106,10 @@ public class ServersTreeStructure extends AbstractTreeStructureBase { public interface LogProvidingNode { @Nullable - LoggingHandlerImpl getLoggingHandler(); + JComponent getComponent(); - @NotNull String getLogId(); + @NotNull + String getLogId(); } public class ServersTreeRootNode extends AbstractTreeNode { @@ -343,9 +346,11 @@ public class ServersTreeStructure extends AbstractTreeStructureBase { @Nullable @Override - public LoggingHandlerImpl getLoggingHandler() { + public JComponent getComponent() { DeploymentLogManagerImpl logManager = getLogManager(); - return logManager != null && logManager.isMainHandlerVisible() ? logManager.getMainLoggingHandler() : null; + return logManager != null && logManager.isMainHandlerVisible() + ? logManager.getMainLoggingHandler().getConsole().getComponent() + : null; } @Nullable @@ -368,10 +373,9 @@ public class ServersTreeStructure extends AbstractTreeStructureBase { public Collection getChildren() { DeploymentLogManagerImpl logManager = (DeploymentLogManagerImpl)getConnection().getLogManager(getValue()); if (logManager != null) { - Map handlers = logManager.getAdditionalLoggingHandlers(); List nodes = new ArrayList(); - for (Map.Entry entry : handlers.entrySet()) { - nodes.add(new DeploymentLogNode(Pair.create(entry.getValue(), entry.getKey()), this)); + for (LoggingHandlerBase loggingComponent : logManager.getAdditionalLoggingHandlers()) { + nodes.add(new DeploymentLogNode(loggingComponent, this)); } return nodes; } @@ -398,10 +402,10 @@ public class ServersTreeStructure extends AbstractTreeStructureBase { } } - public class DeploymentLogNode extends AbstractTreeNode> implements ServersTreeNode, LogProvidingNode { + public class DeploymentLogNode extends AbstractTreeNode implements ServersTreeNode, LogProvidingNode { @NotNull private final DeploymentNodeImpl myDeploymentNode; - public DeploymentLogNode(@NotNull Pair value, @NotNull DeploymentNodeImpl deploymentNode) { + public DeploymentLogNode(@NotNull LoggingHandlerBase value, @NotNull DeploymentNodeImpl deploymentNode) { super(doGetProject(), value); myDeploymentNode = deploymentNode; } @@ -419,13 +423,13 @@ public class ServersTreeStructure extends AbstractTreeStructureBase { } private String getLogName() { - return getValue().getSecond(); + return getValue().getPresentableName(); } @Nullable @Override - public LoggingHandlerImpl getLoggingHandler() { - return getValue().getFirst(); + public JComponent getComponent() { + return getValue().getComponent(); } @NotNull diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudLoggingHandlerImpl.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudLoggingHandlerImpl.java index 6154ebd407d7..41ad5e1c59eb 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudLoggingHandlerImpl.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudLoggingHandlerImpl.java @@ -22,6 +22,7 @@ import com.intellij.remoteServer.runtime.deployment.DeploymentLogManager; import com.intellij.remoteServer.runtime.log.LoggingHandler; import org.jetbrains.annotations.Nullable; +import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; @@ -101,6 +102,16 @@ public class CloudLoggingHandlerImpl implements CloudAgentLoggingHandler { }; } + @Override + public boolean isTtySupported() { + return myLogManager.isTtySupported(); + } + + @Override + public void createTerminal(final String pipeName, OutputStream terminalInput, InputStream terminalOutput) { + myLogManager.addTerminal(pipeName, terminalOutput, terminalInput); + } + private static class LogListenerImpl implements LogListener { private final LoggingHandler myLoggingHandler; diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudSilentLoggingHandlerImpl.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudSilentLoggingHandlerImpl.java index 2397953752d6..02219bbfffb6 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudSilentLoggingHandlerImpl.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudSilentLoggingHandlerImpl.java @@ -4,6 +4,7 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.remoteServer.agent.util.CloudAgentLoggingHandler; import com.intellij.remoteServer.agent.util.log.LogListener; +import java.io.InputStream; import java.io.OutputStream; /** @@ -32,4 +33,14 @@ public class CloudSilentLoggingHandlerImpl implements CloudAgentLoggingHandler { public LogListener createConsole(String pipeName, OutputStream consoleInput) { return LogListener.NULL; } + + @Override + public boolean isTtySupported() { + return false; + } + + @Override + public void createTerminal(String pipeName, OutputStream terminalInput, InputStream terminalOutput) { + + } } diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/SMTestRunnerConnectionUtil.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/SMTestRunnerConnectionUtil.java index 0ad0279358dc..b561bf8999bb 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/SMTestRunnerConnectionUtil.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/SMTestRunnerConnectionUtil.java @@ -204,8 +204,6 @@ public class SMTestRunnerConnectionUtil { // UI actions final SMTRunnerUIActionsHandler uiActionsHandler = new SMTRunnerUIActionsHandler(consoleProperties); - // notifications - final SMTRunnerNotificationsHandler notifierHandler = new SMTRunnerNotificationsHandler(consoleProperties); // subscribe to events @@ -219,8 +217,6 @@ public class SMTestRunnerConnectionUtil { if (Registry.is("tests.view.old.statistics.panel")) { eventsProcessor.addEventsListener(statisticsPane.createTestEventsListener()); } - // subscribes test runner's notification balloons on results viewer events - eventsProcessor.addEventsListener(notifierHandler); processHandler.addProcessListener(new ProcessAdapter() { @Override diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertor.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertor.java index 022232641fab..c81797ec8fda 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertor.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertor.java @@ -111,6 +111,7 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP fireOnTestingFinished(); } }); + stopEventProcessing(); } @Override diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralTestEventsProcessor.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralTestEventsProcessor.java index 0708abdcb940..fdeaf362cd96 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralTestEventsProcessor.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralTestEventsProcessor.java @@ -141,6 +141,15 @@ public abstract class GeneralTestEventsProcessor implements Disposable { } } + public void stopEventProcessing() { + UIUtil.invokeLaterIfNeeded(new Runnable() { + @Override + public void run() { + myTransferToEDTQueue.drain(); + } + }); + } + protected static boolean isTreeComplete(Collection runningTests, SMTestProxy.SMRootTestProxy rootNode) { if (!runningTests.isEmpty()) { diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralToSMTRunnerEventsConvertor.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralToSMTRunnerEventsConvertor.java index fe006c360001..09574b2ab3d8 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralToSMTRunnerEventsConvertor.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralToSMTRunnerEventsConvertor.java @@ -112,6 +112,7 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso fireOnTestingFinished(); } }); + stopEventProcessing(); } @Override diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTRunnerTreeBuilder.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTRunnerTreeBuilder.java index e4d9ff5c9c08..a1db456c0710 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTRunnerTreeBuilder.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTRunnerTreeBuilder.java @@ -44,10 +44,7 @@ public class SMTRunnerTreeBuilder extends AbstractTestTreeBuilder { } public void updateTestsSubtree(final SMTestProxy parentTestProxy) { - final AbstractTreeUpdater updater = getUpdater(); - if (updater != null) { - updater.addSubtreeToUpdateByElement(parentTestProxy); - } + queueUpdateFrom(parentTestProxy, false, true); } diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTestProxy.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTestProxy.java index 6b3535ca89fe..9fc70fb262a5 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTestProxy.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTestProxy.java @@ -146,7 +146,7 @@ public class SMTestProxy extends AbstractTestProxy { final boolean canCacheErrors = !myState.isInProgress(); // calculate final boolean hasErrors = calcHasErrors(); - if (canCacheErrors) { + if (canCacheErrors || hasErrors) { myHasCriticalErrors = hasErrors; myHasErrorsCached = true; } diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTRunnerNotificationsHandler.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTRunnerNotificationsHandler.java deleted file mode 100644 index b10d2e03c7dc..000000000000 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTRunnerNotificationsHandler.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.execution.testframework.sm.runner.ui; - -import com.intellij.execution.testframework.TestConsoleProperties; -import com.intellij.execution.testframework.TestsUIUtil; -import com.intellij.execution.testframework.sm.runner.SMTRunnerConsoleProperties; -import com.intellij.execution.testframework.sm.runner.SMTRunnerEventsAdapter; -import com.intellij.execution.testframework.sm.runner.SMTestProxy; -import org.jetbrains.annotations.NotNull; - -/** - * @author Roman Chernyatchik - */ -public class SMTRunnerNotificationsHandler extends SMTRunnerEventsAdapter { - private final TestConsoleProperties myConsoleProperties; - private boolean myStarted = false; - - public SMTRunnerNotificationsHandler(@NotNull final TestConsoleProperties consoleProperties) { - myConsoleProperties = consoleProperties; - } - - public void onTestingStarted(@NotNull SMTestProxy.SMRootTestProxy testsRoot) { - myStarted = true; - } - - public void onTestingFinished(@NotNull SMTestProxy.SMRootTestProxy testsRoot) { - if (testsRoot.isEmptySuite() && - !testsRoot.isInterrupted() && - myConsoleProperties instanceof SMTRunnerConsoleProperties && - ((SMTRunnerConsoleProperties)myConsoleProperties).fixEmptySuite()) { - return; - } - TestsUIUtil.notifyByBalloon(myConsoleProperties.getProject(), myStarted, testsRoot, myConsoleProperties, null); - } -} \ No newline at end of file diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsForm.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsForm.java index 4237ddf91c63..0d164e129900 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsForm.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsForm.java @@ -24,17 +24,22 @@ import com.intellij.execution.testframework.sm.runner.ui.statistics.StatisticsPa import com.intellij.execution.testframework.ui.TestResultsPanel; import com.intellij.execution.testframework.ui.TestsProgressAnimator; import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.progress.util.ColorProgressBar; import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Pass; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.ui.JBColor; +import com.intellij.util.Alarm; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.text.DateFormatUtil; +import com.intellij.util.ui.update.MergingUpdateQueue; +import com.intellij.util.ui.update.Update; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -45,9 +50,8 @@ import javax.swing.event.TreeSelectionListener; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; -import java.util.LinkedHashSet; +import java.util.*; import java.util.List; -import java.util.Set; /** * @author: Roman Chernyatchik @@ -89,6 +93,8 @@ public class SMTestRunnerResultsForm extends TestResultsPanel private final Set myMentionedCategories = new LinkedHashSet(); private boolean myTestsRunning = true; private AbstractTestProxy myLastSelected; + private Alarm myUpdateQueue; + private Set myRequests = Collections.synchronizedSet(new HashSet()); public SMTestRunnerResultsForm(final RunConfiguration runConfiguration, @NotNull final JComponent console, @@ -195,7 +201,7 @@ public class SMTestRunnerResultsForm extends TestResultsPanel //TODO always hide root node //myTreeView.setRootVisible(false); - + myUpdateQueue = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, this); return myTreeView; } @@ -236,6 +242,7 @@ public class SMTestRunnerResultsForm extends TestResultsPanel */ public void onTestingStarted(@NotNull SMTestProxy.SMRootTestProxy testsRoot) { myAnimator.setCurrentTestCase(myTestsRootNode); + myTreeBuilder.updateFromRoot(); // Status line myStatusLine.setStatusColor(ColorProgressBar.GREEN); @@ -294,6 +301,16 @@ public class SMTestRunnerResultsForm extends TestResultsPanel } fireOnTestingFinished(); + + if (testsRoot.isEmptySuite() && + !testsRoot.isInterrupted() && + myConsoleProperties instanceof SMTRunnerConsoleProperties && + ((SMTRunnerConsoleProperties)myConsoleProperties).fixEmptySuite()) { + return; + } + final TestsUIUtil.TestResultPresentation presentation = new TestsUIUtil.TestResultPresentation(testsRoot, myStartTime > 0, null) + .getPresentation(myFailedTestCount, myFinishedTestCount - myFailedTestCount - myIgnoredTestCount, myTotalTestCount - myFinishedTestCount, myIgnoredTestCount); + TestsUIUtil.notifyByBalloon(myConsoleProperties.getProject(), testsRoot, myConsoleProperties, presentation); } public void onTestsCountInSuite(final int count) { @@ -315,12 +332,10 @@ public class SMTestRunnerResultsForm extends TestResultsPanel @Override public void onSuiteTreeNodeAdded(SMTestProxy testProxy) { myTotalTestCount++; - _addTestOrSuite(testProxy); } @Override public void onSuiteTreeStarted(SMTestProxy suite) { - _addTestOrSuite(suite); } public void onTestFailed(@NotNull final SMTestProxy test) { @@ -514,7 +529,19 @@ public class SMTestRunnerResultsForm extends TestResultsPanel assert parentSuite != null; // Tree - myTreeBuilder.updateTestsSubtree(parentSuite); + final Update update = new Update(parentSuite) { + @Override + public void run() { + myRequests.remove(this); + myTreeBuilder.updateTestsSubtree(parentSuite); + } + }; + if (ApplicationManager.getApplication().isUnitTestMode()) { + update.run(); + } + else if (myRequests.add(update)) { + myUpdateQueue.addRequest(update, 100); + } myTreeBuilder.repaintWithParents(newTestOrSuite); myAnimator.setCurrentTestCase(newTestOrSuite); diff --git a/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java b/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java index bc2edcb2e2f7..42ac6f59e2ca 100644 --- a/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java @@ -136,7 +136,7 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da private static PsiManager ourPsiManager; private static boolean ourAssertionsInTestDetected; private static VirtualFile ourSourceRoot; - private static TestCase ourTestCase = null; + private static TestCase ourTestCase; public static Thread ourTestThread; private static LightProjectDescriptor ourProjectDescriptor; private static boolean ourHaveShutdownHook; @@ -253,7 +253,7 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da ByteArrayOutputStream buffer = new ByteArrayOutputStream(); new Throwable(projectFile.getPath()).printStackTrace(new PrintStream(buffer)); - ourProject = PlatformTestCase.createProject(projectFile, LIGHT_PROJECT_MARK + buffer.toString()); + ourProject = PlatformTestCase.createProject(projectFile, LIGHT_PROJECT_MARK + buffer); ourPathToKeep = projectFile.getPath(); if (!ourHaveShutdownHook) { ourHaveShutdownHook = true; @@ -310,14 +310,6 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da }); MessageBusConnection connection = ourProject.getMessageBus().connect(); - connection.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootAdapter() { - @Override - public void beforeRootsChange(ModuleRootEvent event) { - /*if (!event.isCausedByFileTypesChange()) { - fail("Root modification in LightIdeaTestCase is not allowed."); - }*/ - } - }); connection.subscribe(ProjectTopics.MODULES, new ModuleAdapter() { @Override public void moduleAdded(@NotNull Project project, @NotNull Module module) { @@ -372,7 +364,7 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da ApplicationInfoImpl.setInPerformanceTest(isPerformanceTest()); ourApplication.setDataProvider(LightPlatformTestCase.this); - SimpleLightProjectDescriptor descriptor = new SimpleLightProjectDescriptor(getModuleType(), getProjectJDK()); + LightProjectDescriptor descriptor = new SimpleLightProjectDescriptor(getModuleType(), getProjectJDK()); doSetup(descriptor, configureLocalInspectionTools(), getTestRootDisposable()); InjectedLanguageManagerImpl.pushInjectors(getProject()); @@ -417,7 +409,7 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da try { passed = StartupManagerEx.getInstanceEx(getProject()).startupActivityPassed(); } - catch (Exception e) { + catch (Exception ignored) { } assertTrue("open: " + getProject().isOpen() + @@ -733,7 +725,7 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da * @param fileName - name of the file to create. Extension is used to choose what PSI should be created like java, jsp, aj, xml etc. * @param text - file text. * @return dummy psi file. - * @throws com.intellij.util.IncorrectOperationException + * @throws IncorrectOperationException * */ protected static PsiFile createFile(@NonNls String fileName, @NonNls String text) throws IncorrectOperationException { @@ -788,20 +780,22 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da ApplicationManager.getApplication().assertWriteAccessAllowed(); ((ProjectImpl)ourProject).setTemporarilyDisposed(false); - VirtualFile projectFile = ((ProjectEx)ourProject).getStateStore().getProjectFile(); - File ioFile = projectFile == null ? null : VfsUtilCore.virtualToIoFile(projectFile); - if (!ourProject.isDisposed()) Disposer.dispose(ourProject); - - if (ioFile != null) { - File dir = ioFile.getParentFile(); - if (dir.getName().startsWith(UsefulTestCase.TEMP_DIR_MARKER)) { - FileUtil.delete(dir); - } - else { - FileUtil.delete(ioFile); + if (!ourProject.isDisposed()) { + VirtualFile projectFile = ((ProjectEx)ourProject).getStateStore().getProjectFile(); + File ioFile = projectFile == null ? null : VfsUtilCore.virtualToIoFile(projectFile); + Disposer.dispose(ourProject); + if (ioFile != null) { + File dir = ioFile.getParentFile(); + if (dir.getName().startsWith(UsefulTestCase.TEMP_DIR_MARKER)) { + FileUtil.delete(dir); + } + else { + FileUtil.delete(ioFile); + } } } + ProjectManagerEx.getInstanceEx().closeTestProject(ourProject); ourProject = null; ourPathToKeep = null; diff --git a/platform/testFramework/src/com/intellij/util/GCUtil.java b/platform/testFramework/src/com/intellij/util/GCUtil.java index ab2f1a419b68..8f82b7d16df5 100644 --- a/platform/testFramework/src/com/intellij/util/GCUtil.java +++ b/platform/testFramework/src/com/intellij/util/GCUtil.java @@ -21,7 +21,7 @@ import org.jetbrains.annotations.TestOnly; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; -import java.util.List; +import java.util.ArrayList; public class GCUtil { /** @@ -46,7 +46,7 @@ public class GCUtil { public static void tryGcSoftlyReachableObjects() { ReferenceQueue q = new ReferenceQueue(); SoftReference ref = new SoftReference(new Object(), q); - List list = ContainerUtil.newArrayListWithCapacity(100 + useReference(ref)); + ArrayList list = ContainerUtil.newArrayListWithCapacity(100 + useReference(ref)); for (int i = 0; i < 100; i++) { System.gc(); if (q.poll() != null) { @@ -55,6 +55,10 @@ public class GCUtil { TimeoutUtil.sleep(10); long bytes = Math.min(Runtime.getRuntime().freeMemory() / 2, Integer.MAX_VALUE); list.add(new SoftReference(new byte[(int)bytes])); + + // use ref is important as to loop to finish with several iterations: long runs of the method (~80 run of PsiModificationTrackerTest) + // discovered 'ref' being collected and loop iterated 100 times taking a lot of time + list.ensureCapacity(list.size() + useReference(ref)); } } diff --git a/platform/testRunner/src/com/intellij/execution/testframework/TestTreeView.java b/platform/testRunner/src/com/intellij/execution/testframework/TestTreeView.java index 2c32b366a923..6df1834aa748 100644 --- a/platform/testRunner/src/com/intellij/execution/testframework/TestTreeView.java +++ b/platform/testRunner/src/com/intellij/execution/testframework/TestTreeView.java @@ -191,7 +191,9 @@ public abstract class TestTreeView extends Tree implements DataProvider, CopyPro if (TestConsoleProperties.SHOW_INLINE_STATISTICS.value(properties)) { Rectangle visibleRect = getVisibleRect(); Rectangle clip = g.getClipBounds(); - for (int row = 0; row < getRowCount(); row++) { + final int visibleRowCount = TreeUtil.getVisibleRowCountForFixedRowHeight(this); + final int firstRow = getClosestRowForLocation(0, visibleRect.y); + for (int row = firstRow; row < Math.min(firstRow + visibleRowCount, getRowCount()); row++) { if (isExpandableHandlerVisibleForCurrentRow(row)) { continue; } diff --git a/platform/testRunner/src/com/intellij/execution/testframework/TestsUIUtil.java b/platform/testRunner/src/com/intellij/execution/testframework/TestsUIUtil.java index 177ca6793d49..667f34ae126c 100644 --- a/platform/testRunner/src/com/intellij/execution/testframework/TestsUIUtil.java +++ b/platform/testRunner/src/com/intellij/execution/testframework/TestsUIUtil.java @@ -112,6 +112,13 @@ public class TestsUIUtil { final AbstractTestProxy root, final TestConsoleProperties properties, @Nullable final String comment) { + notifyByBalloon(project, root, properties, new TestResultPresentation(root, started, comment).getPresentation()); + } + + public static void notifyByBalloon(@NotNull final Project project, + final AbstractTestProxy root, + final TestConsoleProperties properties, + TestResultPresentation testResultPresentation) { if (project.isDisposed()) return; if (properties == null) return; @@ -120,15 +127,10 @@ public class TestsUIUtil { final String testRunDebugId = properties.isDebug() ? ToolWindowId.DEBUG : ToolWindowId.RUN; final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project); - String title; - String text; - String balloonText; - MessageType type; - TestResultPresentation testResultPresentation = new TestResultPresentation(root, started, comment).getPresentation(); - type = testResultPresentation.getType(); - balloonText = testResultPresentation.getBalloonText(); - title = testResultPresentation.getTitle(); - text = testResultPresentation.getText(); + final String title = testResultPresentation.getTitle(); + final String text = testResultPresentation.getText(); + final String balloonText = testResultPresentation.getBalloonText(); + final MessageType type = testResultPresentation.getType(); if (!Comparing.strEqual(toolWindowManager.getActiveToolWindowId(), testRunDebugId)) { toolWindowManager.notifyByBalloon(testRunDebugId, type, balloonText, null, null); @@ -172,10 +174,10 @@ public class TestsUIUtil { AppIcon.getInstance().setErrorBadge(project, null); } - private static class TestResultPresentation { + public static class TestResultPresentation { private AbstractTestProxy myRoot; private boolean myStarted; - private final String myComment; + private String myComment; private String myTitle; private String myText; private String myBalloonText; @@ -208,30 +210,34 @@ public class TestsUIUtil { } public TestResultPresentation getPresentation() { + List allTests = Filter.LEAF.select(myRoot.getAllTests()); + final List failed = Filter.DEFECTIVE_LEAF.select(allTests); + final List notStarted = Filter.NOT_PASSED.select(allTests); + notStarted.removeAll(failed); + final List ignored = Filter.IGNORED.select(allTests); + notStarted.removeAll(ignored); + failed.removeAll(ignored); + int failedCount = failed.size(); + int notStartedCount = notStarted.size() + ignored.size(); + int passedCount = allTests.size() - failedCount - notStartedCount; + return getPresentation(failedCount, passedCount, notStartedCount, ignored.size()); + } + + public TestResultPresentation getPresentation(int failedCount, int passedCount, int notStartedCount, int ignoredCount) { if (myRoot == null) { myBalloonText = myTitle = myStarted ? "Tests were interrupted" : ExecutionBundle.message("test.not.started.progress.text"); myText = ""; myType = MessageType.WARNING; } else{ - List allTests = Filter.LEAF.select(myRoot.getAllTests()); - final List failed = Filter.DEFECTIVE_LEAF.select(allTests); - final List notStarted = Filter.NOT_PASSED.select(allTests); - notStarted.removeAll(failed); - final List ignored = Filter.IGNORED.select(allTests); - notStarted.removeAll(ignored); - failed.removeAll(ignored); - int failedCount = failed.size(); - int notStartedCount = notStarted.size() + ignored.size(); - int passedCount = allTests.size() - failedCount - notStartedCount; if (failedCount > 0) { myTitle = ExecutionBundle.message("junit.runing.info.tests.failed.label"); myText = passedCount + " passed, " + failedCount + " failed" + (notStartedCount > 0 ? ", " + notStartedCount + " not started" : ""); myType = MessageType.ERROR; } else if (notStartedCount > 0) { - myTitle = !notStarted.isEmpty() ? ExecutionBundle.message("junit.running.info.failed.to.start.error.message") : "Tests Ignored"; - myText = passedCount + " passed, " + notStartedCount + (!notStarted.isEmpty() ? " not started" : " ignored"); - myType = notStarted.isEmpty() ? MessageType.WARNING : MessageType.ERROR; + myTitle = ignoredCount > 0 ? "Tests Ignored" : ExecutionBundle.message("junit.running.info.failed.to.start.error.message"); + myText = passedCount + " passed, " + notStartedCount + (ignoredCount > 0 ? " ignored" : " not started"); + myType = ignoredCount == 0 ? MessageType.WARNING : MessageType.ERROR; } else { myTitle = ExecutionBundle.message("junit.runing.info.tests.passed.label"); diff --git a/platform/testRunner/src/com/intellij/execution/testframework/ToolbarPanel.java b/platform/testRunner/src/com/intellij/execution/testframework/ToolbarPanel.java index 7bd1aec865bb..56502b99c51d 100644 --- a/platform/testRunner/src/com/intellij/execution/testframework/ToolbarPanel.java +++ b/platform/testRunner/src/com/intellij/execution/testframework/ToolbarPanel.java @@ -123,22 +123,26 @@ public class ToolbarPanel extends JPanel implements OccurenceNavigator, Disposab null, properties, TestConsoleProperties.TRACK_RUNNING_TEST)); secondaryGroup.add(new ToggleBooleanProperty("Hide Ignored", null, null, properties, TestConsoleProperties.HIDE_IGNORED_TEST)); - secondaryGroup.add(new ToggleBooleanProperty(ExecutionBundle.message("junit.runing.info.select.first.failed.action.name"), - null, null, properties, TestConsoleProperties.SELECT_FIRST_DEFECT)); - secondaryGroup.add(new ToggleBooleanProperty(ExecutionBundle.message("junit.runing.info.scroll.to.stacktrace.action.name"), - ExecutionBundle.message("junit.runing.info.scroll.to.stacktrace.action.description"), - null, properties, TestConsoleProperties.SCROLL_TO_STACK_TRACE)); - myScrollToSource = new ScrollToTestSourceAction(properties); - secondaryGroup.add(myScrollToSource); - secondaryGroup.add(new ToggleBooleanProperty(ExecutionBundle.message("junit.runing.info.open.source.at.exception.action.name"), - ExecutionBundle.message("junit.runing.info.open.source.at.exception.action.description"), - null, properties, TestConsoleProperties.OPEN_FAILURE_LINE)); if (Registry.is("tests.view.old.statistics.panel")) { secondaryGroup.add(new ShowStatisticsAction(properties)); } secondaryGroup.add(new ToggleBooleanProperty("Show Inline Statistics", "Toggle the visibility of the test duration in the tree", null, properties, TestConsoleProperties.SHOW_INLINE_STATISTICS)); + + secondaryGroup.addSeparator(); + secondaryGroup.add(new ToggleBooleanProperty(ExecutionBundle.message("junit.runing.info.scroll.to.stacktrace.action.name"), + ExecutionBundle.message("junit.runing.info.scroll.to.stacktrace.action.description"), + null, properties, TestConsoleProperties.SCROLL_TO_STACK_TRACE)); + secondaryGroup.add(new ToggleBooleanProperty(ExecutionBundle.message("junit.runing.info.open.source.at.exception.action.name"), + ExecutionBundle.message("junit.runing.info.open.source.at.exception.action.description"), + null, properties, TestConsoleProperties.OPEN_FAILURE_LINE)); + myScrollToSource = new ScrollToTestSourceAction(properties); + secondaryGroup.add(myScrollToSource); + secondaryGroup.add(new AdjustAutotestDelayActionGroup(parent)); + secondaryGroup.addSeparator(); + secondaryGroup.add(new ToggleBooleanProperty(ExecutionBundle.message("junit.runing.info.select.first.failed.action.name"), + null, null, properties, TestConsoleProperties.SELECT_FIRST_DEFECT)); properties.appendAdditionalActions(secondaryGroup, environment, parent); actionGroup.add(secondaryGroup); diff --git a/platform/util/src/com/intellij/execution/process/BaseOSProcessHandler.java b/platform/util/src/com/intellij/execution/process/BaseOSProcessHandler.java index 787215593f04..7ef0d68755be 100644 --- a/platform/util/src/com/intellij/execution/process/BaseOSProcessHandler.java +++ b/platform/util/src/com/intellij/execution/process/BaseOSProcessHandler.java @@ -36,16 +36,14 @@ import static com.intellij.util.io.BaseDataReader.AdaptiveSleepingPolicy; public class BaseOSProcessHandler extends ProcessHandler implements TaskExecutor { private static final Logger LOG = Logger.getInstance("#com.intellij.execution.process.OSProcessHandlerBase"); - @NotNull protected final Process myProcess; - @Nullable protected final String myCommandLine; - protected final ProcessWaitFor myWaitFor; - @Nullable protected final Charset myCharset; + protected final Process myProcess; + protected final String myCommandLine; + protected final Charset myCharset; - public BaseOSProcessHandler(@NotNull final Process process, @Nullable final String commandLine, @Nullable Charset charset) { + public BaseOSProcessHandler(@NotNull Process process, @Nullable String commandLine, @Nullable Charset charset) { myProcess = process; myCommandLine = commandLine; myCharset = charset; - myWaitFor = new ProcessWaitFor(process, this); } /** @@ -97,7 +95,7 @@ public class BaseOSProcessHandler extends ProcessHandler implements TaskExecutor final BaseDataReader stdOutReader = createOutputDataReader(getPolicy()); final BaseDataReader stdErrReader = processHasSeparateErrorStream() ? createErrorDataReader(getPolicy()) : null; - myWaitFor.setTerminationCallback(new Consumer() { + ProcessWaitFor.attach(myProcess, new Consumer() { @Override public void consume(Integer exitCode) { try { @@ -193,7 +191,7 @@ public class BaseOSProcessHandler extends ProcessHandler implements TaskExecutor public void run() { closeStreams(); - myWaitFor.detach(); + ProcessWaitFor.detach(myProcess); notifyProcessDetached(); } }; diff --git a/platform/util/src/com/intellij/execution/process/ProcessWaitFor.java b/platform/util/src/com/intellij/execution/process/ProcessWaitFor.java index d2b42ada2822..b633408621c0 100644 --- a/platform/util/src/com/intellij/execution/process/ProcessWaitFor.java +++ b/platform/util/src/com/intellij/execution/process/ProcessWaitFor.java @@ -1,53 +1,70 @@ +/* + * 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. + */ package com.intellij.execution.process; -import com.intellij.execution.TaskExecutor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.util.Consumer; +import com.intellij.util.TimeoutUtil; +import com.intellij.util.containers.ContainerUtil; +import org.jetbrains.annotations.NotNull; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Future; +import java.util.Map; public class ProcessWaitFor { private static final Logger LOG = Logger.getInstance("#com.intellij.execution.process.ProcessWaitFor"); - private final Future myWaitForThreadFuture; - private final BlockingQueue> myTerminationCallback = new ArrayBlockingQueue>(1); + private static final Map> ourQueue; - public void detach() { - myWaitForThreadFuture.cancel(true); - } + static { + ourQueue = ContainerUtil.newConcurrentMap(); - - public ProcessWaitFor(final Process process, final TaskExecutor executor) { - myWaitForThreadFuture = executor.executeTask(new Runnable() { + BaseOSProcessHandler.ExecutorServiceHolder.submit(new Runnable() { @Override public void run() { - int exitCode = 0; - try { - while (true) { - try { - exitCode = process.waitFor(); - break; - } - catch (InterruptedException e) { - LOG.debug(e); - } - } - } - finally { - try { - myTerminationCallback.take().consume(exitCode); - } - catch (InterruptedException e) { - LOG.info(e); - } + //noinspection InfiniteLoopStatement + while (true) { + processQueue(); + TimeoutUtil.sleep(50); } } }); } - public void setTerminationCallback(Consumer r) { - myTerminationCallback.offer(r); + private static void processQueue() { + for (Process process : ourQueue.keySet()) { + try { + int value = process.exitValue(); + + Consumer callback = ourQueue.remove(process); + if (callback != null) { + callback.consume(value); + } + } + catch (IllegalThreadStateException ignore) { } + catch (RuntimeException e) { + LOG.debug(e); + } + } + } + + public static void attach(@NotNull Process process, @NotNull Consumer callback) { + ourQueue.put(process, callback); + } + + public static void detach(@NotNull Process process) { + ourQueue.remove(process); } } diff --git a/platform/util/src/com/intellij/util/ui/MacUIUtil.java b/platform/util/src/com/intellij/util/ui/MacUIUtil.java index af3b55023539..b5899bc95c46 100644 --- a/platform/util/src/com/intellij/util/ui/MacUIUtil.java +++ b/platform/util/src/com/intellij/util/ui/MacUIUtil.java @@ -136,27 +136,16 @@ public class MacUIUtil { g.setColor(c.getBackground()); g.fillRect(x1, y1, width1, height1); - + if (!myEnabledComponent.isEnabled()) { ((Graphics2D)g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f)); } g.setColor(new Color(100, 100, 100, 200)); - g.drawLine(x1, y1, x1 + width1 - 1, y1); - - g.setColor(new Color(212, 212, 212, 200)); - g.drawLine(x1, y1 + 1, x1 + width1 - 1, y1 + 1); + g.drawRect(x1, y1, width1 - 1, height1 - 1); g.setColor(Gray._225); - g.drawLine(x1 + 1, y1 + height1 - 1, x1 + width1 - 2, y1 + height1 - 1); - - g.setColor(new Color(30, 30, 30, 70)); - g.drawLine(x1, y1, x1, y1 + height1 - 1); - g.drawLine(x1 + width1 - 1, y1, x1 + width1 - 1, y1 + height1 - 1); - - g.setColor(new Color(30, 30, 30, 10)); - g.drawLine(x1 + 1, y1, x1 + 1, y1 + height1 - 1); - g.drawLine(x1 + width1 - 2, y1, x1 + width1 - 2, y1 + height1 - 1); + g.drawRect(x1 + 1, y1 + 1, width1 - 3, height1 - 3); if (myEnabledComponent.isEnabled() && myEnabledComponent.isVisible() && hasFocus(myEnabledComponent)) { paintTextFieldFocusRing((Graphics2D) g, new Rectangle(x1, y1, width1, height1)); diff --git a/platform/util/src/com/intellij/util/xmlb/BeanBinding.java b/platform/util/src/com/intellij/util/xmlb/BeanBinding.java index e9a0ea274b29..ea764fa14550 100644 --- a/platform/util/src/com/intellij/util/xmlb/BeanBinding.java +++ b/platform/util/src/com/intellij/util/xmlb/BeanBinding.java @@ -50,7 +50,7 @@ class BeanBinding extends Binding implements MainBinding { final Class myBeanClass; - ThreeState hasEqualMethod = ThreeState.UNSURE; + ThreeState compareByFields = ThreeState.UNSURE; public BeanBinding(@NotNull Class beanClass, @Nullable MutableAccessor accessor) { super(accessor); diff --git a/platform/util/src/com/intellij/util/xmlb/SkipDefaultsSerializationFilter.java b/platform/util/src/com/intellij/util/xmlb/SkipDefaultsSerializationFilter.java index 57d8458be07e..610c5d9dddcc 100644 --- a/platform/util/src/com/intellij/util/xmlb/SkipDefaultsSerializationFilter.java +++ b/platform/util/src/com/intellij/util/xmlb/SkipDefaultsSerializationFilter.java @@ -48,11 +48,11 @@ public final class SkipDefaultsSerializationFilter extends SkipDefaultValuesSeri Binding referencedBinding = ((BasePrimitiveBinding)binding).myBinding; if (referencedBinding instanceof BeanBinding) { BeanBinding classBinding = (BeanBinding)referencedBinding; - ThreeState compareByFields = classBinding.hasEqualMethod; + ThreeState compareByFields = classBinding.compareByFields; if (compareByFields == ThreeState.UNSURE) { compareByFields = ReflectionUtil.getDeclaredMethod(classBinding.myBeanClass, "equals", Object.class) == null ? ThreeState.YES : ThreeState.NO; - classBinding.hasEqualMethod = compareByFields; + classBinding.compareByFields = compareByFields; } if (compareByFields == ThreeState.YES) { diff --git a/platform/util/testSrc/com/intellij/execution/process/ProcessWaitForTest.java b/platform/util/testSrc/com/intellij/execution/process/ProcessWaitForTest.java new file mode 100644 index 000000000000..d596bce075e9 --- /dev/null +++ b/platform/util/testSrc/com/intellij/execution/process/ProcessWaitForTest.java @@ -0,0 +1,48 @@ +/* + * 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. + */ +package com.intellij.execution.process; + +import com.intellij.openapi.util.SystemInfo; +import com.intellij.util.Consumer; +import com.intellij.util.concurrency.Semaphore; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; + +import static org.junit.Assert.assertTrue; + +public class ProcessWaitForTest { + @Test(timeout = 10000) + public void notification() throws IOException, InterruptedException { + File jvm = new File(System.getProperty("java.home") + (SystemInfo.isWindows ? "\\bin\\java.exe" : "/bin/java")); + assertTrue(jvm.canExecute()); + + final Semaphore semaphore = new Semaphore(); + semaphore.down(); + + Process process = new ProcessBuilder(jvm.getPath(), "-version").redirectErrorStream(true).start(); + ProcessWaitFor.attach(process, new Consumer() { + @Override + public void consume(Integer exitCode) { + semaphore.up(); + } + }); + process.waitFor(); + + assertTrue(semaphore.waitFor(5000)); + } +} \ No newline at end of file diff --git a/platform/util/testSrc/com/intellij/util/xmlb/XmlSerializerTest.java b/platform/util/testSrc/com/intellij/util/xmlb/XmlSerializerTest.java index 53dcc89daea5..7e5fe1f646af 100644 --- a/platform/util/testSrc/com/intellij/util/xmlb/XmlSerializerTest.java +++ b/platform/util/testSrc/com/intellij/util/xmlb/XmlSerializerTest.java @@ -168,6 +168,37 @@ public class XmlSerializerTest extends TestCase { bean, new SkipDefaultsSerializationFilter()); } + public final static class BeanWithEquals { + public String STRING_V = "hello"; + + public BeanWithEquals() { + } + + @Override + public boolean equals(Object o) { + // any instance of this class is equal + return this == o || (o != null && getClass() == o.getClass()); + } + } + + public static class BeanWithSubBeanWithEquals { + public EmptyBeanWithCustomName BEAN1 = new EmptyBeanWithCustomName(); + public BeanWithEquals BEAN2 = new BeanWithEquals(); + } + + public void testSubBeanWithEqualsSerializationAndSkipDefaults() { + BeanWithSubBeanWithEquals bean = new BeanWithSubBeanWithEquals(); + SkipDefaultsSerializationFilter filter = new SkipDefaultsSerializationFilter(); + doSerializerTest( + "", + bean, filter); + + bean.BEAN2.STRING_V = "new"; + doSerializerTest( + "", + bean, filter); + } + public void testNullFieldValue() { BeanWithPublicFields bean1 = new BeanWithPublicFields(); diff --git a/platform/vcs-impl/testSrc/com/intellij/testFramework/vcs/MockVcsContextFactory.java b/platform/vcs-impl/testSrc/com/intellij/testFramework/vcs/MockVcsContextFactory.java index 16dde9fe003f..1e825f2e2d6e 100644 --- a/platform/vcs-impl/testSrc/com/intellij/testFramework/vcs/MockVcsContextFactory.java +++ b/platform/vcs-impl/testSrc/com/intellij/testFramework/vcs/MockVcsContextFactory.java @@ -38,7 +38,7 @@ public class MockVcsContextFactory extends VcsContextFactoryImpl { } private class CustomFileSystemFilePath extends LocalFilePath { - public CustomFileSystemFilePath(String path, boolean directory) { + public CustomFileSystemFilePath(@NotNull String path, boolean directory) { super(path, directory); } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/XDebuggerUtilImpl.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/XDebuggerUtilImpl.java index cc2ba00f239f..bc5288599510 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/XDebuggerUtilImpl.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/XDebuggerUtilImpl.java @@ -18,6 +18,7 @@ package com.intellij.xdebugger.impl; import com.intellij.lang.Language; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.editor.Caret; @@ -28,12 +29,18 @@ import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.popup.JBPopupFactory; +import com.intellij.openapi.ui.popup.PopupStep; +import com.intellij.openapi.ui.popup.util.BaseListPopupStep; +import com.intellij.openapi.util.AsyncResult; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.ui.awt.RelativePoint; import com.intellij.util.Processor; +import com.intellij.util.SmartList; import com.intellij.xdebugger.*; import com.intellij.xdebugger.breakpoints.*; import com.intellij.xdebugger.breakpoints.ui.XBreakpointGroupingRule; @@ -45,6 +52,8 @@ import com.intellij.xdebugger.frame.XSuspendContext; import com.intellij.xdebugger.frame.XValueContainer; import com.intellij.xdebugger.impl.breakpoints.XBreakpointUtil; import com.intellij.xdebugger.impl.breakpoints.XExpressionImpl; +import com.intellij.xdebugger.impl.breakpoints.XLineBreakpointVariant; +import com.intellij.xdebugger.impl.breakpoints.XLineBreakpointVariantsProvider; import com.intellij.xdebugger.impl.breakpoints.ui.grouping.XBreakpointFileGroupingRule; import com.intellij.xdebugger.impl.evaluate.quick.common.ValueLookupManager; import com.intellij.xdebugger.impl.settings.XDebuggerSettingsManager; @@ -54,6 +63,7 @@ import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import javax.swing.*; import java.util.*; /** @@ -107,26 +117,78 @@ public class XDebuggerUtilImpl extends XDebuggerUtil { @NotNull final VirtualFile file, final int line, final boolean temporary) { - toggleAndReturnLineBreakpoint(project, type, file, line, temporary); + XSourcePositionImpl position = XSourcePositionImpl.create(file, line); + if (position != null) { + toggleAndReturnLineBreakpoint(project, type, position, temporary, null); + } } - public static

XLineBreakpoint toggleAndReturnLineBreakpoint(@NotNull final Project project, + @NotNull + public static

AsyncResult toggleAndReturnLineBreakpoint(@NotNull final Project project, @NotNull final XLineBreakpointType

type, - @NotNull final VirtualFile file, - final int line, - final boolean temporary) { - return new WriteAction() { + @NotNull final XSourcePosition position, + final boolean temporary, + final RelativePoint relativePoint) { + return new WriteAction>() { @Override - protected void run(@NotNull final Result result) { - XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager(); + protected void run(@NotNull Result> result) throws Throwable { + final VirtualFile file = position.getFile(); + final int line = position.getLine(); + final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager(); XLineBreakpoint

breakpoint = breakpointManager.findBreakpointAtLine(type, file, line); if (breakpoint != null) { breakpointManager.removeBreakpoint(breakpoint); } else { + if (type instanceof XLineBreakpointVariantsProvider) { + final XLineBreakpointVariantsProvider provider = + (XLineBreakpointVariantsProvider)type; + List variants = provider.computeLineBreakpointVariants(project, position); + if (!variants.isEmpty()) { + if (variants.size() > 1 && relativePoint != null) { + final AsyncResult res = new AsyncResult(); + JBPopupFactory.getInstance().createListPopup( + new BaseListPopupStep("Create breakpoint for", variants) { + @NotNull + @Override + public String getTextFor(XLineBreakpointVariant value) { + return value.getText(); + } + + @Override + public Icon getIconFor(XLineBreakpointVariant value) { + return value.getIcon(); + } + + @Override + public PopupStep onChosen(final XLineBreakpointVariant selectedValue, boolean finalChoice) { + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + P properties = (P)selectedValue.createProperties(); + res.setDone(breakpointManager.addLineBreakpoint(type, file.getUrl(), line, properties, temporary)); + } + }); + return FINAL_CHOICE; + } + }).show(relativePoint); + result.setResult(res); + return; + } + else { + P properties = (P)variants.get(0).createProperties(); + result.setResult(AsyncResult.done( + (XLineBreakpoint)breakpointManager.addLineBreakpoint(type, file.getUrl(), line, properties, temporary))); + return; + } + } + } P properties = type.createBreakpointProperties(file, line); - result.setResult(breakpointManager.addLineBreakpoint(type, file.getUrl(), line, properties, temporary)); + result.setResult(AsyncResult + .done((XLineBreakpoint)breakpointManager.addLineBreakpoint(type, file.getUrl(), line, properties, temporary))); + return; } + result.setResult(AsyncResult.rejected()); } }.execute().getResultObject(); } @@ -199,13 +261,10 @@ public class XDebuggerUtilImpl extends XDebuggerUtil { return Collections.emptyList(); } - final Document document = editor.getDocument(); - VirtualFile file = FileDocumentManager.getInstance().getFile(document); - Collection res = new ArrayList(); - List carets = editor.getCaretModel().getAllCarets(); - for (Caret caret : carets) { - int line = caret.getLogicalPosition().line; - XSourcePositionImpl position = XSourcePositionImpl.create(file, line); + VirtualFile file = FileDocumentManager.getInstance().getFile(editor.getDocument()); + List res = new SmartList(); + for (Caret caret : editor.getCaretModel().getAllCarets()) { + XSourcePositionImpl position = XSourcePositionImpl.createByOffset(file, caret.getOffset()); if (position != null) { res.add(position); } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/actions/handlers/XToggleLineBreakpointActionHandler.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/actions/handlers/XToggleLineBreakpointActionHandler.java index 78462bbee293..b9a8beafed14 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/actions/handlers/XToggleLineBreakpointActionHandler.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/actions/handlers/XToggleLineBreakpointActionHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * 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. @@ -65,7 +65,7 @@ public class XToggleLineBreakpointActionHandler extends DebuggerActionHandler { Set processedLines = new HashSet(); for (XSourcePosition position : XDebuggerUtilImpl.getAllCaretsPositions(project, event.getDataContext())) { if (processedLines.add(position.getLine())) { - XBreakpointUtil.toggleLineBreakpoint(project, position.getFile(), editor, position.getLine(), myTemporary, true); + XBreakpointUtil.toggleLineBreakpoint(project, position, editor, myTemporary, true); } } } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XBreakpointUtil.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XBreakpointUtil.java index 7bfc31989e3b..d5280fc94e6e 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XBreakpointUtil.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XBreakpointUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * 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. @@ -22,16 +22,20 @@ import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.FoldRegion; import com.intellij.openapi.editor.markup.GutterIconRenderer; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.AsyncResult; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.xdebugger.XDebuggerManager; import com.intellij.xdebugger.XDebuggerUtil; +import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.breakpoints.*; import com.intellij.xdebugger.impl.DebuggerSupport; import com.intellij.xdebugger.impl.XDebuggerUtilImpl; +import com.intellij.xdebugger.impl.XSourcePositionImpl; import com.intellij.xdebugger.impl.breakpoints.ui.BreakpointItem; import com.intellij.xdebugger.impl.breakpoints.ui.BreakpointPanelProvider; +import com.intellij.xdebugger.impl.ui.DebuggerUIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -130,12 +134,14 @@ public class XBreakpointUtil { * - unfolds folded block on the line * - if folded, checks if line breakpoints could be toggled inside folded text */ - public static XLineBreakpoint toggleLineBreakpoint(Project project, - VirtualFile file, - Editor editor, - int lineStart, + @NotNull + public static AsyncResult toggleLineBreakpoint(@NotNull Project project, + @NotNull XSourcePosition position, + @Nullable Editor editor, boolean temporary, boolean moveCarret) { + int lineStart = position.getLine(); + VirtualFile file = position.getFile(); // for folded text check each line and find out type with the biggest priority int linesEnd = lineStart; if (editor != null) { @@ -147,7 +153,7 @@ public class XBreakpointUtil { final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager(); XLineBreakpointType[] lineTypes = XDebuggerUtil.getInstance().getLineBreakpointTypes(); - XLineBreakpointType typeWinner = null; + XLineBreakpointType typeWinner = null; int lineWinner = -1; for (int line = lineStart; line <= linesEnd; line++) { int maxPriority = 0; @@ -170,18 +176,22 @@ public class XBreakpointUtil { } if (typeWinner != null) { - XLineBreakpoint res = XDebuggerUtilImpl.toggleAndReturnLineBreakpoint(project, typeWinner, file, lineWinner, temporary); + XSourcePosition winPosition = (lineStart == lineWinner) ? position : XSourcePositionImpl.create(file, lineWinner); + if (winPosition != null) { + AsyncResult res = XDebuggerUtilImpl.toggleAndReturnLineBreakpoint(project, typeWinner, winPosition, temporary, + DebuggerUIUtil.calcPopupLocation(editor, lineWinner)); - if (editor != null && lineStart != lineWinner) { - int offset = editor.getDocument().getLineStartOffset(lineWinner); - ExpandRegionAction.expandRegionAtOffset(project, editor, offset); - if (moveCarret) { - editor.getCaretModel().moveToOffset(offset); + if (editor != null && lineStart != lineWinner) { + int offset = editor.getDocument().getLineStartOffset(lineWinner); + ExpandRegionAction.expandRegionAtOffset(project, editor, offset); + if (moveCarret) { + editor.getCaretModel().moveToOffset(offset); + } } + return res; } - return res; } - return null; + return AsyncResult.rejected(); } } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XLineBreakpointManager.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XLineBreakpointManager.java index acf896a8d357..626b22e068f0 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XLineBreakpointManager.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XLineBreakpointManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * 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. @@ -38,6 +38,7 @@ import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.project.DumbAwareRunnable; import com.intellij.openapi.project.Project; import com.intellij.openapi.startup.StartupManager; +import com.intellij.openapi.util.AsyncResult; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; @@ -45,6 +46,7 @@ import com.intellij.openapi.vfs.VirtualFileEvent; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.VirtualFileUrlChangeAdapter; import com.intellij.psi.PsiDocumentManager; +import com.intellij.util.Consumer; import com.intellij.util.SmartList; import com.intellij.util.containers.BidirectionalMap; import com.intellij.util.ui.update.MergingUpdateQueue; @@ -53,6 +55,7 @@ import com.intellij.xdebugger.XDebuggerManager; import com.intellij.xdebugger.breakpoints.SuspendPolicy; import com.intellij.xdebugger.breakpoints.XBreakpoint; import com.intellij.xdebugger.breakpoints.XLineBreakpoint; +import com.intellij.xdebugger.impl.XSourcePositionImpl; import com.intellij.xdebugger.impl.ui.DebuggerUIUtil; import gnu.trove.TIntHashSet; import org.jetbrains.annotations.NotNull; @@ -297,20 +300,25 @@ public class XLineBreakpointManager { if (!myProject.isDisposed() && myProject.isInitialized() && file.isValid()) { ActionManagerEx.getInstanceEx().fireBeforeActionPerformed("ToggleLineBreakpoint", e.getMouseEvent()); - XLineBreakpoint breakpoint = - XBreakpointUtil.toggleLineBreakpoint(myProject, file, editor, line, mouseEvent.isAltDown(), false); - if (!mouseEvent.isAltDown() && mouseEvent.isShiftDown() && breakpoint != null) { - breakpoint.setSuspendPolicy(SuspendPolicy.NONE); - String selection = editor.getSelectionModel().getSelectedText(); - if (selection != null) { - breakpoint.setLogExpression(selection); + AsyncResult result = XBreakpointUtil.toggleLineBreakpoint( + myProject, XSourcePositionImpl.create(file, line), editor, mouseEvent.isAltDown(), false); + result.doWhenDone(new Consumer() { + @Override + public void consume(XLineBreakpoint breakpoint) { + if (!mouseEvent.isAltDown() && mouseEvent.isShiftDown() && breakpoint != null) { + breakpoint.setSuspendPolicy(SuspendPolicy.NONE); + String selection = editor.getSelectionModel().getSelectedText(); + if (selection != null) { + breakpoint.setLogExpression(selection); + } + else { + breakpoint.setLogMessage(true); + } + // edit breakpoint + DebuggerUIUtil.showXBreakpointEditorBalloon(myProject, mouseEvent.getPoint(), ((EditorEx)editor).getGutterComponentEx(), false, breakpoint); + } } - else { - breakpoint.setLogMessage(true); - } - // edit breakpoint - DebuggerUIUtil.showXBreakpointEditorBalloon(myProject, mouseEvent.getPoint(), ((EditorEx)editor).getGutterComponentEx(), false, breakpoint); - } + }); } } }); diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XLineBreakpointVariant.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XLineBreakpointVariant.java new file mode 100644 index 000000000000..18b4db2b6891 --- /dev/null +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XLineBreakpointVariant.java @@ -0,0 +1,34 @@ +/* + * 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. + */ +package com.intellij.xdebugger.impl.breakpoints; + +import com.intellij.openapi.util.TextRange; +import com.intellij.xdebugger.breakpoints.XBreakpointProperties; + +import javax.swing.*; + +/** + * @author egor + */ +public abstract class XLineBreakpointVariant

{ + public abstract String getText(); + + public abstract Icon getIcon(); + + public abstract TextRange getHighlightRange(); + + public abstract P createProperties(); +} diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XLineBreakpointVariantsProvider.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XLineBreakpointVariantsProvider.java new file mode 100644 index 000000000000..9861ef0f8a29 --- /dev/null +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XLineBreakpointVariantsProvider.java @@ -0,0 +1,30 @@ +/* + * 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. + */ +package com.intellij.xdebugger.impl.breakpoints; + +import com.intellij.openapi.project.Project; +import com.intellij.xdebugger.XSourcePosition; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +/** + * @author egor + */ +public interface XLineBreakpointVariantsProvider { + @NotNull + List computeLineBreakpointVariants(@NotNull Project project, @NotNull XSourcePosition position); +} diff --git a/plugins/devkit/src/testAssistant/NavigateToTestDataAction.java b/plugins/devkit/src/testAssistant/NavigateToTestDataAction.java index 91b903e9bbdb..c325da519163 100644 --- a/plugins/devkit/src/testAssistant/NavigateToTestDataAction.java +++ b/plugins/devkit/src/testAssistant/NavigateToTestDataAction.java @@ -65,7 +65,7 @@ public class NavigateToTestDataAction extends AnAction implements TestTreeViewAc } @Nullable - public static List findTestDataFiles(@NotNull DataContext context) { + static List findTestDataFiles(@NotNull DataContext context) { final PsiMethod method = findTargetMethod(context); if (method == null) { return null; diff --git a/plugins/devkit/src/testAssistant/NavigateToTestDataActionGroup.java b/plugins/devkit/src/testAssistant/NavigateToTestDataActionGroup.java deleted file mode 100644 index 795832f78cc8..000000000000 --- a/plugins/devkit/src/testAssistant/NavigateToTestDataActionGroup.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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. - */ -package org.jetbrains.idea.devkit.testAssistant; - -import com.intellij.openapi.actionSystem.ActionGroup; -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.fileTypes.FileTypeManager; -import com.intellij.psi.PsiMethod; -import com.intellij.util.Function; -import com.intellij.util.containers.ContainerUtil; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -public class NavigateToTestDataActionGroup extends ActionGroup { - private final PsiMethod myMethod; - - public NavigateToTestDataActionGroup(PsiMethod method) { - myMethod = method; - } - - @NotNull - @Override - public AnAction[] getChildren(@Nullable AnActionEvent e) { - List names = TestDataNavigationHandler.getFileNames(myMethod); - if (names == null || names.isEmpty()) return new AnAction[0]; - return ContainerUtil.map2Array(names, AnAction.class, new Function() { - @Override - public AnAction fun(String s) { - return new GotoTestDataAction(s, myMethod.getProject(), FileTypeManager.getInstance().getFileTypeByFileName(s).getIcon()); - } - }); - } -} diff --git a/plugins/devkit/src/testAssistant/TestDataLineMarkerProvider.java b/plugins/devkit/src/testAssistant/TestDataLineMarkerProvider.java index 017d5b95a6a2..f0dcc8e2202a 100644 --- a/plugins/devkit/src/testAssistant/TestDataLineMarkerProvider.java +++ b/plugins/devkit/src/testAssistant/TestDataLineMarkerProvider.java @@ -18,6 +18,7 @@ package org.jetbrains.idea.devkit.testAssistant; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.execution.lineMarker.RunLineMarkerContributor; import com.intellij.icons.AllIcons; +import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; @@ -39,9 +40,11 @@ public class TestDataLineMarkerProvider extends RunLineMarkerContributor { public static final String CONTENT_ROOT_VARIABLE = "$CONTENT_ROOT"; public static final String PROJECT_ROOT_VARIABLE = "$PROJECT_ROOT"; - public AnAction getAdditionalAction(@NotNull PsiElement element) { + public AnAction getAdditionalAction(@NotNull PsiElement e) { - if (!(element instanceof PsiMethod) && + PsiElement element = e.getParent(); + if (!(e instanceof PsiIdentifier) || + !(element instanceof PsiMethod) && !(element instanceof PsiClass)) { return null; } @@ -55,8 +58,7 @@ public class TestDataLineMarkerProvider extends RunLineMarkerContributor { return null; } if (element instanceof PsiMethod) { - final PsiMethod method = (PsiMethod)element; - return new NavigateToTestDataActionGroup(method); + return ActionManager.getInstance().getAction("TestData.Navigate"); } else { final PsiClass psiClass = (PsiClass)element; final String basePath = getTestDataBasePath(psiClass); diff --git a/plugins/junit/src/com/intellij/execution/junit/JUnitRunLineMarkerProvider.java b/plugins/junit/src/com/intellij/execution/junit/JUnitRunLineMarkerProvider.java index f49c3c4995a7..d83b7ea49d40 100644 --- a/plugins/junit/src/com/intellij/execution/junit/JUnitRunLineMarkerProvider.java +++ b/plugins/junit/src/com/intellij/execution/junit/JUnitRunLineMarkerProvider.java @@ -21,6 +21,7 @@ import com.intellij.execution.PsiLocation; import com.intellij.execution.lineMarker.RunLineMarkerInfo; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiIdentifier; import com.intellij.psi.PsiMethod; import com.intellij.util.Function; import org.jetbrains.annotations.NotNull; @@ -43,13 +44,17 @@ public class JUnitRunLineMarkerProvider implements LineMarkerProvider { @Nullable @Override - public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement element) { - if (element instanceof PsiClass && JUnitUtil.isTestClass((PsiClass)element, false, true)) - return new RunLineMarkerInfo(element, JUnitConfigurationType.getInstance().getIcon(), TOOLTIP_PROVIDER); - if (element instanceof PsiMethod && JUnitUtil.isTestMethod(new PsiLocation((PsiMethod)element))) - return new RunLineMarkerInfo(element, JUnitConfigurationType.getInstance().getIcon(), TOOLTIP_PROVIDER); + public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement e) { + if (e instanceof PsiIdentifier) { + PsiElement element = e.getParent(); + if (element instanceof PsiClass && JUnitUtil.isTestClass((PsiClass)element, false, true)) { + return new RunLineMarkerInfo(e, JUnitConfigurationType.getInstance().getIcon(), TOOLTIP_PROVIDER); + } + if (element instanceof PsiMethod && JUnitUtil.isTestMethod(new PsiLocation((PsiMethod)element))) { + return new RunLineMarkerInfo(e, JUnitConfigurationType.getInstance().getIcon(), TOOLTIP_PROVIDER); + } + } return null; - } @Override diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenPluginCompletionAndResolutionTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenPluginCompletionAndResolutionTest.java index 827f5acda464..237d5387281b 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenPluginCompletionAndResolutionTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenPluginCompletionAndResolutionTest.java @@ -15,7 +15,6 @@ */ package org.jetbrains.idea.maven.dom; -import com.intellij.idea.Bombed; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; @@ -25,7 +24,6 @@ import com.intellij.psi.xml.XmlTag; import org.jetbrains.idea.maven.indices.MavenIndicesTestFixture; import java.io.IOException; -import java.util.Calendar; import java.util.List; public class MavenPluginCompletionAndResolutionTest extends MavenDomWithIndicesTestCase { @@ -43,7 +41,6 @@ public class MavenPluginCompletionAndResolutionTest extends MavenDomWithIndicesT "1"); } - @Bombed(year = 2014, month = Calendar.APRIL, day = 25, user = "sergey.evdokimov") public void testGroupIdCompletion() throws Exception { createProjectPom("test" + "project" + @@ -60,7 +57,6 @@ public class MavenPluginCompletionAndResolutionTest extends MavenDomWithIndicesT assertCompletionVariants(myProjectPom, "org.codehaus.plexus", "intellij.test", "test", "org.apache.maven.plugins", "org.codehaus.mojo"); } - @Bombed(year = 2013, month = Calendar.APRIL, day = 25, user = "sergey.evdokimov") public void testArtifactIdCompletion() throws Exception { createProjectPom("test" + "project" + @@ -96,7 +92,6 @@ public class MavenPluginCompletionAndResolutionTest extends MavenDomWithIndicesT assertCompletionVariants(myProjectPom, "2.0.2"); } - @Bombed(year = 2013, month = Calendar.APRIL, day = 25, user = "sergey.evdokimov") public void testArtifactWithoutGroupCompletion() throws Exception { createProjectPom("test" + "project" + @@ -823,7 +818,6 @@ public class MavenPluginCompletionAndResolutionTest extends MavenDomWithIndicesT assertCompletionVariants(myProjectPom); } - @Bombed(year = 2014, month = Calendar.MARCH, day = 25, user = "sergey.evdokimov") public void testDocumentationForParameter() throws Exception { createProjectPom("test" + "project" + diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/PropertiesImplUtil.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/PropertiesImplUtil.java index a61509234792..12d3362f33c4 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/PropertiesImplUtil.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/PropertiesImplUtil.java @@ -26,6 +26,7 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.psi.PsiDirectory; +import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.search.GlobalSearchScope; @@ -122,6 +123,12 @@ public class PropertiesImplUtil extends PropertiesUtil { return file instanceof PropertiesFile ? (PropertiesFile)file : XmlPropertiesFileImpl.getPropertiesFile(file); } + @Nullable + public static PropertiesFile getPropertiesFile(@Nullable PsiElement element) { + if (!(element instanceof PsiFile)) return null; + return getPropertiesFile((PsiFile)element); + } + @NotNull public static List findPropertiesByKey(@NotNull final Project project, @NotNull final String key) { final GlobalSearchScope scope = GlobalSearchScope.allScope(project); diff --git a/plugins/properties/src/com/intellij/lang/properties/customizeActions/CombinePropertiesFilesAction.java b/plugins/properties/src/com/intellij/lang/properties/customizeActions/CombinePropertiesFilesAction.java index b90e74a2c767..35264b2f5697 100644 --- a/plugins/properties/src/com/intellij/lang/properties/customizeActions/CombinePropertiesFilesAction.java +++ b/plugins/properties/src/com/intellij/lang/properties/customizeActions/CombinePropertiesFilesAction.java @@ -32,11 +32,10 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.InputValidatorEx; import com.intellij.openapi.ui.Messages; import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.List; +import java.util.*; /** * @author Dmitry Batkovich @@ -49,7 +48,16 @@ public class CombinePropertiesFilesAction extends AnAction { @Override public void actionPerformed(final AnActionEvent e) { - final List propertiesFiles = getPropertiesFiles(e); + final List initialPropertiesFiles = getPropertiesFiles(e); + final List propertiesFiles = initialPropertiesFiles == null ? new ArrayList() + : new ArrayList(initialPropertiesFiles); + final List resourceBundles = getResourceBundles(e); + if (resourceBundles != null) { + for (ResourceBundle bundle : resourceBundles) { + propertiesFiles.addAll(bundle.getPropertiesFiles()); + } + } + final String newBaseName = Messages.showInputDialog(propertiesFiles.get(0).getProject(), PropertiesBundle.message("combine.properties.files.prompt.text"), PropertiesBundle.message("combine.properties.files.title"), @@ -58,7 +66,20 @@ public class CombinePropertiesFilesAction extends AnAction { new MyInputValidator(propertiesFiles)); if (newBaseName != null) { final Project project = propertiesFiles.get(0).getProject(); - ResourceBundleManager.getInstance(project).combineToResourceBundle(propertiesFiles, newBaseName); + + final Set uniqueBundlesToDissociate = new HashSet(); + for (PropertiesFile file : propertiesFiles) { + final ResourceBundle resourceBundle = file.getResourceBundle(); + if (resourceBundle.getPropertiesFiles().size() != 1) { + uniqueBundlesToDissociate.add(resourceBundle); + } + } + final ResourceBundleManager resourceBundleManager = ResourceBundleManager.getInstance(project); + for (ResourceBundle resourceBundle : uniqueBundlesToDissociate) { + resourceBundleManager.dissociateResourceBundle(resourceBundle); + } + + resourceBundleManager.combineToResourceBundle(propertiesFiles, newBaseName); final ResourceBundle resourceBundle = propertiesFiles.get(0).getResourceBundle(); FileEditorManager.getInstance(project).openFile(new ResourceBundleAsVirtualFile(resourceBundle), true); ProjectView.getInstance(project).refresh(); @@ -67,17 +88,22 @@ public class CombinePropertiesFilesAction extends AnAction { @Override public void update(final AnActionEvent e) { - final List propertiesFiles = getPropertiesFiles(e); - boolean isAvailable = propertiesFiles != null && propertiesFiles.size() > 1; - if (isAvailable) { - for (PropertiesFile propertiesFile : propertiesFiles) { - if (propertiesFile.getResourceBundle().getPropertiesFiles().size() != 1) { - isAvailable = false; - break; - } - } + final Collection propertiesFiles = getPropertiesFiles(e); + final List resourceBundles = getResourceBundles(e); + int elementCount = 0; + if (propertiesFiles != null) { + elementCount += propertiesFiles.size(); } - e.getPresentation().setVisible(isAvailable); + if (resourceBundles != null) { + elementCount += resourceBundles.size(); + } + e.getPresentation().setEnabledAndVisible(elementCount > 1); + } + + @Nullable + private static List getResourceBundles(AnActionEvent e) { + final ResourceBundle[] resourceBundles = e.getData(ResourceBundle.ARRAY_DATA_KEY); + return resourceBundles == null ? null : ContainerUtil.newArrayList(resourceBundles); } @Nullable @@ -88,10 +114,7 @@ public class CombinePropertiesFilesAction extends AnAction { } final List files = new ArrayList(psiElements.length); for (PsiElement psiElement : psiElements) { - if (!(psiElement instanceof PsiFile)) { - return null; - } - final PropertiesFile propertiesFile = PropertiesImplUtil.getPropertiesFile((PsiFile)psiElement); + final PropertiesFile propertiesFile = PropertiesImplUtil.getPropertiesFile(psiElement); if (propertiesFile == null) { return null; } diff --git a/plugins/properties/src/com/intellij/lang/properties/customizeActions/DissociateResourceBundleAction.java b/plugins/properties/src/com/intellij/lang/properties/customizeActions/DissociateResourceBundleAction.java index 7c6590634698..43b87266d475 100644 --- a/plugins/properties/src/com/intellij/lang/properties/customizeActions/DissociateResourceBundleAction.java +++ b/plugins/properties/src/com/intellij/lang/properties/customizeActions/DissociateResourceBundleAction.java @@ -31,14 +31,13 @@ import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileSystemItem; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashSet; import org.jetbrains.annotations.NotNull; -import javax.swing.*; -import java.util.*; +import java.util.Collection; +import java.util.Set; /** * @author Dmitry Batkovich @@ -116,13 +115,11 @@ public class DissociateResourceBundleAction extends AnAction { final PsiElement[] psiElements = event.getData(LangDataKeys.PSI_ELEMENT_ARRAY); if (psiElements != null) { for (PsiElement element : psiElements) { - if (element instanceof PsiFile) { - final PropertiesFile propertiesFile = PropertiesImplUtil.getPropertiesFile((PsiFile)element); - if (propertiesFile != null) { - final ResourceBundle bundle = propertiesFile.getResourceBundle(); - if (bundle.getPropertiesFiles().size() > 1) { - targetResourceBundles.add(bundle); - } + final PropertiesFile propertiesFile = PropertiesImplUtil.getPropertiesFile(element); + if (propertiesFile != null) { + final ResourceBundle bundle = propertiesFile.getResourceBundle(); + if (bundle.getPropertiesFiles().size() > 1) { + targetResourceBundles.add(bundle); } } } diff --git a/plugins/properties/src/com/intellij/lang/properties/editor/NewPropertyAction.java b/plugins/properties/src/com/intellij/lang/properties/editor/NewPropertyAction.java index 80d8be9974cb..4bad9e837f41 100644 --- a/plugins/properties/src/com/intellij/lang/properties/editor/NewPropertyAction.java +++ b/plugins/properties/src/com/intellij/lang/properties/editor/NewPropertyAction.java @@ -22,7 +22,7 @@ import com.intellij.lang.properties.psi.PropertiesFile; import com.intellij.lang.properties.structureView.PropertiesPrefixGroup; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.command.CommandProcessor; +import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; @@ -148,11 +148,10 @@ class NewPropertyAction extends AnAction { } } - final PropertiesFile defaultPropertiesFile = resourceBundle.getDefaultPropertiesFile(); ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { - CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() { + WriteCommandAction.runWriteCommandAction(resourceBundle.getProject(), new Runnable() { @Override public void run() { myResourceBundleEditor.getPropertiesInsertDeleteManager().insertNewProperty(newPropertyName, ""); diff --git a/plugins/terminal/resources/META-INF/terminal.xml b/plugins/terminal/resources/META-INF/terminal.xml index c91a17d76f91..4d8550d94892 100644 --- a/plugins/terminal/resources/META-INF/terminal.xml +++ b/plugins/terminal/resources/META-INF/terminal.xml @@ -6,6 +6,8 @@ + + diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java index 8521de83d42e..bc131af62ade 100644 --- a/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java +++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * 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. @@ -156,13 +156,10 @@ public class LocalTerminalDirectRunner extends AbstractTerminalRunner() { + ProcessWaitFor.attach(myProcess, new Consumer() { @Override public void consume(Integer integer) { notifyProcessTerminated(integer); diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/cloud/CloudTerminalProcess.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/cloud/CloudTerminalProcess.java new file mode 100644 index 000000000000..05df756ec393 --- /dev/null +++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/cloud/CloudTerminalProcess.java @@ -0,0 +1,65 @@ +/* + * 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. + */ +package org.jetbrains.plugins.terminal.cloud; + +import java.io.InputStream; +import java.io.OutputStream; + +public class CloudTerminalProcess extends Process { + + private final OutputStream myOutputStream; + private final InputStream myInputStream; + + private boolean myRunning = true; + + public CloudTerminalProcess(OutputStream terminalInput, InputStream terminalOutput) { + myOutputStream = terminalInput; + myInputStream = terminalOutput; + } + + @Override + public OutputStream getOutputStream() { + return myOutputStream; + } + + @Override + public InputStream getInputStream() { + return myInputStream; + } + + @Override + public InputStream getErrorStream() { + return null; + } + + @Override + public int waitFor() throws InterruptedException { + while (myRunning) { + Thread.sleep(100); + } + return exitValue(); + } + + @Override + public int exitValue() { + return 0; + } + + @Override + public void destroy() { + myRunning = true; + } +} diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/cloud/CloudTerminalProviderImpl.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/cloud/CloudTerminalProviderImpl.java new file mode 100644 index 000000000000..80d326507447 --- /dev/null +++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/cloud/CloudTerminalProviderImpl.java @@ -0,0 +1,40 @@ +/* + * 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. + */ +package org.jetbrains.plugins.terminal.cloud; + +import com.intellij.openapi.project.Project; +import com.intellij.remoteServer.impl.runtime.log.CloudTerminalProvider; +import com.intellij.remoteServer.impl.runtime.log.LoggingHandlerBase; +import org.jetbrains.annotations.NotNull; + +import java.io.InputStream; +import java.io.OutputStream; + +public class CloudTerminalProviderImpl implements CloudTerminalProvider { + + @Override + public LoggingHandlerBase createTerminal(@NotNull String presentableName, + @NotNull Project project, + @NotNull InputStream terminalOutput, + @NotNull OutputStream terminalInput) { + return new TerminalHandlerImpl(presentableName, project, terminalOutput, terminalInput); + } + + @Override + public boolean isTtySupported() { + return true; + } +} diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/cloud/CloudTerminalRunner.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/cloud/CloudTerminalRunner.java new file mode 100644 index 000000000000..61174b2832e0 --- /dev/null +++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/cloud/CloudTerminalRunner.java @@ -0,0 +1,102 @@ +/* + * 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. + */ +package org.jetbrains.plugins.terminal.cloud; + +import com.intellij.execution.process.ProcessHandler; +import com.intellij.openapi.project.Project; +import com.jediterm.terminal.ProcessTtyConnector; +import com.jediterm.terminal.TtyConnector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.plugins.terminal.AbstractTerminalRunner; + +import java.io.OutputStream; +import java.nio.charset.Charset; +import java.util.concurrent.ExecutionException; + +public class CloudTerminalRunner extends AbstractTerminalRunner { + private final String myPipeName; + private CloudTerminalProcess myProcess; + + public CloudTerminalRunner(@NotNull Project project, String pipeName, CloudTerminalProcess process) { + super(project); + myPipeName = pipeName; + myProcess = process; + } + + @Override + protected CloudTerminalProcess createProcess(@Nullable String directory) throws ExecutionException { + return myProcess; + } + + @Override + protected ProcessHandler createProcessHandler(final CloudTerminalProcess process) { + return new ProcessHandler() { + + @Override + protected void destroyProcessImpl() { + process.destroy(); + } + + @Override + protected void detachProcessImpl() { + process.destroy(); + } + + @Override + public boolean detachIsDefault() { + return false; + } + + @Nullable + @Override + public OutputStream getProcessInput() { + return process.getOutputStream(); + } + }; + } + + @Override + protected String getTerminalConnectionName(CloudTerminalProcess process) { + return "Terminal: " + myPipeName; + } + + @Override + protected TtyConnector createTtyConnector(CloudTerminalProcess process) { + return new ProcessTtyConnector(process, Charset.defaultCharset()) { + + @Override + protected void resizeImmediately() { + + } + + @Override + public String getName() { + return "Connector: " + myPipeName; + } + + @Override + public boolean isConnected() { + return true; + } + }; + } + + @Override + public String runningTargetName() { + return "Cloud terminal"; + } +} diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/cloud/TerminalHandlerImpl.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/cloud/TerminalHandlerImpl.java new file mode 100644 index 000000000000..12a898a8dde4 --- /dev/null +++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/cloud/TerminalHandlerImpl.java @@ -0,0 +1,48 @@ +/* + * 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. + */ +package org.jetbrains.plugins.terminal.cloud; + +import com.intellij.openapi.project.Project; +import com.intellij.remoteServer.impl.runtime.log.LoggingHandlerBase; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.plugins.terminal.JBTabbedTerminalWidget; + +import javax.swing.*; +import java.io.InputStream; +import java.io.OutputStream; + +public class TerminalHandlerImpl extends LoggingHandlerBase { + + private final JBTabbedTerminalWidget myTerminalWidget; + + public TerminalHandlerImpl(@NotNull String presentableName, + @NotNull Project project, + @NotNull InputStream terminalOutput, + @NotNull OutputStream terminalInput) { + super(presentableName); + + final CloudTerminalProcess process = new CloudTerminalProcess(terminalInput, terminalOutput); + + CloudTerminalRunner terminalRunner = new CloudTerminalRunner(project, presentableName, process); + + myTerminalWidget = terminalRunner.createTerminalWidget(project); + } + + @Override + public JComponent getComponent() { + return myTerminalWidget.getComponent(); + } +} diff --git a/plugins/terminal/terminal.iml b/plugins/terminal/terminal.iml index 7b4c13d4c09f..622ab8978555 100644 --- a/plugins/terminal/terminal.iml +++ b/plugins/terminal/terminal.iml @@ -23,6 +23,7 @@ + + - - + \ No newline at end of file diff --git a/python/edu/interactive-learning-python/interactive-learning-python.iml b/python/edu/interactive-learning-python/interactive-learning-python.iml index e92551376fe3..1d2fc6ad288e 100644 --- a/python/edu/interactive-learning-python/interactive-learning-python.iml +++ b/python/edu/interactive-learning-python/interactive-learning-python.iml @@ -5,7 +5,7 @@ - + @@ -15,16 +15,8 @@ - - - - - - - - - + \ No newline at end of file diff --git a/python/edu/interactive-learning-python/tests/JsonParserTest.java b/python/edu/interactive-learning-python/tests/JsonParserTest.java index 5cba837b2bcf..42ac11d1eb37 100644 --- a/python/edu/interactive-learning-python/tests/JsonParserTest.java +++ b/python/edu/interactive-learning-python/tests/JsonParserTest.java @@ -1,3 +1,5 @@ +package com.jetbrains.edu.learning; + import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -33,6 +35,6 @@ public class JsonParserTest extends TestCase { assertEquals(myCourse.getLessons().get(1).getTaskList().size(), 1); } protected String getTestDataPath() { - return PythonHelpersLocator.getPythonCommunityPath() + "/edu/learn-python/testData"; + return PythonHelpersLocator.getPythonCommunityPath() + "/edu/interactive-learning-python/testData"; } } diff --git a/python/edu/interactive-learning-python/tests/StudyDocumentListenerTest.java b/python/edu/interactive-learning-python/tests/StudyDocumentListenerTest.java index dc6c2a496dab..996536f4bf7b 100644 --- a/python/edu/interactive-learning-python/tests/StudyDocumentListenerTest.java +++ b/python/edu/interactive-learning-python/tests/StudyDocumentListenerTest.java @@ -1,3 +1,5 @@ +package com.jetbrains.edu.learning; + import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.Document; diff --git a/python/edu/interactive-learning-python/tests/StudyTestCase.java b/python/edu/interactive-learning-python/tests/StudyTestCase.java index 39bc30c165eb..c822fb869073 100644 --- a/python/edu/interactive-learning-python/tests/StudyTestCase.java +++ b/python/edu/interactive-learning-python/tests/StudyTestCase.java @@ -1,3 +1,5 @@ +package com.jetbrains.edu.learning; + import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.UsefulTestCase; import com.intellij.testFramework.fixtures.CodeInsightTestFixture; diff --git a/python/educational/interactive-learning/src/com/jetbrains/edu/learning/StudyTaskManager.java b/python/educational/interactive-learning/src/com/jetbrains/edu/learning/StudyTaskManager.java index 43de59f09bad..1722e67aedfa 100644 --- a/python/educational/interactive-learning/src/com/jetbrains/edu/learning/StudyTaskManager.java +++ b/python/educational/interactive-learning/src/com/jetbrains/edu/learning/StudyTaskManager.java @@ -1,12 +1,6 @@ package com.jetbrains.edu.learning; -import com.intellij.openapi.components.PersistentStateComponent; -import com.intellij.openapi.components.State; -import com.intellij.openapi.components.Storage; -import com.intellij.openapi.components.StorageScheme; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleManager; -import com.intellij.openapi.module.ModuleServiceManager; +import com.intellij.openapi.components.*; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.ui.JBColor; @@ -31,9 +25,9 @@ import java.util.Map; @State( name = "StudySettings", storages = { + @Storage(file = StoragePathMacros.PROJECT_FILE), @Storage( - id = "others", - file = "$PROJECT_CONFIG_DIR$/study_project.xml", + file = StoragePathMacros.PROJECT_CONFIG_DIR + "/study_project.xml", scheme = StorageScheme.DIRECTORY_BASED )} ) @@ -176,8 +170,6 @@ public class StudyTaskManager implements PersistentStateComponent parameters = new ArrayList(); - for (PyParameter parameter: baseParams) { + for (PyParameter parameter : baseParams) { final PyNamedParameter pyNamedParameter = parameter.getAsNamed(); if (pyNamedParameter != null) { String repr = pyNamedParameter.getRepr(false); @@ -244,7 +249,7 @@ public class PyOverrideImplementUtil { PsiElement outerClass = PsiTreeUtil.getParentOfType(pyClass, PyClass.class, true, PyFunction.class); String className = pyClass.getName(); final List nameResult = Lists.newArrayList(className); - while(outerClass != null) { + while (outerClass != null) { nameResult.add(0, ((PyClass)outerClass).getName()); outerClass = PsiTreeUtil.getParentOfType(outerClass, PyClass.class, true, PyFunction.class); } @@ -297,7 +302,7 @@ public class PyOverrideImplementUtil { final PyExpression[] superClassExpressions = fromClass.getSuperClassExpressions(); for (PyExpression expression : superClassExpressions) { if (expression instanceof PyReferenceExpression) { - PsiElement target = ((PyReferenceExpression) expression).getReference().resolve(); + PsiElement target = ((PyReferenceExpression)expression).getReference().resolve(); if (target == toClass) { return expression.getText(); } @@ -307,13 +312,57 @@ public class PyOverrideImplementUtil { } @NotNull - public static Collection getAllSuperFunctions(@NotNull PyClass pyClass) { + public static Collection getAllSuperFunctions(@NotNull final PyClass pyClass) { final Map superFunctions = new HashMap(); - for (PyFunction function : pyClass.getMethods(true)) { + for (final PyFunction function : ArrayUtil.mergeArrays(pyClass.getMethods(true), getCalculatedParentMethods(pyClass))) { if (!superFunctions.containsKey(function.getName())) { superFunctions.put(function.getName(), function); } } return superFunctions.values(); } + + + /** + * Since some classes inherit from {@link PyClassLikeType} they have no {@link PyClass} parent, hence have no + * {@link PyClass#getMethods(boolean)}. But they still do have some methods, and such methods should also be overwritable. + *

+ * This method fetches all methods, provided by parents regardless their type, and returns them. + * + * @param pyClass class to get parent methods from + * @return parent methods + */ + @NotNull + private static PyFunction[] getCalculatedParentMethods(@NotNull final PyClass pyClass) { + final TypeEvalContext context = TypeEvalContext.deepCodeInsight(pyClass.getProject()); + final PyClassLikeType type = PyUtil.as(context.getType(pyClass), PyClassLikeType.class); + if (type == null) { + return PyFunction.EMPTY_ARRAY; + } + + final List result = new ArrayList(); + /** + * Ideally there has to be

getMembers
method in {@link PyClassLikeType}, but there is no such method for now, + * and it can't be added easily due to huge refactoring {@link com.jetbrains.python.psi.types.PyClassTypeImpl} should have + * to fetch members from parents as well: + * See ({@link com.jetbrains.python.psi.types.PyClassTypeImpl#addInheritedMembers(String, PsiElement, Set, ProcessingContext, List, TypeEvalContext)} + * It is tied to completion, but contains required logic. + * + * For now, we use {@link PyClassLikeType#getCompletionVariants(String, PsiElement, ProcessingContext)} as temporary hack. + */ + // TODO: Use "getMembers" instead of "getCompletionVariants" hack. + for (final Object completion : type.getCompletionVariants("", null, new ProcessingContext())) { + // It could be PyFunction itself or lookup element with function + if (completion instanceof PyFunction) { + result.add((PyFunction)completion); + } + else if (completion instanceof LookupElement) { + final PyFunction element = PyUtil.as(((LookupElement)completion).getPsiElement(), PyFunction.class); + if (element != null) { + result.add(element); + } + } + } + return result.toArray(new PyFunction[result.size()]); + } } diff --git a/python/src/com/jetbrains/python/run/PythonTask.java b/python/src/com/jetbrains/python/run/PythonTask.java index bddb96fc3333..3ddd6a30969e 100644 --- a/python/src/com/jetbrains/python/run/PythonTask.java +++ b/python/src/com/jetbrains/python/run/PythonTask.java @@ -35,6 +35,7 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.NotNullFunction; import com.jetbrains.python.PyBundle; import com.jetbrains.python.buildout.BuildoutFacet; +import com.jetbrains.python.console.PydevConsoleRunner; import com.jetbrains.python.sdk.PySdkUtil; import com.jetbrains.python.sdk.PythonEnvUtil; import com.jetbrains.python.sdk.PythonSdkType; @@ -109,6 +110,7 @@ public class PythonTask { if (env != null) { commandLine.getEnvironment().putAll(env); } + PydevConsoleRunner.setCorrectStdOutEncoding(commandLine.getEnvironment(), myModule.getProject()); // To support UTF-8 output ProcessHandler handler; if (PySdkUtil.isRemote(mySdk)) { diff --git a/xml/impl/src/com/intellij/ide/browsers/actions/BaseOpenInBrowserAction.java b/xml/impl/src/com/intellij/ide/browsers/actions/BaseOpenInBrowserAction.java index bdf5faa321bb..2c50377e2af5 100644 --- a/xml/impl/src/com/intellij/ide/browsers/actions/BaseOpenInBrowserAction.java +++ b/xml/impl/src/com/intellij/ide/browsers/actions/BaseOpenInBrowserAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * 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. @@ -30,7 +30,6 @@ import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.popup.JBPopupFactory; -import com.intellij.openapi.util.AsyncResult; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; @@ -45,6 +44,8 @@ import com.intellij.util.containers.ContainerUtil; import com.intellij.xml.util.HtmlUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.concurrency.AsyncPromise; +import org.jetbrains.concurrency.Promise; import javax.swing.*; import java.awt.event.InputEvent; @@ -167,13 +168,14 @@ public abstract class BaseOpenInBrowserAction extends DumbAwareAction { try { Collection urls = WebBrowserService.getInstance().getUrlsToOpen(request, preferLocalUrl); if (!urls.isEmpty()) { - chooseUrl(urls).doWhenDone(new Consumer() { - @Override - public void consume(Url url) { - ApplicationManager.getApplication().saveAll(); - BrowserLauncher.getInstance().browse(url.toExternalForm(), browser, request.getProject()); - } - }); + chooseUrl(urls) + .done(new Consumer() { + @Override + public void consume(Url url) { + ApplicationManager.getApplication().saveAll(); + BrowserLauncher.getInstance().browse(url.toExternalForm(), browser, request.getProject()); + } + }); } } catch (WebBrowserUrlProvider.BrowserException e1) { @@ -185,9 +187,9 @@ public abstract class BaseOpenInBrowserAction extends DumbAwareAction { } @NotNull - private static AsyncResult chooseUrl(@NotNull Collection urls) { + private static Promise chooseUrl(@NotNull Collection urls) { if (urls.size() == 1) { - return new AsyncResult.Done(ContainerUtil.getFirstItem(urls)); + return Promise.resolve(ContainerUtil.getFirstItem(urls)); } final JBList list = new JBList(urls); @@ -200,23 +202,24 @@ public abstract class BaseOpenInBrowserAction extends DumbAwareAction { } }); - final AsyncResult result = new AsyncResult(); - JBPopupFactory.getInstance(). - createListPopupBuilder(list). - setTitle("Choose Url"). - setItemChoosenCallback(new Runnable() { + final AsyncPromise result = new AsyncPromise(); + JBPopupFactory.getInstance() + .createListPopupBuilder(list) + .setTitle("Choose Url") + .setItemChoosenCallback(new Runnable() { @Override public void run() { Url value = (Url)list.getSelectedValue(); - if (value != null) { - result.setDone(value); + if (value == null) { + result.setError(Promise.createError("selected value is null")); } else { - result.setRejected(); + result.setResult(value); } } - }). - createPopup().showInFocusCenter(); + }) + .createPopup() + .showInFocusCenter(); return result; } } \ No newline at end of file diff --git a/xml/relaxng/lib/rngom-20051226-patched.jar b/xml/relaxng/lib/rngom-20051226-patched.jar index 68cad0271595..3bc509bb967c 100644 Binary files a/xml/relaxng/lib/rngom-20051226-patched.jar and b/xml/relaxng/lib/rngom-20051226-patched.jar differ diff --git a/xml/relaxng/lib/rngom-src.zip b/xml/relaxng/lib/rngom-src.zip index 4b660e99def5..d316d6f1c653 100644 Binary files a/xml/relaxng/lib/rngom-src.zip and b/xml/relaxng/lib/rngom-src.zip differ diff --git a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlDocumentImpl.java b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlDocumentImpl.java index 00a7e9c4afc4..c3328dd9f9f3 100644 --- a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlDocumentImpl.java +++ b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlDocumentImpl.java @@ -41,6 +41,7 @@ import com.intellij.psi.tree.ChildRoleBase; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.CachedValue; import com.intellij.psi.util.CachedValueProvider; +import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.xml.*; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ContainerUtil; @@ -237,6 +238,17 @@ public class XmlDocumentImpl extends XmlElementImpl implements XmlDocument { } nsDescriptor = getDefaultNSDescriptor(htmlns, false); } + final XmlFile descriptorFile = nsDescriptor.getDescriptorFile(); + if (descriptorFile != null) { + final XmlNSDescriptor finalNsDescriptor = nsDescriptor; + return CachedValuesManager.getCachedValue(descriptorFile, new CachedValueProvider() { + @Nullable + @Override + public Result compute() { + return Result.create(new HtmlNSDescriptorImpl(finalNsDescriptor), descriptorFile); + } + }); + } return new HtmlNSDescriptorImpl(nsDescriptor); } else if (XmlUtil.XHTML_URI.equals(namespace)) {