Merge remote-tracking branch 'origin/master'

This commit is contained in:
Yann Cébron
2015-03-31 22:27:42 +02:00
104 changed files with 1396 additions and 775 deletions
@@ -886,11 +886,17 @@ public class HighlightUtil extends HighlightUtilBase {
isAllowed = false;
}
if (PsiModifier.PRIVATE.equals(modifier) || PsiModifier.PROTECTED.equals(modifier) || PsiModifier.TRANSIENT.equals(modifier) ||
PsiModifier.STRICTFP.equals(modifier) || PsiModifier.SYNCHRONIZED.equals(modifier)) {
if (PsiModifier.PRIVATE.equals(modifier)) {
isAllowed &= modifierOwnerParent instanceof PsiClass &&
(!((PsiClass)modifierOwnerParent).isInterface() || PsiUtil.isLanguageLevel9OrHigher(modifierOwner));
}
else if (PsiModifier.STRICTFP.equals(modifier)) {
isAllowed &= modifierOwnerParent instanceof PsiClass && (!((PsiClass)modifierOwnerParent).isInterface() || PsiUtil.isLanguageLevel8OrHigher(modifierOwner));
}
else if (PsiModifier.PROTECTED.equals(modifier) || PsiModifier.TRANSIENT.equals(modifier) ||
PsiModifier.SYNCHRONIZED.equals(modifier)) {
isAllowed &= modifierOwnerParent instanceof PsiClass && !((PsiClass)modifierOwnerParent).isInterface();
}
if (containingClass != null && containingClass.isAnnotationType()) {
isAllowed &= !PsiModifier.STATIC.equals(modifier);
@@ -238,10 +238,10 @@ public class AnonymousCanBeLambdaInspection extends BaseJavaBatchLocalInspection
final ForbiddenRefsChecker checker = new ForbiddenRefsChecker(method, anonymousClass);
body.accept(checker);
PsiResolveHelper helper = PsiResolveHelper.SERVICE.getInstance(body.getProject());
final Set<PsiLocalVariable> conflictingLocals = checker.getLocals();
for (Iterator<PsiLocalVariable> iterator = conflictingLocals.iterator(); iterator.hasNext(); ) {
PsiLocalVariable local = iterator.next();
final PsiResolveHelper helper = PsiResolveHelper.SERVICE.getInstance(body.getProject());
final Set<PsiVariable> conflictingLocals = checker.getLocals();
for (Iterator<PsiVariable> iterator = conflictingLocals.iterator(); iterator.hasNext(); ) {
PsiVariable local = iterator.next();
final String localName = local.getName();
if (localName == null || helper.resolveReferencedVariable(localName, anonymousClass) == null) {
iterator.remove();
@@ -252,7 +252,7 @@ public class AnonymousCanBeLambdaInspection extends BaseJavaBatchLocalInspection
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
ReplaceWithLambdaFix
.giveUniqueNames(project, lambdaContext, elementFactory, body, conflictingLocals.toArray(new PsiVariable[conflictingLocals.size()]));
.giveUniqueNames(project, anonymousClass, elementFactory, body, conflictingLocals.toArray(new PsiVariable[conflictingLocals.size()]));
final String lambdaWithTypesDeclared = ReplaceWithLambdaFix.composeLambdaText(method, true);
final String withoutTypesDeclared = ReplaceWithLambdaFix.composeLambdaText(method, false);
@@ -350,7 +350,7 @@ public class AnonymousCanBeLambdaInspection extends BaseJavaBatchLocalInspection
final Map<PsiVariable, String> names = new HashMap<PsiVariable, String>();
for (PsiVariable parameter : parameters) {
String parameterName = parameter.getName();
final String uniqueVariableName = codeStyleManager.suggestUniqueVariableName(parameterName, lambdaContext, false);
final String uniqueVariableName = codeStyleManager.suggestUniqueVariableName(parameterName, parameter.getParent(), false);
if (!Comparing.equal(parameterName, uniqueVariableName)) {
names.put(parameter, uniqueVariableName);
}
@@ -451,7 +451,7 @@ public class AnonymousCanBeLambdaInspection extends BaseJavaBatchLocalInspection
private static class ForbiddenRefsChecker extends JavaRecursiveElementWalkingVisitor {
private boolean myBodyContainsForbiddenRefs;
private final Set<PsiLocalVariable> myLocals = ContainerUtilRt.newHashSet(5);
private final Set<PsiVariable> myLocals = ContainerUtilRt.newHashSet(5);
private final PsiMethod myMethod;
private final PsiAnonymousClass myAnonymClass;
@@ -502,11 +502,13 @@ public class AnonymousCanBeLambdaInspection extends BaseJavaBatchLocalInspection
}
@Override
public void visitLocalVariable(PsiLocalVariable variable) {
public void visitVariable(PsiVariable variable) {
if (myBodyContainsForbiddenRefs) return;
super.visitLocalVariable(variable);
myLocals.add(variable);
super.visitVariable(variable);
if (!(variable instanceof PsiField)) {
myLocals.add(variable);
}
}
@Override
@@ -590,7 +592,7 @@ public class AnonymousCanBeLambdaInspection extends BaseJavaBatchLocalInspection
return myBodyContainsForbiddenRefs;
}
public Set<PsiLocalVariable> getLocals() {
public Set<PsiVariable> getLocals() {
return myLocals;
}
}
@@ -340,6 +340,9 @@ public class LambdaUtil {
if (gParent instanceof PsiCall) {
final PsiCall contextCall = (PsiCall)gParent;
final MethodCandidateInfo.CurrentCandidateProperties properties = MethodCandidateInfo.getCurrentMethod(contextCall.getArgumentList());
if (MethodCandidateInfo.isOverloadCheck()) {
MethodCandidateInfo.ourOverloadGuard.prohibitResultCaching(MethodCandidateInfo.ourOverloadGuard.currentStack().get(0));
}
if (properties != null && properties.isApplicabilityCheck()) { //todo simplification
final PsiParameter[] parameters = properties.getMethod().getParameterList().getParameters();
final int finalLambdaIdx = adjustLambdaIdx(lambdaIdx, properties.getMethod(), parameters);
@@ -326,9 +326,6 @@ public class MethodCandidateInfo extends CandidateInfo{
public static CurrentCandidateProperties getCurrentMethod(PsiElement context) {
if (isOverloadCheck()) {
ourOverloadGuard.prohibitResultCaching(ourOverloadGuard.currentStack().get(0));
}
final Map<PsiElement, CurrentCandidateProperties> currentMethodCandidates = CURRENT_CANDIDATE.get();
return currentMethodCandidates != null ? currentMethodCandidates.get(context) : null;
}
@@ -364,14 +364,6 @@ public class JavaDocUtil {
}
public static boolean isInsidePackageInfo(@Nullable PsiDocComment containingComment) {
if (containingComment == null || containingComment.getOwner() != null) {
return false;
}
final PsiElement parent = containingComment.getParent();
if (!(parent instanceof PsiJavaFile)) {
return false;
}
final PsiJavaFile file = (PsiJavaFile)parent;
return "package-info.java".equals(file.getName());
return containingComment != null && containingComment.getOwner() == null && containingComment.getParent() instanceof PsiJavaFile;
}
}
@@ -34,7 +34,10 @@ import com.intellij.psi.scope.NameHint;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.scope.processor.FilterScopeProcessor;
import com.intellij.psi.scope.processor.MethodResolverProcessor;
import com.intellij.psi.search.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.PackageScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.util.*;
import com.intellij.ui.IconDeferrer;
import com.intellij.ui.RowIcon;
@@ -711,54 +714,12 @@ public class PsiClassImplUtil {
}
@Nullable
public static PsiClassType correctType(PsiClassType originalType, final GlobalSearchScope resolveScope) {
if (!Registry.is("java.correct.class.type.by.place.resolve.scope")) {
public static <T extends PsiType> T correctType(@Nullable final T originalType, @NotNull final GlobalSearchScope resolveScope) {
if (originalType == null || !Registry.is("java.correct.class.type.by.place.resolve.scope")) {
return originalType;
}
final PsiClassType.ClassResolveResult originalResolveResult = originalType.resolveGenerics();
PsiClass superClass = originalResolveResult.getElement();
if (superClass == null) {
return originalType;
}
String qualifiedName = superClass.getQualifiedName();
if (qualifiedName != null && !PsiSearchScopeUtil.isInScope(resolveScope, superClass)) {
final PsiFile file = superClass.getContainingFile();
if (file == null || !file.getViewProvider().isPhysical()) {
return originalType;
}
PsiClass originalSuperClass = superClass;
PsiSubstitutor originalSubstitutor = originalResolveResult.getSubstitutor();
superClass = JavaPsiFacade.getInstance(superClass.getProject()).findClass(qualifiedName, resolveScope);
if (superClass == null) {
return null;
}
PsiTypeParameter[] typeParameters = superClass.getTypeParameters();
PsiTypeParameter[] originalTypeParameters = originalSuperClass.getTypeParameters();
if (typeParameters.length != originalTypeParameters.length) return null;
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
for (int i = 0; i < originalTypeParameters.length; i++) {
PsiType originalSubstitute = originalSubstitutor.substitute(originalTypeParameters[i]);
if (originalSubstitute != null) {
PsiType substitute = originalSubstitute.accept(new PsiTypeVisitor<PsiType>() {
@Nullable
@Override
public PsiType visitClassType(PsiClassType classType) {
return correctType(classType, resolveScope);
}
});
if (substitute == null) return null;
substitutor = substitutor.put(typeParameters[i], substitute);
}
}
return JavaPsiFacade.getElementFactory(superClass.getProject()).createType(superClass, substitutor);
}
return originalType;
return new TypeCorrector(resolveScope).mapType(originalType);
}
private static boolean processSuperTypes(@NotNull PsiClass aClass,
@@ -0,0 +1,283 @@
/*
* 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.psi.impl;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
/**
* @author peter
*/
class TypeCorrector extends PsiTypeMapper {
private final Map<PsiClassType, PsiClassType> myResultMap = ContainerUtil.newIdentityHashMap();
private final GlobalSearchScope myResolveScope;
TypeCorrector(GlobalSearchScope resolveScope) {
myResolveScope = resolveScope;
}
@Override
public PsiType visitType(PsiType type) {
if (type instanceof PsiLambdaParameterType || type instanceof PsiLambdaExpressionType || type instanceof PsiMethodReferenceType) {
return type;
}
return super.visitType(type);
}
@Override
public PsiType visitClassType(final PsiClassType classType) {
PsiClassType alreadyComputed = myResultMap.get(classType);
if (alreadyComputed != null) {
return alreadyComputed;
}
final PsiClassType.ClassResolveResult classResolveResult = classType.resolveGenerics();
final PsiClass psiClass = classResolveResult.getElement();
final PsiSubstitutor substitutor = classResolveResult.getSubstitutor();
if (psiClass == null) return classType;
PsiUtilCore.ensureValid(psiClass);
final PsiClass mappedClass = mapClass(psiClass);
if (mappedClass == null) return null;
PsiClassType mappedType = new PsiCorrectedClassType(classType.getLanguageLevel(),
classType,
new CorrectedResolveResult(psiClass, mappedClass, substitutor, classResolveResult));
myResultMap.put(classType, mappedType);
return mappedType;
}
private PsiClass mapClass(@NotNull PsiClass psiClass) {
String qualifiedName = psiClass.getQualifiedName();
if (qualifiedName == null) {
return psiClass;
}
PsiFile file = psiClass.getContainingFile();
if (file == null || !file.getViewProvider().isPhysical()) {
return psiClass;
}
return JavaPsiFacade.getInstance(psiClass.getProject()).findClass(qualifiedName, myResolveScope);
}
@Nullable
private PsiSubstitutor mapSubstitutor(PsiClass originalClass, PsiClass mappedClass, PsiSubstitutor substitutor) {
PsiTypeParameter[] typeParameters = mappedClass.getTypeParameters();
PsiTypeParameter[] originalTypeParameters = originalClass.getTypeParameters();
if (typeParameters.length != originalTypeParameters.length) return null;
PsiSubstitutor mappedSubstitutor = PsiSubstitutor.EMPTY;
for (int i = 0; i < originalTypeParameters.length; i++) {
PsiType originalSubstitute = substitutor.substitute(originalTypeParameters[i]);
if (originalSubstitute != null) {
PsiType substitute = mapType(originalSubstitute);
if (substitute == null) return null;
mappedSubstitutor = mappedSubstitutor.put(typeParameters[i], substitute);
}
else {
mappedSubstitutor = mappedSubstitutor.put(typeParameters[i], null);
}
}
if (mappedClass.hasModifierProperty(PsiModifier.STATIC)) {
return mappedSubstitutor;
}
PsiClass mappedContaining = mappedClass.getContainingClass();
PsiClass originalContaining = originalClass.getContainingClass();
if ((mappedContaining != null) != (originalContaining != null)) {
return null;
}
if (mappedContaining != null) {
PsiSubstitutor outerSubstitutor = mapSubstitutor(originalContaining, mappedContaining, substitutor);
if (outerSubstitutor == null) return null;
return mappedSubstitutor.putAll(outerSubstitutor);
}
return mappedSubstitutor;
}
private class PsiCorrectedClassType extends PsiClassType.Stub {
private final PsiClassType myDelegate;
private final CorrectedResolveResult myResolveResult;
public PsiCorrectedClassType(LanguageLevel languageLevel,
PsiClassType delegate,
CorrectedResolveResult resolveResult) {
super(languageLevel, delegate.getAnnotations());
myDelegate = delegate;
myResolveResult = resolveResult;
}
@NotNull
@Override
public String getCanonicalText(boolean annotated) {
return myDelegate.getCanonicalText();
}
@NotNull
@Override
public PsiClass resolve() {
return myResolveResult.myMappedClass;
}
@Override
public String getClassName() {
return myDelegate.getClassName();
}
@NotNull
@Override
public PsiType[] getParameters() {
return ContainerUtil.map2Array(myDelegate.getParameters(), PsiType.class, new Function<PsiType, PsiType>() {
@Override
public PsiType fun(PsiType type) {
return mapType(type);
}
});
}
@NotNull
@Override
public ClassResolveResult resolveGenerics() {
return myResolveResult;
}
@NotNull
@Override
public PsiClassType rawType() {
PsiClass psiClass = resolve();
PsiElementFactory factory = JavaPsiFacade.getElementFactory(psiClass.getProject());
return factory.createType(psiClass, factory.createRawSubstitutor(psiClass));
}
@NotNull
@Override
public GlobalSearchScope getResolveScope() {
return myResolveScope;
}
@NotNull
@Override
public LanguageLevel getLanguageLevel() {
return myLanguageLevel;
}
@NotNull
@Override
public PsiClassType setLanguageLevel(@NotNull LanguageLevel languageLevel) {
return new PsiCorrectedClassType(languageLevel, myDelegate, myResolveResult);
}
@NotNull
@Override
public String getPresentableText() {
return myDelegate.getPresentableText();
}
@NotNull
@Override
public String getInternalCanonicalText() {
return myDelegate.getInternalCanonicalText();
}
@Override
public boolean isValid() {
return myDelegate.isValid() && resolve().isValid();
}
@Override
public boolean equalsToText(@NotNull @NonNls String text) {
return myDelegate.equalsToText(text);
}
}
private class CorrectedResolveResult implements PsiClassType.ClassResolveResult {
private final PsiClass myPsiClass;
private final PsiClass myMappedClass;
private final PsiSubstitutor mySubstitutor;
private final PsiClassType.ClassResolveResult myClassResolveResult;
private volatile PsiSubstitutor myLazySubstitutor;
public CorrectedResolveResult(PsiClass psiClass,
PsiClass mappedClass,
PsiSubstitutor substitutor,
PsiClassType.ClassResolveResult classResolveResult) {
myPsiClass = psiClass;
myMappedClass = mappedClass;
mySubstitutor = substitutor;
myClassResolveResult = classResolveResult;
}
@NotNull
@Override
public PsiSubstitutor getSubstitutor() {
PsiSubstitutor result = myLazySubstitutor;
if (result == null) {
result = mapSubstitutor(myPsiClass, myMappedClass, mySubstitutor);
if (result == null) {
//better ideas?
result = JavaPsiFacade.getElementFactory(myMappedClass.getProject()).createRawSubstitutor(myMappedClass);
}
myLazySubstitutor = result;
}
return result;
}
@Override
public PsiClass getElement() {
return myMappedClass;
}
@Override
public boolean isPackagePrefixPackageReference() {
return myClassResolveResult.isPackagePrefixPackageReference();
}
@Override
public boolean isAccessible() {
return myClassResolveResult.isAccessible();
}
@Override
public boolean isStaticsScopeCorrect() {
return myClassResolveResult.isStaticsScopeCorrect();
}
@Override
public PsiElement getCurrentFileResolveScope() {
return myClassResolveResult.getCurrentFileResolveScope();
}
@Override
public boolean isValidResult() {
return myClassResolveResult.isValidResult();
}
}
}
@@ -24,6 +24,7 @@ import com.intellij.openapi.util.Condition;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.psi.impl.PsiClassImplUtil;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.source.resolve.JavaResolveCache;
import com.intellij.psi.impl.source.resolve.graphInference.InferenceSession;
@@ -171,7 +172,7 @@ public class PsiMethodCallExpressionImpl extends ExpressionPsiElement implements
}
}
return theOnly;
return PsiClassImplUtil.correctType(theOnly, call.getResolveScope());
}
@Nullable
@@ -27,6 +27,7 @@ import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.JavaCodeStyleSettingsFacade;
import com.intellij.psi.filters.*;
import com.intellij.psi.impl.CheckUtil;
import com.intellij.psi.impl.PsiClassImplUtil;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.impl.source.SourceJavaCodeReference;
@@ -405,11 +406,11 @@ public class PsiReferenceExpressionImpl extends PsiReferenceExpressionBase imple
PsiUtil.ensureValidType(substitutedType);
PsiType normalized = PsiImplUtil.normalizeWildcardTypeByPosition(substitutedType, expr);
PsiUtil.ensureValidType(normalized);
return normalized;
return PsiClassImplUtil.correctType(normalized, expr.getResolveScope());
}
}
return TypeConversionUtil.erasure(ret);
return PsiClassImplUtil.correctType(TypeConversionUtil.erasure(ret), expr.getResolveScope());
}
}
@@ -0,0 +1,5 @@
interface A {
<error descr="Illegal combination of modifiers: 'strictfp' and 'abstract'">strictfp</error> void m();
strictfp default void m1(){}
strictfp static void m2() {}
}
@@ -0,0 +1,15 @@
// "Replace with lambda" "true"
class Test2 {
void foo(final List<PatchLogger> loggers) {
final PatchLogger logger = logger1 -> {
for (PatchLogger logger2 : loggers) {
logger2.logOperation(logger1);
}
};
}
public interface PatchLogger {
void logOperation(String logger);
}
}
@@ -0,0 +1,15 @@
// "Replace with lambda" "true"
class Test2 {
void foo(final List<PatchLogger> loggers) {
final PatchLogger logger = s -> {
for (PatchLogger logger1 : loggers) {
logger1.logOperation(s);
}
};
}
public interface PatchLogger {
void logOperation(String logger);
}
}
@@ -0,0 +1,18 @@
// "Replace with lambda" "true"
class Test2 {
void foo(final List<PatchLogger> loggers) {
final PatchLogger logger = new Patch<caret>Logger() {
@Override
public void logOperation(String logger1) {
for (PatchLogger logger : loggers) {
logger.logOperation(logger1);
}
}
};
}
public interface PatchLogger {
void logOperation(String logger);
}
}
@@ -0,0 +1,18 @@
// "Replace with lambda" "true"
class Test2 {
void foo(final List<PatchLogger> loggers) {
final PatchLogger logger = new Patch<caret>Logger() {
@Override
public void logOperation(String s) {
for (PatchLogger logger : loggers) {
logger.logOperation(s);
}
}
};
}
public interface PatchLogger {
void logOperation(String logger);
}
}
@@ -15,7 +15,6 @@
*/
package com.intellij.codeInsight
import com.intellij.idea.Bombed
import com.intellij.openapi.module.JavaModuleType
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.testFramework.PsiTestUtil
@@ -25,7 +24,6 @@ import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase
*/
class MultipleModuleHighlightingTest extends JavaCodeInsightFixtureTestCase {
@Bombed(day = 1, month = Calendar.APRIL)
public void "test use original place classpath for reference type resolving"() {
addTwoModules()
@@ -60,7 +58,6 @@ class Class3 {
myFixture.checkHighlighting()
}
@Bombed(day = 1, month = Calendar.APRIL)
public void "test use original place classpath for new expression type resolving"() {
addTwoModules()
@@ -43,6 +43,10 @@ public class LightAdvHighlightingJdk8Test extends LightDaemonAnalyzerTestCase {
doTest();
}
public void testStrictfpInsideInterface() throws Exception {
doTest();
}
private void doTest() {
IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_8, getModule(), getTestRootDisposable());
doTest(BASE_PATH + "/" + getTestName(false) + ".java", true, false);
@@ -31,16 +31,11 @@ public class ApplicationNamesInfo {
@NonNls private static final String ATTRIBUTE_PRODUCT = "product";
@NonNls private static final String ATTRIBUTE_FULL_NAME = "fullname";
@NonNls private static final String ATTRIBUTE_SCRIPT = "script";
@NonNls private static final String ELEMENT_VERSION = "version";
@NonNls private static final String ATTRIBUTE_MAJOR = "major";
@NonNls private static final String ATTRIBUTE_MINOR = "minor";
private String myProductName;
private String myFullProductName;
private String myLowercaseProductName;
private String myScriptName;
private String myMajorVersion;
private String myMinorVersion;
private static class ApplicationNamesInfoHolder {
private static final ApplicationNamesInfo ourInstance = new ApplicationNamesInfo();
@@ -69,12 +64,6 @@ public class ApplicationNamesInfo {
myFullProductName = names.getAttributeValue(ATTRIBUTE_FULL_NAME);
myLowercaseProductName = StringUtil.capitalize(myProductName.toLowerCase());
myScriptName = names.getAttributeValue(ATTRIBUTE_SCRIPT);
final Element version = rootElement.getChild(ELEMENT_VERSION);
if (version != null) {
myMajorVersion = version.getAttributeValue(ATTRIBUTE_MAJOR);
myMinorVersion = version.getAttributeValue(ATTRIBUTE_MINOR);
}
}
/**
@@ -105,14 +94,6 @@ public class ApplicationNamesInfo {
return myScriptName;
}
public String getMinorVersion() {
return myMinorVersion;
}
public String getMajorVersion() {
return myMajorVersion;
}
public static String getComponentName() {
final String prefix = System.getProperty(PlatformUtils.PLATFORM_PREFIX_KEY);
if (prefix != null) {
@@ -105,6 +105,7 @@ public class CompareFilesAction extends BaseShowDiffAction {
if (data.length == 1) {
VirtualFile otherFile = getOtherFile(project, data[0]);
if (otherFile == null) return null;
if (!data[0].isValid()) return null;
return DiffRequestFactory.getInstance().createFromFiles(project, data[0], otherFile);
}
else {
@@ -127,8 +128,7 @@ public class CompareFilesAction extends BaseShowDiffAction {
key = LAST_USED_FILE_KEY;
}
VirtualFile selectedFile = getDefaultSelection(project, key, file);
VirtualFile[] result = FileChooser.chooseFiles(descriptor, project, selectedFile);
VirtualFile otherFile = result.length == 1 ? result[0] : null;
VirtualFile otherFile = FileChooser.chooseFile(descriptor, project, selectedFile);
if (otherFile != null) updateDefaultSelection(project, key, otherFile);
return otherFile;
}
@@ -31,15 +31,16 @@ import java.util.List;
public abstract class SetEditorSettingsAction extends ActionGroup implements DumbAware {
@NotNull private final TextDiffSettingsHolder.TextDiffSettings myTextSettings;
@NotNull private final List<? extends Editor> myEditors;
@NotNull private final EditorSettingToggleAction[] myActions;
@NotNull
public abstract List<? extends Editor> getEditors();
public SetEditorSettingsAction(@NotNull TextDiffSettingsHolder.TextDiffSettings settings) {
public SetEditorSettingsAction(@NotNull TextDiffSettingsHolder.TextDiffSettings settings,
@NotNull List<? extends Editor> editors) {
super("Editor Settings", null, AllIcons.General.SecondaryGroup);
setPopup(true);
myTextSettings = settings;
myEditors = editors;
myActions = new EditorSettingToggleAction[]{
new EditorSettingToggleAction("EditorToggleShowWhitespaces") {
@@ -121,7 +122,7 @@ public abstract class SetEditorSettingsAction extends ActionGroup implements Dum
}
public void applyDefaults() {
for (Editor editor : getEditors()) {
for (Editor editor : myEditors) {
for (EditorSettingToggleAction action : myActions) {
action.apply(editor, action.isSelected());
}
@@ -146,7 +147,7 @@ public abstract class SetEditorSettingsAction extends ActionGroup implements Dum
@Override
public void setSelected(AnActionEvent e, boolean state) {
for (Editor editor : getEditors()) {
for (Editor editor : myEditors) {
setSelected(state);
apply(editor, state);
}
@@ -42,7 +42,7 @@ public class BinaryFileContentImpl implements DiffContent, BinaryFileContent {
@Nullable
@Override
public OpenFileDescriptor getOpenFileDescriptor() {
if (myProject == null) return null;
if (myProject == null || myProject.isDefault()) return null;
return new OpenFileDescriptor(myProject, myFile);
}
@@ -35,7 +35,7 @@ public class DirectoryContentImpl implements DiffContent, DirectoryContent {
@Nullable
@Override
public OpenFileDescriptor getOpenFileDescriptor() {
if (myProject == null) return null;
if (myProject == null || myProject.isDefault()) return null;
return new OpenFileDescriptor(myProject, myFile);
}
@@ -39,7 +39,7 @@ public class FileDocumentContentImpl extends DocumentContentImpl implements File
@Nullable
@Override
public OpenFileDescriptor getOpenFileDescriptor(int offset) {
if (myProject == null) return null;
if (myProject == null || myProject.isDefault()) return null;
return new OpenFileDescriptor(myProject, myFile, offset);
}
@@ -390,10 +390,13 @@ public class BinaryDiffViewer extends ListenerDiffViewerBase {
List<DiffContent> contents = ((ContentDiffRequest)request).getContents();
if (contents.size() != 2) return false;
if (!canShowContent(contents.get(0), context)) return false;
if (!canShowContent(contents.get(1), context)) return false;
return wantShowContent(contents.get(0), context) || wantShowContent(contents.get(1), context);
boolean canShow = true;
boolean wantShow = false;
for (DiffContent content : contents) {
canShow &= canShowContent(content, context);
wantShow |= wantShowContent(content, context);
}
return canShow && wantShow;
}
public static boolean canShowContent(@NotNull DiffContent content, @NotNull DiffContext context) {
@@ -71,6 +71,8 @@ import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import static com.intellij.diff.util.DiffUtil.getLineCount;
public class OnesideDiffViewer extends TextDiffViewerBase {
public static final Logger LOG = Logger.getInstance(OnesideDiffViewer.class);
@@ -67,6 +67,8 @@ import java.awt.event.WindowFocusListener;
import java.util.*;
import java.util.List;
import static com.intellij.diff.util.DiffUtil.getLineCount;
public class SimpleDiffViewer extends TwosideTextDiffViewer {
public static final Logger LOG = Logger.getInstance(SimpleDiffViewer.class);
@@ -71,7 +71,6 @@ public abstract class ListenerDiffViewerBase extends DiffViewerBase {
@Override
public void documentChanged(DocumentEvent event) {
onDocumentChange(event);
scheduleRediff();
}
};
}
@@ -92,7 +91,6 @@ public abstract class ListenerDiffViewerBase extends DiffViewerBase {
public void contentsChanged(@NotNull VirtualFileEvent event) {
if (files.contains(event.getFile())) {
onFileChange(event);
scheduleRediff();
}
}
@@ -100,7 +98,6 @@ public abstract class ListenerDiffViewerBase extends DiffViewerBase {
public void propertyChanged(@NotNull VirtualFilePropertyEvent event) {
if (files.contains(event.getFile())) {
onFileChange(event);
scheduleRediff();
}
}
};
@@ -112,6 +109,7 @@ public abstract class ListenerDiffViewerBase extends DiffViewerBase {
@CalledInAwt
protected void onDocumentChange(@NotNull DocumentEvent event) {
scheduleRediff();
}
@CalledInAwt
@@ -120,6 +118,7 @@ public abstract class ListenerDiffViewerBase extends DiffViewerBase {
@CalledInAwt
protected void onFileChange(@NotNull VirtualFileEvent event) {
scheduleRediff();
}
//
@@ -26,7 +26,6 @@ import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ComboBoxAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actions.EditorActionUtil;
import com.intellij.openapi.editor.event.EditorMouseEvent;
import com.intellij.openapi.editor.ex.EditorEx;
@@ -118,6 +117,11 @@ public abstract class TextDiffViewerBase extends ListenerDiffViewerBase {
);
}
@CalledInAwt
protected void onSettingsChanged() {
rediff();
}
//
// Impl
//
@@ -162,10 +166,6 @@ public abstract class TextDiffViewerBase extends ListenerDiffViewerBase {
return result;
}
protected static int getLineCount(@NotNull Document document) {
return DiffUtil.getLineCount(document);
}
private class MyFontSizeListener implements PropertyChangeListener {
private boolean myDuringUpdate = false;
@@ -194,13 +194,7 @@ public abstract class TextDiffViewerBase extends ListenerDiffViewerBase {
protected class MySetEditorSettingsAction extends SetEditorSettingsAction {
public MySetEditorSettingsAction() {
super(myTextSettings);
}
@NotNull
@Override
public List<? extends Editor> getEditors() {
return TextDiffViewerBase.this.getEditors();
super(myTextSettings, getEditors());
}
}
@@ -280,7 +274,7 @@ public abstract class TextDiffViewerBase extends ListenerDiffViewerBase {
if (getCurrentSetting() == setting) return;
getTextSettings().setHighlightPolicy(setting);
update(e);
rediff();
onSettingsChanged();
}
@NotNull
@@ -311,7 +305,7 @@ public abstract class TextDiffViewerBase extends ListenerDiffViewerBase {
if (getCurrentSetting() == setting) return;
getTextSettings().setIgnorePolicy(setting);
update(e);
rediff();
onSettingsChanged();
}
@NotNull
@@ -318,11 +318,13 @@ public abstract class ThreesideTextDiffViewer extends TextDiffViewerBase {
List<DiffContent> contents = ((ContentDiffRequest)request).getContents();
if (contents.size() != 3) return false;
if (!canShowContent(contents.get(0))) return false;
if (!canShowContent(contents.get(1))) return false;
if (!canShowContent(contents.get(2))) return false;
return true;
boolean canShow = true;
boolean wantShow = false;
for (DiffContent content : contents) {
canShow &= canShowContent(content);
wantShow |= wantShowContent(content);
}
return canShow && wantShow;
}
public static boolean canShowContent(@NotNull DiffContent content) {
@@ -330,6 +332,11 @@ public abstract class ThreesideTextDiffViewer extends TextDiffViewerBase {
return false;
}
public static boolean wantShowContent(@NotNull DiffContent content) {
if (content instanceof DocumentContent) return true;
return false;
}
//
// Actions
//
@@ -351,7 +351,7 @@ public abstract class TwosideTextDiffViewer extends TextDiffViewerBase {
EditorEx editor = getCurrentEditor();
DocumentContent content = getCurrentSide().select(myActualContent1, myActualContent2);
if (content == null) return null;
assert content != null;
int offset = editor.getCaretModel().getOffset();
return content.getOpenFileDescriptor(offset);
@@ -363,12 +363,13 @@ public abstract class TwosideTextDiffViewer extends TextDiffViewerBase {
List<DiffContent> contents = ((ContentDiffRequest)request).getContents();
if (contents.size() != 2) return false;
if (!canShowContent(contents.get(0))) return false;
if (!canShowContent(contents.get(1))) return false;
if (contents.get(0) instanceof EmptyContent && contents.get(1) instanceof EmptyContent) return false;
return true;
boolean canShow = true;
boolean wantShow = false;
for (DiffContent content : contents) {
canShow &= canShowContent(content);
wantShow |= wantShowContent(content);
}
return canShow && wantShow;
}
public static boolean canShowContent(@NotNull DiffContent content) {
@@ -377,6 +378,11 @@ public abstract class TwosideTextDiffViewer extends TextDiffViewerBase {
return false;
}
public static boolean wantShowContent(@NotNull DiffContent content) {
if (content instanceof DocumentContent) return true;
return false;
}
//
// Actions
//
@@ -91,7 +91,9 @@ public class CodeStyleMainPanel extends JPanel implements TabbedLanguageCodeStyl
@Override
public void currentSettingsChanged() {
ensureCurrentPanel().onSomethingChanged();
if (!myIsDisposed) {
ensureCurrentPanel().onSomethingChanged();
}
}
@Override
@@ -60,16 +60,14 @@ public class FacetManagerImpl extends FacetManager implements ModuleComponent, P
@NonNls public static final String COMPONENT_NAME = "FacetManager";
private final Module myModule;
private final FacetTypeRegistry myFacetTypeRegistry;
private final FacetManagerModel myModel = new FacetManagerModel();
private boolean myInsideCommit = false;
private final MessageBus myMessageBus;
private boolean myModuleAdded;
public FacetManagerImpl(final Module module, MessageBus messageBus, final FacetTypeRegistry facetTypeRegistry) {
public FacetManagerImpl(final Module module, MessageBus messageBus) {
myModule = module;
myMessageBus = messageBus;
myFacetTypeRegistry = facetTypeRegistry;
}
@Override
@@ -167,6 +165,8 @@ public class FacetManagerImpl extends FacetManager implements ModuleComponent, P
}
private void addFacets(final List<FacetState> facetStates, final Facet underlyingFacet, ModifiableFacetModel model) {
FacetTypeRegistry registry = FacetTypeRegistry.getInstance();
for (FacetState child : facetStates) {
final String typeId = child.getFacetType();
if (typeId == null) {
@@ -174,7 +174,7 @@ public class FacetManagerImpl extends FacetManager implements ModuleComponent, P
continue;
}
final FacetType<?,?> type = myFacetTypeRegistry.findFacetType(typeId);
final FacetType<?,?> type = registry.findFacetType(typeId);
if (type == null) {
addInvalidFacet(child, model, underlyingFacet, ProjectBundle.message("error.message.unknown.facet.type.0", typeId), typeId);
continue;
@@ -190,7 +190,7 @@ public class FacetManagerImpl extends FacetManager implements ModuleComponent, P
FacetType<?,?> expectedUnderlyingType = null;
FacetTypeId<?> underlyingTypeId = type.getUnderlyingFacetType();
if (underlyingTypeId != null) {
expectedUnderlyingType = myFacetTypeRegistry.findFacetType(underlyingTypeId);
expectedUnderlyingType = registry.findFacetType(underlyingTypeId);
}
FacetType actualUnderlyingType = underlyingFacet != null ? underlyingFacet.getType() : null;
if (expectedUnderlyingType != null) {
@@ -56,17 +56,19 @@ public class PsiAwareTextEditorProvider extends TextEditorProvider implements As
LOG.error("Cannot open text editor for " + file);
}
CodeFoldingState state = null;
try {
Document document = FileDocumentManager.getInstance().getDocument(file);
if (document != null) {
state = CodeFoldingManager.getInstance(project).buildInitialFoldings(document);
if (!project.isDefault()) { // There's no CodeFoldingManager for default project (which is used in diff command-line application)
try {
Document document = FileDocumentManager.getInstance().getDocument(file);
if (document != null) {
state = CodeFoldingManager.getInstance(project).buildInitialFoldings(document);
}
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Exception e) {
LOG.error("Error building initial foldings", e);
}
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Exception e) {
LOG.error("Error building initial foldings", e);
}
final CodeFoldingState finalState = state;
return new Builder() {
@@ -20,7 +20,6 @@
package com.intellij.openapi.roots.impl;
import com.intellij.ProjectTopics;
import com.intellij.concurrency.JobLauncher;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.ExtensionException;
@@ -48,7 +47,6 @@ import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent;
import com.intellij.psi.PsiManager;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.impl.file.impl.FileManagerImpl;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.FileBasedIndex;
import com.intellij.util.indexing.FileBasedIndexProjectHandler;
@@ -63,6 +61,7 @@ import java.util.Collections;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Future;
public class PushedFilePropertiesUpdaterImpl extends PushedFilePropertiesUpdater {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.roots.impl.PushedFilePropertiesUpdater");
@@ -290,18 +289,44 @@ public class PushedFilePropertiesUpdaterImpl extends PushedFilePropertiesUpdater
}
if (ourConcurrentlyFlag.get() == Boolean.TRUE && Registry.is("idea.concurrent.scanning.files.to.index")) {
JobLauncher.getInstance().invokeConcurrentlyUnderProgress(tasks, null, false, new Processor<Runnable>() {
@Override
public boolean process(Runnable runnable) {
runnable.run();
return true;
}
});
invoke2xConcurrently(tasks);
} else {
for(Runnable r:tasks) r.run();
}
}
public static void invoke2xConcurrently(final List<Runnable> tasks) {
final ConcurrentLinkedQueue<Runnable> tasksQueue = new ConcurrentLinkedQueue<Runnable>(tasks);
Future<?> result = null;
if (tasks.size() > 1) {
result = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
@Override
public void run() {
Runnable runnable;
while ((runnable = tasksQueue.poll()) != null) runnable.run();
}
});
}
Runnable runnable;
while ((runnable = tasksQueue.poll()) != null) runnable.run();
if (result != null) {
try {
result.get();
} catch (Exception ex) {
LOG.error(ex);
}
}
//JobLauncher.getInstance().invokeConcurrently(tasks, null, false, false, new Processor<Runnable>() {
// @Override
// public boolean process(Runnable runnable) {
// runnable.run();
// return true;
// }
//});
}
public static final ThreadLocal<Boolean> ourConcurrentlyFlag = new ThreadLocal<Boolean>();
private void applyPushersToFile(final VirtualFile fileOrDir, final FilePropertyPusher[] pushers, final Object[] moduleValues) {
@@ -17,7 +17,6 @@
package com.intellij.util.indexing;
import com.intellij.AppTopics;
import com.intellij.concurrency.JobLauncher;
import com.intellij.history.LocalHistory;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.ide.util.DelegatingProgressIndicator;
@@ -47,6 +46,7 @@ import com.intellij.openapi.progress.Task;
import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator;
import com.intellij.openapi.project.*;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.impl.PushedFilePropertiesUpdaterImpl;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.registry.Registry;
@@ -2658,13 +2658,7 @@ public class FileBasedIndexImpl extends FileBasedIndex {
}
if (ourConcurrentlyFlag.get() == Boolean.TRUE && Registry.is("idea.concurrent.scanning.files.to.index")) {
JobLauncher.getInstance().invokeConcurrentlyUnderProgress(tasks, indicator, false, false, new Processor<Runnable>() {
@Override
public boolean process(Runnable runnable) {
runnable.run();
return true;
}
});
PushedFilePropertiesUpdaterImpl.invoke2xConcurrently(tasks);
} else {
for(Runnable r:tasks) r.run();
}
@@ -18,6 +18,8 @@ package com.intellij.openapi.actionSystem.ex;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
@@ -218,13 +220,13 @@ public abstract class ComboBoxAction extends AnAction implements CustomComponent
@Override
public void run() {
// give button chance to handle action listener
UIUtil.invokeLaterIfNeeded(new Runnable() {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
myForcePressed = false;
myPopup = null;
}
});
}, ModalityState.any());
repaint();
fireStateChanged();
}
@@ -15,23 +15,13 @@
*/
package com.intellij.ui.components;
import com.intellij.openapi.actionSystem.DataKey;
import com.intellij.openapi.actionSystem.DataSink;
import com.intellij.openapi.actionSystem.TypeSafeDataProvider;
import com.intellij.util.IconUtil;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class JBPanel extends JPanel implements TypeSafeDataProvider {
@Nullable
private Icon myBackgroundImage;
@Nullable
private Icon myCenterImage;
public class JBPanel extends JPanel {
public JBPanel(LayoutManager layout, boolean isDoubleBuffered) {
super(layout, isDoubleBuffered);
@@ -49,56 +39,4 @@ public class JBPanel extends JPanel implements TypeSafeDataProvider {
super();
}
@Nullable
public Icon getBackgroundImage() {
return myBackgroundImage;
}
public void setBackgroundImage(@Nullable Icon backgroundImage) {
myBackgroundImage = backgroundImage;
}
@Nullable
public Icon getCenterImage() {
return myCenterImage;
}
public void setCenterImage(@Nullable Icon centerImage) {
myCenterImage = centerImage;
}
@Override
protected void paintComponent(Graphics g) {
Icon image = getBackgroundImage();
if (image != null) {
final int w = image.getIconWidth();
final int h = image.getIconHeight();
int x = 0;
int y = 0;
while (w > 0 && x < getWidth()) {
while (h > 0 && y < getHeight()) {
image.paintIcon(this, g, x, y);
y+=h;
}
y=0;
x+=w;
}
} else {
super.paintComponent(g);
}
paintCenterImage(g);
}
protected void paintCenterImage(Graphics g) {
Icon centerImage = getCenterImage();
if (centerImage != null) {
IconUtil.paintInCenterOf(this, g, centerImage);
}
}
@Override
public void calcData(DataKey key, DataSink sink) {
// override this to provide additional context
}
}
@@ -282,18 +282,12 @@ public final class HttpRequests {
if (connection instanceof HttpURLConnection) {
int responseCode = ((HttpURLConnection)connection).getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_NOT_MODIFIED) {
if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
((HttpURLConnection)connection).disconnect();
if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
url = connection.getHeaderField("Location");
if (url != null) {
continue;
}
url = connection.getHeaderField("Location");
if (url != null) {
continue;
}
throw new IOException(IdeBundle.message("error.connection.failed.with.http.code.N", responseCode));
}
}
@@ -96,7 +96,7 @@ public class VirtualFileDiffElement extends DiffElement<VirtualFile> {
@Override
@Nullable
public OpenFileDescriptor getOpenFileDescriptor(@Nullable Project project) {
if (project == null) return null;
if (project == null || project.isDefault()) return null;
return new OpenFileDescriptor(project, myFile);
}
@@ -176,7 +176,8 @@ public class InstallPluginAction extends AnAction implements DumbAware {
ourInstallingNodes.removeAll(list);
}
};
PluginManagerMain.downloadPlugins(list, myHost.getPluginsModel().getAllPlugins(), onInstallRunnable, cleanupRunnable);
final List<IdeaPluginDescriptor> plugins = myHost.getPluginsModel().getAllPlugins();
PluginManagerMain.downloadPlugins(list, PluginManagerMain.mapToPluginIds(plugins), onInstallRunnable, cleanupRunnable);
}
catch (final IOException e1) {
ourInstallingNodes.removeAll(list);
@@ -56,7 +56,7 @@ public class PluginInstaller {
private PluginInstaller() { }
public static boolean prepareToInstall(List<PluginNode> pluginsToInstall,
List<IdeaPluginDescriptor> allPlugins,
List<PluginId> allPlugins,
@NotNull ProgressIndicator indicator) {
updateUrls(pluginsToInstall, indicator);
Set<PluginNode> dependant = new THashSet<PluginNode>();
@@ -108,7 +108,7 @@ public class PluginInstaller {
}
private static boolean prepareToInstall(List<PluginNode> pluginsToInstall,
List<IdeaPluginDescriptor> allPlugins,
List<PluginId> allPlugins,
Set<PluginNode> installedDependant,
@NotNull ProgressIndicator indicator) {
List<PluginId> pluginIds = new SmartList<PluginId>();
@@ -134,7 +134,7 @@ public class PluginInstaller {
private static boolean prepareToInstall(PluginNode pluginNode,
List<PluginId> pluginIds,
List<IdeaPluginDescriptor> allPlugins,
List<PluginId> allPlugins,
Set<PluginNode> installedDependant,
@NotNull ProgressIndicator indicator) throws IOException {
installedDependant.add(pluginNode);
@@ -236,13 +236,8 @@ public class PluginInstaller {
return true;
}
private static boolean isPluginInRepo(PluginId depPluginId, List<IdeaPluginDescriptor> allPlugins) {
for (IdeaPluginDescriptor plugin : allPlugins) {
if (plugin.getPluginId().equals(depPluginId)) {
return true;
}
}
return false;
private static boolean isPluginInRepo(PluginId depPluginId, List<PluginId> allPlugins) {
return allPlugins.contains(depPluginId);
}
public static void prepareToUninstall(PluginId pluginId) throws IOException {
@@ -49,6 +49,7 @@ import com.intellij.ui.*;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.speedSearch.SpeedSearchSupply;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
@@ -229,6 +230,16 @@ public abstract class PluginManagerMain implements Disposable {
return pluginTable;
}
@NotNull
public static List<PluginId> mapToPluginIds(List<IdeaPluginDescriptor> plugins) {
return ContainerUtil.map(plugins, new Function<IdeaPluginDescriptor, PluginId>() {
@Override
public PluginId fun(IdeaPluginDescriptor descriptor) {
return descriptor.getPluginId();
}
});
}
private static String getTextPrefix() {
final int fontSize = JBUI.scale(12);
final int m1 = JBUI.scale(2);
@@ -394,7 +405,7 @@ public abstract class PluginManagerMain implements Disposable {
}
public static boolean downloadPlugins(final List<PluginNode> plugins,
final List<IdeaPluginDescriptor> allPlugins,
final List<PluginId> allPlugins,
final Runnable onSuccess,
@Nullable final Runnable cleanup) throws IOException {
final boolean[] result = new boolean[1];
@@ -164,7 +164,7 @@ public class ApplicationStatisticsPersistenceComponent extends ApplicationStatis
public String fun(UsageDescriptor usageDescriptor) {
final String key = usageDescriptor.getKey();
final int value = usageDescriptor.getValue();
return value > 1 ? key + "=" + value : key;
return value != 1 ? key + "=" + value : key;
}
}, TOKENIZER);
}
@@ -59,7 +59,7 @@ public class DiffPanelOptions {
}
public void showSource(@Nullable OpenFileDescriptor descriptor) {
if (descriptor == null || myDiffPanel.getProject() == null) return;
if (descriptor == null || myDiffPanel.getProject() == null || myDiffPanel.getProject().isDefault()) return;
myShowSourcePolicy.showSource(descriptor, myDiffPanel);
}
@@ -36,6 +36,7 @@ import com.intellij.openapi.ui.Queryable;
import com.intellij.openapi.ui.TypingTarget;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.wm.impl.IdeBackgroundUtil;
import com.intellij.ui.Grayer;
import com.intellij.ui.components.Magnificator;
import com.intellij.util.ui.UIUtil;
@@ -172,6 +173,8 @@ public class EditorComponentImpl extends JComponent implements Scrollable, DataP
UIUtil.setupComposite((Graphics2D)g);
UISettings.setupAntialiasing(g);
myEditor.paint((Graphics2D)g);
IdeBackgroundUtil.paintEditorBackground(g, this);
}
finally {
myApplication.editorPaintFinish();
@@ -48,6 +48,7 @@ import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.wm.impl.IdeBackgroundUtil;
import com.intellij.ui.HintHint;
import com.intellij.ui.JBColor;
import com.intellij.ui.awt.RelativePoint;
@@ -229,6 +230,8 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse
}
g2.setTransform(old);
IdeBackgroundUtil.paintEditorBackground(g, this);
}
finally {
((ApplicationImpl)ApplicationManager.getApplication()).editorPaintFinish();
@@ -41,6 +41,7 @@ import com.intellij.openapi.wm.IdeFrame;
import com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.openapi.wm.impl.FrameTitleBuilder;
import com.intellij.openapi.wm.impl.IdeBackgroundUtil;
import com.intellij.openapi.wm.impl.IdePanePanel;
import com.intellij.ui.JBColor;
import com.intellij.ui.OnePixelSplitter;
@@ -155,14 +156,12 @@ public class EditorsSplitters extends IdePanePanel implements UISettingsListener
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (myCurrentWindow == null || myCurrentWindow.getFiles().length == 0) {
g.setColor(UIUtil.isUnderDarcula()? UIUtil.getBorderColor() : new Color(0, 0, 0, 50));
g.drawLine(0, 0, getWidth(), 0);
}
if (showEmptyText()) {
super.paintComponent(g);
g.setColor(UIUtil.isUnderDarcula() ? UIUtil.getBorderColor() : new Color(0, 0, 0, 50));
g.drawLine(0, 0, getWidth(), 0);
IdeBackgroundUtil.paintFrameBackground(g, this);
ourPainter.paintEmptyText(this, g);
}
}
@@ -133,7 +133,9 @@ class TextEditorComponent extends JBLoadingPanel implements DataProvider {
*/
void dispose(){
myDocument.removeDocumentListener(myDocumentListener);
EditorHistoryManager.getInstance(myProject).updateHistoryEntry(myFile, false);
if (!myProject.isDefault()) { // There's no EditorHistoryManager for default project (which is used in diff command-line application)
EditorHistoryManager.getInstance(myProject).updateHistoryEntry(myFile, false);
}
disposeEditor(myEditor);
myConnection.disconnect();
@@ -276,7 +278,8 @@ class TextEditorComponent extends JBLoadingPanel implements DataProvider {
final Editor e = validateCurrentEditor();
if (e == null) return null;
if (!myProject.isDisposed()) {
// There's no FileEditorManager for default project (which is used in diff command-line application)
if (!myProject.isDisposed() && !myProject.isDefault()) {
final Object o = FileEditorManager.getInstance(myProject).getData(dataId, e, e.getCaretModel().getCurrentCaret());
if (o != null) return o;
}
@@ -16,8 +16,10 @@
package com.intellij.openapi.updateSettings.impl.pluginsAdvertisement;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManagerMain;
import com.intellij.ide.plugins.RepositoryHelper;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileTypes.FileTypeFactory;
import com.intellij.openapi.fileTypes.PlainTextFileType;
@@ -30,6 +32,9 @@ import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.EditorNotificationPanel;
import com.intellij.ui.EditorNotifications;
import com.intellij.util.ContentsUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -132,7 +137,9 @@ public class PluginAdvertiserEditorNotificationProvider extends EditorNotificati
@Override
public void onSuccess() {
final PluginsAdvertiserDialog advertiserDialog =
new PluginsAdvertiserDialog(null, myPlugins.toArray(new PluginDownloader[myPlugins.size()]), myAllPlugins);
new PluginsAdvertiserDialog(null,
myPlugins.toArray(new PluginDownloader[myPlugins.size()]),
PluginManagerMain.mapToPluginIds(myAllPlugins));
if (advertiserDialog.showAndGet()) {
myEnabledExtensions.add(extension);
myNotifications.updateAllNotifications();
@@ -41,6 +41,7 @@ import com.intellij.reference.SoftReference;
import com.intellij.ui.EditorNotifications;
import com.intellij.util.Function;
import com.intellij.util.PlatformUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.LinkedMultiMap;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.io.HttpRequests;
@@ -322,7 +323,7 @@ public class PluginsAdvertiser implements StartupActivity {
}
if (message != null) {
final ConfigurePluginsListener notificationListener = new ConfigurePluginsListener(unknownFeatures, project, myAllPlugins, myPlugins, myDisabledPlugins);
final ConfigurePluginsListener notificationListener = new ConfigurePluginsListener(unknownFeatures, project, PluginManagerMain.mapToPluginIds(myAllPlugins), myPlugins, myDisabledPlugins);
NOTIFICATION_GROUP.createNotification(DISPLAY_ID, message, NotificationType.INFORMATION, notificationListener).notify(project);
}
}
@@ -449,13 +450,13 @@ public class PluginsAdvertiser implements StartupActivity {
private static class ConfigurePluginsListener implements NotificationListener {
private final Set<UnknownFeature> myUnknownFeatures;
private final Project myProject;
private final List<IdeaPluginDescriptor> myAllPlugins;
private final List<PluginId> myAllPlugins;
private final Set<PluginDownloader> myPlugins;
private final Map<Plugin, IdeaPluginDescriptor> myDisabledPlugins;
public ConfigurePluginsListener(Set<UnknownFeature> unknownFeatures,
Project project,
List<IdeaPluginDescriptor> allPlugins,
List<PluginId> allPlugins,
Set<PluginDownloader> plugins,
Map<Plugin, IdeaPluginDescriptor> disabledPlugins) {
myUnknownFeatures = unknownFeatures;
@@ -17,11 +17,14 @@ package com.intellij.openapi.updateSettings.impl.pluginsAdvertisement;
import com.intellij.ide.plugins.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.updateSettings.impl.DetectedPluginsPanel;
import com.intellij.openapi.updateSettings.impl.PluginDownloader;
import com.intellij.ui.TableUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
@@ -36,10 +39,10 @@ public class PluginsAdvertiserDialog extends DialogWrapper {
@Nullable private final Project myProject;
private final PluginDownloader[] myUploadedPlugins;
private final List<IdeaPluginDescriptor> myAllPlugins;
private final List<PluginId> myAllPlugins;
private final Set<String> mySkippedPlugins = new HashSet<String>();
PluginsAdvertiserDialog(@Nullable Project project, PluginDownloader[] plugins, List<IdeaPluginDescriptor> allPlugins) {
PluginsAdvertiserDialog(@Nullable Project project, PluginDownloader[] plugins, List<PluginId> allPlugins) {
super(project);
myProject = project;
Arrays.sort(plugins, new Comparator<PluginDownloader>() {
@@ -23,14 +23,17 @@ import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.ZipFileCache;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VFileProperty;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.impl.ArchiveHandler;
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent;
import com.intellij.openapi.vfs.newvfs.events.VFileEvent;
import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent;
import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent;
import com.intellij.util.Consumer;
import com.intellij.util.Function;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
@@ -206,15 +209,14 @@ public class VfsImplUtil {
ourHandlers.put(localPath, record);
final String finalRootPath = localPath;
forEachDirectoryComponent(localPath, new Processor<String>() {
forEachDirectoryComponent(localPath, new Consumer<String>() {
@Override
public boolean process(String containingDirectoryPath) {
public void consume(String containingDirectoryPath) {
Set<String> handlers = ourDominatorsMap.get(containingDirectoryPath);
if (handlers == null) {
ourDominatorsMap.put(containingDirectoryPath, handlers = ContainerUtil.newTroveSet());
}
handlers.add(finalRootPath);
return true;
}
});
refresh = true;
@@ -236,11 +238,11 @@ public class VfsImplUtil {
return t;
}
private static void forEachDirectoryComponent(String rootPath, Processor<String> processor) {
private static void forEachDirectoryComponent(String rootPath, Consumer<String> consumer) {
int index = rootPath.lastIndexOf('/');
while (index > 0) {
String containingDirectoryPath = rootPath.substring(0, index);
if (!processor.process(containingDirectoryPath)) return;
consumer.consume(containingDirectoryPath);
index = rootPath.lastIndexOf('/', index - 1);
}
}
@@ -301,14 +303,13 @@ public class VfsImplUtil {
public static InvalidationState invalidate(@Nullable InvalidationState state, final String path) {
Pair<ArchiveFileSystem, ArchiveHandler> handlerPair = ourHandlers.remove(path);
if (handlerPair != null) {
forEachDirectoryComponent(path, new Processor<String>() {
forEachDirectoryComponent(path, new Consumer<String>() {
@Override
public boolean process(String containingDirectoryPath) {
public void consume(String containingDirectoryPath) {
Set<String> handlers = ourDominatorsMap.get(containingDirectoryPath);
if (handlers != null && handlers.remove(path) && handlers.size() == 0) {
ourDominatorsMap.remove(containingDirectoryPath);
}
return true;
}
});
@@ -0,0 +1,73 @@
/*
* 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.openapi.wm.impl;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
import com.intellij.util.ImageLoader;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
/**
* @author gregsh
*/
public class IdeBackgroundUtil {
public static void paintEditorBackground(@NotNull Graphics g, @NotNull JComponent component) {
JRootPane rootPane = component.getRootPane();
Component glassPane = rootPane == null ? null : rootPane.getGlassPane();
if (glassPane instanceof IdeGlassPaneImpl) {
((IdeGlassPaneImpl)glassPane).getNamedPainters("editor").paint(g, component);
}
}
public static void paintFrameBackground(@NotNull Graphics g, @NotNull JComponent component) {
JRootPane rootPane = component.getRootPane();
Component glassPane = rootPane == null ? null : rootPane.getGlassPane();
if (glassPane instanceof IdeGlassPaneImpl) {
((IdeGlassPaneImpl)glassPane).getNamedPainters("ide").paint(g, component);
}
}
public static void initEditorPainters(@NotNull PaintersHelper painters) {
painters.addPainter(PaintersHelper.newWallpaperPainter("idea.wallpaper.editor"), null);
}
public static void initFramePainters(@NotNull PaintersHelper painters) {
painters.addPainter(PaintersHelper.newWallpaperPainter("idea.wallpaper.ide"), null);
ApplicationInfoEx appInfo = ApplicationInfoEx.getInstanceEx();
String path = UIUtil.isUnderDarcula()? appInfo.getEditorBackgroundImageUrl() : null;
URL url = path == null ? null : appInfo.getClass().getResource(path);
Image centerImage = url == null ? null : ImageLoader.loadFromUrl(url);
if (centerImage != null) {
painters.addPainter(PaintersHelper.newImagePainter(centerImage, PaintersHelper.FillType.TOP_CENTER, 1.0f, JBUI.insets(5, 0, 0, 0)), null);
}
}
@Nullable
public static Color getIdeBackgroundColor() {
Color result = UIUtil.getSlightlyDarkerColor(UIUtil.getPanelBackground());
return UIUtil.isUnderDarcula() ? new Color(40, 40, 41) : UIUtil.getSlightlyDarkerColor(UIUtil.getSlightlyDarkerColor(result));
}
}
@@ -28,9 +28,11 @@ import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Weighted;
import com.intellij.openapi.wm.IdeGlassPane;
import com.intellij.openapi.wm.IdeGlassPaneUtil;
import com.intellij.util.containers.FactoryMap;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.MenuDragMouseEvent;
@@ -40,7 +42,7 @@ import java.awt.event.*;
import java.util.*;
import java.util.List;
public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEventQueue.EventDispatcher, Painter.Listener {
public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEventQueue.EventDispatcher {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.wm.impl.IdeGlassPaneImpl");
@@ -61,10 +63,14 @@ public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEvent
});
private final JRootPane myRootPane;
private final Set<Painter> myPainters = new LinkedHashSet<Painter>();
private final Map<Painter, Component> myPainter2Component = new LinkedHashMap<Painter, Component>();
private final Map<String, PaintersHelper> myNamedPainters = new FactoryMap<String, PaintersHelper>() {
@Nullable
@Override
protected PaintersHelper create(String key) {
return new PaintersHelper(IdeGlassPaneImpl.this);
}
};
private boolean myPaintingActive;
private boolean myPreprocessorActive;
private final Map<Object, Cursor> myListener2Cursor = new LinkedHashMap<Object, Cursor>();
@@ -85,6 +91,11 @@ public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEvent
setVisible(false);
setLayout(null);
if (myRootPane instanceof IdeRootPane) {
IdeBackgroundUtil.initFramePainters(getNamedPainters("ide"));
IdeBackgroundUtil.initEditorPainters(getNamedPainters("editor"));
}
myFocusProxy.setOpaque(false);
myFocusProxy.setPreferredSize(JBUI.emptySize());
myFocusProxy.setFocusable(true);
@@ -486,12 +497,6 @@ public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEvent
}
private void deactivateIfNeeded() {
if (myPaintingActive) {
if (myPainters.isEmpty() && getComponentCount() == 0) {
myPaintingActive = false;
}
}
if (myPreprocessorActive && myMouseListeners.isEmpty()) {
myPreprocessorActive = false;
}
@@ -500,12 +505,6 @@ public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEvent
}
private void activateIfNeeded() {
if (!myPaintingActive) {
if (!myPainters.isEmpty() || getComponentCount() > 0) {
myPaintingActive = true;
}
}
if (!myPreprocessorActive && !myMouseListeners.isEmpty()) {
myPreprocessorActive = true;
}
@@ -515,9 +514,10 @@ public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEvent
private void applyActivationState() {
boolean wasVisible = isVisible();
boolean hasWork = getPainters().hasPainters() || getComponentCount() > 0;
if (wasVisible != myPaintingActive) {
setVisible(myPaintingActive);
if (wasVisible != hasWork) {
setVisible(hasWork);
}
IdeEventQueue queue = IdeEventQueue.getInstance();
@@ -534,10 +534,18 @@ public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEvent
}
}
@NotNull
PaintersHelper getNamedPainters(@NotNull String name) {
return myNamedPainters.get(name);
}
@NotNull
private PaintersHelper getPainters() {
return getNamedPainters("glass");
}
public void addPainter(final Component component, final Painter painter, final Disposable parent) {
myPainters.add(painter);
myPainter2Component.put(painter, component == null ? this : component);
painter.addListener(this);
getPainters().addPainter(painter, component);
activateIfNeeded();
Disposer.register(parent, new Disposable() {
public void dispose() {
@@ -551,9 +559,7 @@ public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEvent
}
public void removePainter(final Painter painter) {
myPainters.remove(painter);
myPainter2Component.remove(painter);
painter.removeListener(this);
getPainters().removePainter(painter);
deactivateIfNeeded();
}
@@ -594,28 +600,7 @@ public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEvent
}
protected void paintComponent(final Graphics g) {
if (myPainters.isEmpty()) return;
Graphics2D g2d = (Graphics2D)g;
for (Painter painter : myPainters) {
final Rectangle clip = g.getClipBounds();
final Component component = myPainter2Component.get(painter);
if (component.getParent() == null) continue;
final Rectangle componentBounds = SwingUtilities.convertRectangle(component.getParent(), component.getBounds(), this);
if (!painter.needsRepaint()) {
continue;
}
if (clip.contains(componentBounds) || clip.intersects(componentBounds)) {
final Point targetPoint = SwingUtilities.convertPoint(this, 0, 0, component);
final Rectangle targetRect = new Rectangle(targetPoint, component.getSize());
g2d.translate(-targetRect.x, -targetRect.y);
painter.paint(component, g2d);
g2d.translate(targetRect.x, targetRect.y);
}
}
getPainters().paint(g);
}
@Override
@@ -623,22 +608,6 @@ public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEvent
super.paintChildren(g);
}
public boolean hasPainters() {
return !myPainters.isEmpty();
}
public void onNeedsRepaint(final Painter painter, final JComponent dirtyComponent) {
if (dirtyComponent != null && dirtyComponent.isShowing()) {
final Rectangle rec = SwingUtilities.convertRectangle(dirtyComponent, dirtyComponent.getBounds(), this);
if (rec != null) {
repaint(rec);
return;
}
}
repaint();
}
public Component getTargetComponentFor(MouseEvent e) {
Component candidate = findComponent(e, myRootPane.getLayeredPane());
if (candidate != null) return candidate;
@@ -654,7 +623,7 @@ public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEvent
@Override
public boolean isOptimizedDrawingEnabled() {
return !hasPainters() && super.isOptimizedDrawingEnabled();
return !getPainters().hasPainters() && super.isOptimizedDrawingEnabled();
}
@Override
@@ -15,66 +15,18 @@
*/
package com.intellij.openapi.wm.impl;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
import com.intellij.openapi.util.IconLoader;
import com.intellij.ui.components.JBPanel;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
public class IdePanePanel extends JBPanel {
public IdePanePanel(LayoutManager layout) {
super(layout);
}
@Nullable
@Override
public Icon getCenterImage() {
return getIdeBackgroundLogo();
}
@Nullable
@Override
public Icon getBackgroundImage() {
return getIdeBackgroundImage();
}
@Override
public Color getBackground() {
return getIdeBackgroundColor();
}
@Nullable
public static Icon getIdeBackgroundImage() {
return null;
}
@Nullable
public static Icon getIdeBackgroundLogo() {
if (UIUtil.isUnderDarcula()) {
String url = ApplicationInfoEx.getInstanceEx().getEditorBackgroundImageUrl();
if (url != null) {
return IconLoader.getIcon(url);
}
}
return null;
}
@Override
protected void paintCenterImage(Graphics g) {
final Icon image = getCenterImage();
if (image != null) {
final int x = (getWidth() - image.getIconWidth()) / 2;
final int y = ((getHeight() - 222) / 2 - image.getIconHeight()) / 2;
image.paintIcon(this, g, x, y);
}
}
@Nullable
public static Color getIdeBackgroundColor() {
Color result = UIUtil.getSlightlyDarkerColor(UIUtil.getPanelBackground());
return UIUtil.isUnderDarcula() ? new Color(40, 40, 41) : UIUtil.getSlightlyDarkerColor(UIUtil.getSlightlyDarkerColor(result));
return IdeBackgroundUtil.getIdeBackgroundColor();
}
}
@@ -324,7 +324,7 @@ public class IdeRootPane extends JRootPane implements UISettingsListener {
}
public boolean isOptimizedDrawingEnabled() {
return !myGlassPane.hasPainters() && myGlassPane.getComponentCount() == 0;
return myGlassPane.isVisible();
}
public ToolWindowsPane getToolWindowsPane() {
@@ -0,0 +1,234 @@
/*
* 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.openapi.wm.impl;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.ui.AbstractPainter;
import com.intellij.openapi.ui.GraphicsConfig;
import com.intellij.openapi.ui.Painter;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
final class PaintersHelper implements Painter.Listener {
private final Set<Painter> myPainters = ContainerUtil.newLinkedHashSet();
private final Map<Painter, Component> myPainter2Component = ContainerUtil.newLinkedHashMap();
private final JComponent myRootComponent;
public PaintersHelper(@NotNull JComponent component) {
myRootComponent = component;
}
public boolean hasPainters() {
return !myPainters.isEmpty();
}
public void addPainter(@NotNull Painter painter, @Nullable Component component) {
myPainters.add(painter);
myPainter2Component.put(painter, component == null ? myRootComponent : component);
painter.addListener(this);
}
public void removePainter(@NotNull Painter painter) {
painter.removeListener(this);
myPainters.remove(painter);
myPainter2Component.remove(painter);
}
public void clear() {
for (Painter painter : myPainters) {
painter.removeListener(this);
}
myPainters.clear();
myPainter2Component.clear();
}
public void paint(Graphics g) {
paint(g, myRootComponent);
}
public void paint(Graphics g, JComponent current) {
if (myPainters.isEmpty()) return;
Graphics2D g2d = (Graphics2D)g;
for (Painter painter : myPainters) {
Rectangle clip = g.getClipBounds();
Component component = myPainter2Component.get(painter);
if (component.getParent() == null) continue;
Rectangle componentBounds = SwingUtilities.convertRectangle(component.getParent(), component.getBounds(), current);
if (!painter.needsRepaint()) {
continue;
}
if (clip.contains(componentBounds) || clip.intersects(componentBounds)) {
Point targetPoint = SwingUtilities.convertPoint(current, 0, 0, component);
Rectangle targetRect = new Rectangle(targetPoint, component.getSize());
g2d.setClip(clip.intersection(componentBounds));
g2d.translate(-targetRect.x, -targetRect.y);
painter.paint(component, g2d);
g2d.translate(targetRect.x, targetRect.y);
}
}
}
@Override
public void onNeedsRepaint(Painter painter, JComponent dirtyComponent) {
if (dirtyComponent != null && dirtyComponent.isShowing()) {
Rectangle rec = SwingUtilities.convertRectangle(dirtyComponent, dirtyComponent.getBounds(), myRootComponent);
myRootComponent.repaint(rec);
}
else {
myRootComponent.repaint();
}
}
public enum FillType {
BG_CENTER, TILE, STRETCH,
CENTER, TOP_CENTER, BOTTOM_CENTER,
TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT
}
public static AbstractPainter newWallpaperPainter(final String propertyName) {
return new ImagePainter() {
Image image;
float alpha;
Insets insets;
FillType fillType;
String current;
@Override
public void executePaint(Component component, Graphics2D g) {
String value = StringUtil.notNullize(System.getProperty(propertyName), propertyName + ".png");
if (!Comparing.equal(value, current)) {
current = value;
image = scaled = null;
insets = JBUI.emptyInsets();
String[] parts = value.split(",");
try {
alpha = StringUtil.parseInt(parts.length > 1 ? parts[1]: "", 10) / 100f;
try {
fillType = FillType.valueOf(parts.length > 2 ? parts[2].toUpperCase(Locale.ENGLISH) : "");
}
catch (IllegalArgumentException e) {
fillType = FillType.STRETCH;
}
String url = parts[0].contains("://")? parts[0] :
VfsUtilCore.pathToUrl(parts[0].contains("/") ? parts[0] : PathManager.getConfigPath() + "/" + parts[0]);
//todo ImageLoader.loadFromUrl(new URL(url)); fails with AlphaComposite for unknown reason
image = ImageIO.read(new URL(url));
}
catch (Exception ignored) {
}
}
if (image == null) return;
executePaint(g, component, image, fillType, alpha, insets);
}
};
}
public static AbstractPainter newImagePainter(final Image image, final FillType fillType, final float alpha, final Insets insets) {
return new ImagePainter() {
@Override
public void executePaint(Component component, Graphics2D g) {
executePaint(g, component, image, fillType, alpha, insets);
}
};
}
private abstract static class ImagePainter extends AbstractPainter {
Image scaled;
@Override
public boolean needsRepaint() { return true; }
public void executePaint(Graphics2D g, Component component, Image image, FillType fillType, float alpha, Insets insets) {
int cw0 = component.getWidth();
int ch0 = component.getHeight();
Insets i = JBUI.insets(insets.top * ch0 / 100, insets.left * cw0 / 100, insets.bottom * ch0 / 100, insets.right * cw0 / 100);
int cw = cw0 - i.left - i.right;
int ch = ch0 - i.top - i.bottom;
int w = image.getWidth(null);
int h = image.getHeight(null);
if (w <= 0 || h <= 0) return;
if (fillType == FillType.STRETCH) {
if (scaled == null || scaled.getWidth(null) != cw || scaled.getHeight(null) != ch) {
scaled = image.getScaledInstance(cw, ch, Image.SCALE_SMOOTH);
}
}
GraphicsConfig cfg = new GraphicsConfig(g).setAlpha(alpha);
g.setColor(g.getBackground());
if (fillType == FillType.CENTER || fillType == FillType.BG_CENTER ||
fillType == FillType.TOP_CENTER || fillType == FillType.BOTTOM_CENTER) {
int x = i.left + (cw - w) / 2;
int y = fillType == FillType.TOP_CENTER? i.top :
fillType == FillType.BOTTOM_CENTER? ch0 - i.bottom - h :
i.top + (ch - h) / 2;
UIUtil.drawImage(g, image, x, y, null);
if (fillType == FillType.BG_CENTER) {
g.setColor(component.getBackground());
g.fillRect(0, 0, x, ch0);
g.fillRect(x, 0, w, h);
g.fillRect(x + w, 0, x, ch0);
g.fillRect(x, y + h, w, y);
}
}
else if (fillType == FillType.TOP_LEFT || fillType == FillType.TOP_RIGHT ||
fillType == FillType.BOTTOM_LEFT || fillType == FillType.BOTTOM_RIGHT) {
int x = fillType == FillType.TOP_LEFT || fillType == FillType.BOTTOM_LEFT ? i.left : cw0 - i.right - w;
int y = fillType == FillType.TOP_LEFT || fillType == FillType.TOP_RIGHT ? i.top : ch0 - i.bottom - h;
UIUtil.drawImage(g, image, x, y, null);
}
else if (fillType == FillType.TILE) {
int x = i.left;
int y = i.top;
while (w > 0 && x < cw) {
while (h > 0 && y < ch) {
UIUtil.drawImage(g, image, x, y, null);
y += h;
}
y = 0;
x += w;
}
}
else if (fillType == FillType.STRETCH) {
UIUtil.drawImage(g, scaled, i.left, i.top, null);
}
cfg.restore();
}
}
}
@@ -1063,17 +1063,12 @@ public final class ToolWindowsPane extends JBLayeredPane implements Disposable {
JComponent c = getComponentAt(anchor);
if (c instanceof Splitter) {
Splitter splitter = (Splitter)c;
if (myInfo.isSplit()) {
InternalDecorator component = (InternalDecorator)splitter.getFirstComponent();
if (component != null) {
final InternalDecorator component =
myInfo.isSplit() ? (InternalDecorator)splitter.getFirstComponent() : (InternalDecorator)splitter.getSecondComponent();
if (myInfo.isSplit() && component != null) {
myId2SplitProportion.put(component.getWindowInfo().getId(), splitter.getProportion());
}
setComponent(component, anchor, component != null ? component.getWindowInfo().getWeight() : 0);
}
else {
InternalDecorator component = (InternalDecorator)splitter.getSecondComponent();
setComponent(component, anchor, component != null ? component.getWindowInfo().getWeight() : 0);
}
setComponent(component, anchor, component != null ? component.getWindowInfo().getWeight() : 0);
} else {
setComponent(null, anchor, 0);
}
@@ -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.
@@ -617,7 +617,7 @@ public class EditorTextField extends NonOpaquePanel implements DocumentListener,
return getParent().getBackground();
}
if (UIUtil.isUnderDarcula() || UIUtil.isUnderIntelliJLaF()) return UIUtil.getTextFieldBackground();
if (UIUtil.isUnderDarcula()/* || UIUtil.isUnderIntelliJLaF()*/) return UIUtil.getTextFieldBackground();
return enabled
? colorsScheme.getDefaultBackground()
@@ -558,7 +558,7 @@ public class PopupFactoryImpl extends JBPopupFactory {
Point p = getVisibleBestPopupLocation(editor);
if (p == null) {
final Rectangle visibleArea = editor.getScrollingModel().getVisibleArea();
p = new Point((visibleArea.x + visibleArea.width) / 2, (visibleArea.y + visibleArea.height) / 2);
p = new Point(visibleArea.x + visibleArea.width / 3, visibleArea.y + visibleArea.height / 2);
}
return new RelativePoint(editor.getContentComponent(), p);
}
@@ -1157,7 +1157,7 @@
<option name="NOTIFICATION_BACKGROUND" value="5c5c42" />
<option name="READONLY_FRAGMENT_BACKGROUND" value="" />
<option name="RECURSIVE_CALL_ATTRIBUTES" value="574300" />
<option name="RIGHT_MARGIN_COLOR" value="323232" />
<option name="RIGHT_MARGIN_COLOR" value="4d4d4d" />
<option name="SELECTED_INDENT_GUIDE" value="505050" />
<option name="SELECTED_TEARLINE_COLOR" value="787878" />
<option name="SELECTION_BACKGROUND" value="214283" />
@@ -27,8 +27,6 @@
<projectService serviceInterface="com.intellij.remoteServer.configuration.deployment.DeploymentConfigurationManager"
serviceImplementation="com.intellij.remoteServer.impl.configuration.deployment.DeploymentConfigurationManagerImpl"/>
<remoteServer.deploymentSource.type implementation="com.intellij.remoteServer.impl.configuration.deployment.ModuleDeploymentSourceType"/>
<productivityFeaturesProvider implementation="com.intellij.remoteServer.statistics.CloudFeaturesProvider"/>
</extensions>
<application-components>
<component>
@@ -1,12 +1,11 @@
package org.jetbrains.protocolModelGenerator
abstract class BoxableType {
abstract fun getFullText(): CharSequence
abstract fun getShortText(contextNamespace: NamePath): String
abstract fun getWriteMethodName(): String
abstract val writeMethodName: String
companion object {
val STRING: BoxableType = StandaloneType(NamePath("String"), "writeString")
@@ -1,5 +1,6 @@
package org.jetbrains.protocolModelGenerator
import gnu.trove.THashMap
import org.jetbrains.jsonProtocol.ItemDescriptor
import org.jetbrains.protocolReader.TextOutput
import java.util.ArrayList
@@ -7,10 +8,6 @@ import java.util.ArrayList
abstract class ClassScope(val generator: DomainGenerator, val classContextNamespace: NamePath) {
private val additionalMemberTexts = ArrayList<TextOutConsumer>(2)
protected fun getShortClassName(): String {
return classContextNamespace.lastComponent
}
fun addMember(out: TextOutConsumer) {
additionalMemberTexts.add(out)
}
@@ -26,9 +23,7 @@ abstract class ClassScope(val generator: DomainGenerator, val classContextNamesp
}
}
abstract fun getTypeDirection(): TypeData.Direction
companion object {
fun getName(named: ItemDescriptor.Named) = named.shortName() ?: named.name()
}
abstract val typeDirection: TypeData.Direction
}
fun ItemDescriptor.Named.getName() = shortName() ?: name()
@@ -88,6 +88,8 @@ class DomainGenerator(val generator: Generator, val domain: ProtocolMetaModel.Do
}
out.closeBlock()
classScope.writeAdditionalMembers(out)
}
else {
generateRequest(command, returnType)
@@ -128,7 +130,7 @@ class DomainGenerator(val generator: Generator, val domain: ProtocolMetaModel.Do
if (!domain.domain().isEmpty()) {
out.append(domain.domain()).append('.')
}
out.append(command.name()).append("\";").closeBlock()
out.append(command.name()).append('"').semi().closeBlock()
}
}
generateTopLevelOutputClass(generator.naming.params, command.name(), command.description(), baseTypeBuilder, memberBuilder, command.parameters())
@@ -179,7 +181,19 @@ class DomainGenerator(val generator: Generator, val domain: ProtocolMetaModel.Do
}
override fun visitEnum(enumConstants: List<String>): StandaloneTypeBinding {
return createStandaloneEnumInputTypeBinding(type, enumConstants, TypeData.Direction.INPUT)
val name = type.id()
return object : StandaloneTypeBinding {
override fun getJavaType() = StandaloneType(generator.naming.inputEnum.getFullName(domain.domain(), name), "writeEnum")
override fun generate() {
val fileUpdater = generator.startJavaFile(generator.naming.inputEnum, domain, name)
fileUpdater.out.doc(type.description())
appendEnums(enumConstants, generator.naming.inputEnum.getShortName(name), true, fileUpdater.out)
fileUpdater.update()
}
override fun getDirection() = TypeData.Direction.INPUT
}
}
override fun visitArray(items: ProtocolMetaModel.ArrayItemType): StandaloneTypeBinding {
@@ -187,30 +201,19 @@ class DomainGenerator(val generator: Generator, val domain: ProtocolMetaModel.Do
// This class is responsible for generating ad hoc type.
// If we ever are to do it, we should generate into string buffer and put strings
// inside TypeDef class.
override fun getDomainName(): String {
return domain.domain()
}
override fun getDomainName() = domain.domain()
override fun getTypeDirection(): TypeData.Direction {
return TypeData.Direction.INPUT
}
override fun <T : ItemDescriptor> resolveType(typedObject: T): TypeDescriptor {
throw UnsupportedOperationException()
}
override fun getTypeDirection() = TypeData.Direction.INPUT
override fun generateNestedObject(description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?) = throw UnsupportedOperationException()
}
val itemBoxableType = generator.resolveType(items, resolveAndGenerateScope).type
val arrayType = ListType(itemBoxableType)
val target = object : Target {
val arrayType = ListType(generator.resolveType(items, resolveAndGenerateScope).type)
return createTypedefTypeBinding(type, object : Target {
override fun resolve(context: Target.ResolveContext): BoxableType {
return arrayType
}
}
return createTypedefTypeBinding(type, target, generator.naming.inputTypedef, TypeData.Direction.INPUT)
}, generator.naming.inputTypedef, TypeData.Direction.INPUT)
}
})
}
@@ -229,11 +232,8 @@ class DomainGenerator(val generator: Generator, val domain: ProtocolMetaModel.Do
val className = generator.naming.inputValue.getFullName(domain.domain(), name)
val fileUpdater = generator.startJavaFile(generator.naming.inputValue, domain, name)
val out = fileUpdater.out
if (type.description() != null) {
out.doc(type.description())
}
descriptionAndRequiredImport(type.description(), out)
out.append("@org.jetbrains.jsonProtocol.JsonType").newLine()
out.append("public interface ").append(className.lastComponent).openBlock()
val classScope = InputClassScope(this@DomainGenerator, className)
if (properties != null) {
@@ -244,29 +244,7 @@ class DomainGenerator(val generator: Generator, val domain: ProtocolMetaModel.Do
fileUpdater.update()
}
override fun getDirection(): TypeData.Direction? {
return TypeData.Direction.INPUT
}
}
}
fun createStandaloneEnumInputTypeBinding(type: ProtocolMetaModel.StandaloneType, enumConstants: List<String>, direction: TypeData.Direction): StandaloneTypeBinding {
val name = type.id()
return object : StandaloneTypeBinding {
override fun getJavaType(): BoxableType {
return StandaloneType(generator.naming.inputEnum.getFullName(domain.domain(), name), "writeEnum")
}
override fun generate() {
val fileUpdater = generator.startJavaFile(generator.naming.inputEnum, domain, name)
fileUpdater.out.doc(type.description())
appendEnums(enumConstants, generator.naming.inputEnum.getShortName(name), true, fileUpdater.out)
fileUpdater.update()
}
override fun getDirection(): TypeData.Direction? {
return direction
}
override fun getDirection() = TypeData.Direction.INPUT
}
}
@@ -297,16 +275,12 @@ class DomainGenerator(val generator: Generator, val domain: ProtocolMetaModel.Do
})
return object : StandaloneTypeBinding {
override fun getJavaType(): BoxableType {
return actualJavaType
}
override fun getJavaType() = actualJavaType
override fun generate() {
}
override fun getDirection(): TypeData.Direction? {
return direction
}
override fun getDirection() = direction
}
}
@@ -317,7 +291,7 @@ class DomainGenerator(val generator: Generator, val domain: ProtocolMetaModel.Do
val fullName = generator.naming.eventData.getFullName(domainName, event.name()).getFullText()
generateJsonProtocolInterface(fileUpdater.out, className, event.description(), event.parameters(), object : TextOutConsumer {
override fun append(out: TextOutput) {
out.newLine().append("org.jetbrains.wip.protocol.WipEventType<").append(fullName).append("> TYPE").newLine()
out.append("org.jetbrains.wip.protocol.WipEventType<").append(fullName).append("> TYPE").newLine()
out.append("\t= new org.jetbrains.wip.protocol.WipEventType<").append(fullName).append(">")
out.append("(\"").append(domainName).append('.').append(event.name()).append("\", ").append(fullName).append(".class)").openBlock()
run {
@@ -333,10 +307,8 @@ class DomainGenerator(val generator: Generator, val domain: ProtocolMetaModel.Do
}
private fun generateJsonProtocolInterface(out: TextOutput, className: String, description: String?, parameters: List<ProtocolMetaModel.Parameter>?, additionalMembersText: TextOutConsumer?) {
if (description != null) {
out.doc(description)
}
out.append("@org.jetbrains.jsonProtocol.JsonType").newLine().append("public interface ").append(className).openBlock()
descriptionAndRequiredImport(description, out)
out.append("public interface ").append(className).openBlock()
val classScope = InputClassScope(this, NamePath(className, NamePath(getPackageName(generator.naming.inputPackage, domain.domain()))))
if (additionalMembersText != null) {
classScope.addMember(additionalMembersText)
@@ -347,4 +319,12 @@ class DomainGenerator(val generator: Generator, val domain: ProtocolMetaModel.Do
classScope.writeAdditionalMembers(out)
out.closeBlock()
}
private fun descriptionAndRequiredImport(description: String?, out: TextOutput) {
out.append("import org.jetbrains.jsonProtocol.JsonType;").newLine().newLine()
if (description != null) {
out.doc(description)
}
out.append("@JsonType").newLine()
}
}
@@ -1,5 +1,6 @@
package org.jetbrains.protocolModelGenerator
import gnu.trove.THashMap
import org.jetbrains.jsonProtocol.*
import org.jetbrains.protocolReader.FileUpdater
import org.jetbrains.protocolReader.TextOutput
@@ -17,6 +18,8 @@ class Generator(outputDir: String, rootPackage: String, requestClassName: String
val parserRootInterfaceItems = ArrayList<ParserRootInterfaceItem>()
val typeMap = TypeMap()
val nestedTypeMap = THashMap<NamePath, StandaloneType>()
private val fileSet: FileSet
val naming: Naming
@@ -72,7 +75,7 @@ class Generator(outputDir: String, rootPackage: String, requestClassName: String
}
}
typeMap.setDomainGeneratorMap(domainGeneratorMap)
typeMap.domainGeneratorMap = domainGeneratorMap
for (domainGenerator in domainGeneratorMap.values()) {
domainGenerator.generateCommandsAndEvents()
@@ -229,7 +232,7 @@ fun generateMethodNameSubstitute(originalName: String, out: TextOutput): String
if (!BAD_METHOD_NAMES.contains(originalName)) {
return originalName
}
out.append("@org.jetbrains.jsonProtocol.JsonField(jsonLiteralName=\"").append(originalName).append("\")").newLine()
out.append("@org.jetbrains.jsonProtocol.JsonField(name = \"").append(originalName).append("\")").newLine()
return "get" + Character.toUpperCase(originalName.charAt(0)) + originalName.substring(1)
}
@@ -6,46 +6,27 @@ import org.jetbrains.protocolReader.TextOutput
import org.jetbrains.protocolReader.appendEnums
class InputClassScope(generator: DomainGenerator, namePath: NamePath) : ClassScope(generator, namePath) {
fun generateDeclarationBody(out: TextOutput, list: List<ItemDescriptor.Named>) {
run {
var i = 0
val n = list.size()
while (i < n) {
val named = list.get(i)
if (named.description() != null) {
out.doc(named.description())
}
for (i in 0..list.size() - 1) {
val named = list.get(i)
if (named.description() != null) {
out.doc(named.description())
}
val name = ClassScope.getName(named)
val declarationName = generateMethodNameSubstitute(name, out)
val typeDescriptor = InputMemberScope(name).resolveType<ItemDescriptor.Named>(named)
typeDescriptor.writeAnnotations(out)
out.append(typeDescriptor.type.getShortText(classContextNamespace)).space().append(declarationName).append("();")
if (i != (n - 1)) {
out.newLine().newLine()
}
i++
val name = named.getName()
val declarationName = generateMethodNameSubstitute(name, out)
val typeDescriptor = InputMemberScope(name).resolveType<ItemDescriptor.Named>(named)
typeDescriptor.writeAnnotations(out)
out.append(typeDescriptor.type.getShortText(classContextNamespace)).space().append(declarationName).append("();")
if (i != (list.size() - 1)) {
out.newLine().newLine()
}
}
}
override fun getTypeDirection(): TypeData.Direction {
return TypeData.Direction.INPUT
}
override val typeDirection = TypeData.Direction.INPUT
inner class InputMemberScope(memberName: String) : MemberScope(this@InputClassScope, memberName) {
override fun generateEnum(description: String?, enumConstants: List<String>): BoxableType {
val enumName = capitalizeFirstChar(memberName)
addMember(object : TextOutConsumer {
override fun append(out: TextOutput) {
out.newLine().doc(description)
appendEnums(enumConstants, enumName, true, out)
}
})
return StandaloneType(NamePath(enumName, classContextNamespace), "writeEnum")
}
override fun generateNestedObject(description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?): BoxableType {
val objectName = capitalizeFirstChar(memberName)
addMember(object : TextOutConsumer {
@@ -61,8 +42,8 @@ class InputClassScope(generator: DomainGenerator, namePath: NamePath) : ClassSco
for (property in properties) {
out.doc(property.description())
val methodName = generateMethodNameSubstitute(ClassScope.getName(property), out)
val memberScope = InputMemberScope(ClassScope.getName(property))
val methodName = generateMethodNameSubstitute(property.getName(), out)
val memberScope = InputMemberScope(property.getName())
val propertyTypeData = memberScope.resolveType<ProtocolMetaModel.ObjectProperty>(property)
propertyTypeData.writeAnnotations(out)
@@ -2,21 +2,18 @@ package org.jetbrains.protocolModelGenerator
open class ListType(private val itemType: BoxableType) : BoxableType() {
override fun getWriteMethodName(): String {
if (itemType == BoxableType.STRING) {
return "writeStringList"
override val writeMethodName: String
get() = when {
itemType == BoxableType.STRING -> {
"writeStringList"
}
itemType == BoxableType.LONG -> "writeLongArray"
itemType == BoxableType.INT -> "writeIntArray"
itemType == BoxableType.NUMBER -> "writeDoubleArray"
itemType == BoxableType.NUMBER -> "writeDoubleArray"
itemType is StandaloneType && itemType.writeMethodName == "writeEnum" -> "writeEnumList"
else -> "writeList"
}
else if (itemType == BoxableType.LONG) {
return "writeLongArray"
}
else if (itemType == BoxableType.INT) {
return "writeIntArray"
}
else if (itemType == BoxableType.NUMBER) {
return "writeDoubleArray"
}
return "writeList"
}
override fun getFullText(): String {
if (itemType == BoxableType.LONG || itemType == BoxableType.INT || itemType == BoxableType.NUMBER) {
@@ -29,6 +26,6 @@ open class ListType(private val itemType: BoxableType) : BoxableType() {
if (itemType == BoxableType.LONG || itemType == BoxableType.INT || itemType == BoxableType.NUMBER) {
return "${itemType.getFullText()}[]"
}
return "java.util.List<" + itemType.getShortText(contextNamespace) + '>'
return "java.util.List<${itemType.getShortText(contextNamespace)}>"
}
}
@@ -1,19 +1,34 @@
package org.jetbrains.protocolModelGenerator
import org.jetbrains.jsonProtocol.ItemDescriptor
import org.jetbrains.protocolReader.TextOutput
import org.jetbrains.protocolReader.appendEnums
/**
* Member scope is used to generate additional types that are used only from method.
* These types will be named after this method.
*/
abstract class MemberScope(private val classScope: ClassScope, protected val memberName: String) : ResolveAndGenerateScope {
override fun <T : ItemDescriptor> resolveType(typedObject: T): TypeDescriptor {
return classScope.generator.generator.resolveType(typedObject, this)
}
open class MemberScope(private val classScope: ClassScope, protected val memberName: String) : ResolveAndGenerateScope {
override fun <T : ItemDescriptor> resolveType(typedObject: T) = classScope.generator.generator.resolveType(typedObject, this)
public abstract fun generateEnum(description: String?, enumConstants: List<String>): BoxableType
fun generateEnum(description: String?, enumConstants: List<String>): BoxableType {
val enumName = capitalizeFirstChar(memberName)
val namePath = NamePath(enumName, classScope.classContextNamespace)
var type = classScope.generator.generator.nestedTypeMap.get(namePath)
if (type == null) {
type = StandaloneType(namePath, "writeEnum")
classScope.generator.generator.nestedTypeMap.put(namePath, type)
classScope.addMember(object : TextOutConsumer {
override fun append(out: TextOutput) {
out.newLine().doc(description)
appendEnums(enumConstants, enumName, classScope.typeDirection == TypeData.Direction.INPUT, out)
}
})
}
return type
}
override fun getDomainName() = classScope.generator.domain.domain()
override fun getTypeDirection() = classScope.getTypeDirection()
override fun getTypeDirection() = classScope.typeDirection
}
@@ -34,11 +34,7 @@ class MyCreateStandaloneTypeBindingVisitorBase(private val generator: DomainGene
override fun getTypeDirection() = TypeData.Direction.OUTPUT
override fun <T : ItemDescriptor> resolveType(typedObject: T) = throw UnsupportedOperationException()
override fun generateNestedObject(description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?): BoxableType {
return context.generateNestedObject("Item", description, properties)
}
override fun generateNestedObject(description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?) = context.generateNestedObject("Item", description, properties)
}).type)
}
}, generator.generator.naming.outputTypedef, TypeData.Direction.OUTPUT)
@@ -1,7 +1,6 @@
package org.jetbrains.protocolModelGenerator
class NamePath(val lastComponent: String, val parent: NamePath? = null) {
data class NamePath(val lastComponent: String, val parent: NamePath? = null) {
fun getLength(): Int {
var res = 1
run {
@@ -28,7 +28,7 @@ class OutputClassScope(generator: DomainGenerator, classNamePath: NamePath) : Cl
generateConstructor(out, mandatoryParameters)
if (mandatoryParameters.size() == 1) {
val parameter = mandatoryParameters.get(0)
val typeData = OutputMemberScope(ClassScope.getName(parameter)).resolveType<P>(parameter)
val typeData = MemberScope(this, parameter.getName()).resolveType<P>(parameter)
if (typeData.type.getFullText() == "int[]") {
val types = arrayOfNulls<BoxableType>(mandatoryParameters.size())
types[0] = object : ListType(BoxableType.INT) {
@@ -40,9 +40,7 @@ class OutputClassScope(generator: DomainGenerator, classNamePath: NamePath) : Cl
return "gnu.trove.TIntArrayList"
}
override fun getWriteMethodName(): String {
return "writeIntList"
}
override val writeMethodName = "writeIntList"
}
out.newLine().newLine()
@@ -53,13 +51,9 @@ class OutputClassScope(generator: DomainGenerator, classNamePath: NamePath) : Cl
return getFullText()
}
override fun getFullText(): String {
return "int"
}
override fun getFullText() = "int"
override fun getWriteMethodName(): String {
return "writeSingletonIntArray"
}
override val writeMethodName = "writeSingletonIntArray"
}
out.newLine().newLine()
@@ -68,26 +62,18 @@ class OutputClassScope(generator: DomainGenerator, classNamePath: NamePath) : Cl
}
}
// generate enum classes after constructor
for (parameter in parameters) {
if (parameter.getEnum() != null) {
out.newLine().newLine()
appendEnumClass(out, parameter.description(), parameter.getEnum()!!, capitalizeFirstChar((parameter.name())))
}
}
for (parameter in optionalParameters) {
out.newLine().newLine()
if (parameter.description() != null) {
out.append("/**").newLine().append(" * @param v ").append(parameter.description()!!).newLine().append(" */").newLine()
}
var type: CharSequence = OutputMemberScope(parameter.name()).resolveType<P>(parameter).type.getShortText(classContextNamespace)
var type: CharSequence = MemberScope(this, parameter.name()).resolveType<P>(parameter).type.getShortText(classContextNamespace)
if (type == javaClass<JsonReaderEx>().getCanonicalName()) {
type = "String"
}
out.append("public ").append(getShortClassName())
out.append("public ").append(classContextNamespace.lastComponent)
out.space().append(parameter.name()).append("(").append(type)
out.space().append("v").append(")").openBlock()
appendWriteValueInvocation(out, parameter, "v")
@@ -113,7 +99,7 @@ class OutputClassScope(generator: DomainGenerator, classNamePath: NamePath) : Cl
}
out.append(" */").newLine()
}
out.append("public " + getShortClassName() + '(')
out.append("public " + classContextNamespace.lastComponent + '(')
writeMethodParameters(out, parameters, parameterTypes)
out.append(')')
@@ -124,56 +110,43 @@ class OutputClassScope(generator: DomainGenerator, classNamePath: NamePath) : Cl
}
fun <P : ItemDescriptor.Named> writeWriteCalls(out: TextOutput, parameters: List<P>, parameterTypes: Array<BoxableType?>, qualifier: String?) {
run {
var i = 0
val size = parameters.size()
while (i < size) {
out.newLine()
for (i in 0..parameters.size() - 1) {
out.newLine()
if (qualifier != null) {
out.append(qualifier).append('.')
}
val parameter = parameters.get(i)
appendWriteValueInvocation(out, parameter, parameter.name(), parameterTypes[i]!!)
i++
if (qualifier != null) {
out.append(qualifier).append('.')
}
val parameter = parameters.get(i)
appendWriteValueInvocation(out, parameter, parameter.name(), parameterTypes[i]!!)
}
}
fun <P : ItemDescriptor.Named> writeMethodParameters(out: TextOutput, parameters: List<P>, parameterTypes: Array<BoxableType?>) {
run {
var i = 0
val length = parameterTypes.size()
while (i < length) {
if (parameterTypes[i] == null) {
val parameter = parameters.get(i)
parameterTypes[i] = OutputMemberScope(parameter.name()).resolveType<P>(parameter).type
}
i++
for (i in 0..parameterTypes.size() - 1) {
if (parameterTypes[i] == null) {
val parameter = parameters.get(i)
parameterTypes[i] = MemberScope(this, parameter.name()).resolveType<P>(parameter).type
}
}
var needComa = false
run {
var i = 0
val size = parameters.size()
while (i < size) {
if (needComa) {
out.comma()
}
else {
needComa = true
}
out.append(parameterTypes[i]!!.getShortText(classContextNamespace))
out.space().append(parameters.get(i).name())
i++
val size = parameters.size()
for (i in 0..size - 1) {
if (needComa) {
out.comma()
}
else {
needComa = true
}
val shortText = parameterTypes[i]!!.getShortText(classContextNamespace)
out.append(if (shortText == "String") "CharSequence" else shortText)
out.space().append(parameters.get(i).name())
}
}
private fun appendWriteValueInvocation(out: TextOutput, parameter: ItemDescriptor.Named, valueRefName: String, type: BoxableType = OutputMemberScope(parameter.name()).resolveType<ItemDescriptor.Named>(parameter).type) {
private fun appendWriteValueInvocation(out: TextOutput, parameter: ItemDescriptor.Named, valueRefName: String, type: BoxableType = MemberScope(this, parameter.name()).resolveType<ItemDescriptor.Named>(parameter).type) {
var blockOpened = false
if (parameter.optional()) {
val nullValue: String?
@@ -199,34 +172,12 @@ class OutputClassScope(generator: DomainGenerator, classNamePath: NamePath) : Cl
}
}
// todo CallArgument (we should allow write null as value)
out.append(if (parameter.name() == "value" && type.getWriteMethodName() == "writeString") "writeNullableString" else type.getWriteMethodName()).append("(")
out.append(if (parameter.name() == "value" && type.writeMethodName == "writeString") "writeNullableString" else type.writeMethodName).append("(")
out.quote(parameter.name()).comma().append(valueRefName).append(");")
if (blockOpened) {
out.closeBlock()
}
}
override fun getTypeDirection(): TypeData.Direction {
return TypeData.Direction.OUTPUT
}
inner class OutputMemberScope(memberName: String) : MemberScope(this@OutputClassScope, memberName) {
override fun generateEnum(description: String?, enumConstants: List<String>): BoxableType {
return StandaloneType(NamePath(capitalizeFirstChar(memberName), classContextNamespace), "writeEnum")
}
override fun generateNestedObject(description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?) = throw UnsupportedOperationException()
}
private fun appendEnumClass(out: TextOutput, description: String?, enumConstants: List<String>, enumName: String) {
out.doc(description)
appendEnums(enumConstants, enumName, false, out)
out.newLine().append("private final String protocolValue;").newLine()
out.newLine().append(enumName).append("(String protocolValue)").openBlock()
out.append("this.protocolValue = protocolValue;").closeBlock()
out.newLine().newLine().append("public String toString()").openBlock()
out.append("return protocolValue;").closeBlock()
out.closeBlock()
}
override val typeDirection = TypeData.Direction.OUTPUT
}
@@ -4,10 +4,10 @@ import org.jetbrains.jsonProtocol.ItemDescriptor
import org.jetbrains.jsonProtocol.ProtocolMetaModel
trait ResolveAndGenerateScope {
public fun getDomainName(): String
public fun getTypeDirection(): TypeData.Direction
fun getDomainName(): String
fun getTypeDirection(): TypeData.Direction
public fun <T : ItemDescriptor> resolveType(typedObject: T): TypeDescriptor
fun <T : ItemDescriptor> resolveType(typedObject: T): TypeDescriptor = throw UnsupportedOperationException()
public fun generateNestedObject(description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?): BoxableType
open fun generateNestedObject(description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?): BoxableType = throw UnsupportedOperationException()
}
@@ -1,8 +1,6 @@
package org.jetbrains.protocolModelGenerator
class StandaloneType(private val namePath: NamePath, private val writeMethodName: String) : BoxableType() {
override fun getWriteMethodName() = writeMethodName
class StandaloneType(private val namePath: NamePath, override val writeMethodName: String) : BoxableType() {
override fun getFullText() = namePath.getFullText()
override fun getShortText(contextNamespace: NamePath): String {
@@ -1,10 +1,25 @@
package org.jetbrains.protocolModelGenerator
import org.jetbrains.jsonProtocol.ProtocolMetaModel
import kotlin.properties.Delegates
val ANY = object : StandaloneTypeBinding {
override fun getJavaType() = BoxableType.ANY_STRING
override fun generate() {
}
override fun getDirection() = null
}
class TypeData(private val name: String) {
private var input: Input? = null
private var output: Output? = null
val input: Input by Delegates.lazy {
Input()
}
val output: Output by Delegates.lazy {
Output()
}
private var type: ProtocolMetaModel.StandaloneType? = null
private var commonBinding: StandaloneTypeBinding? = null
@@ -13,41 +28,14 @@ class TypeData(private val name: String) {
this.type = type
}
fun getInput(): Input {
if (input == null) {
input = Input()
}
return input!!
}
fun getOutput(): Output {
if (output == null) {
output = Output()
}
return output!!
}
fun get(direction: Direction): TypeRef {
return direction.get(this)
}
fun checkComplete() {
if (input != null) {
input!!.checkResolved()
}
if (output != null) {
output!!.checkResolved()
}
}
abstract class Direction {
abstract class Direction {
companion object {
val INPUT = object : Direction() {
override fun get(typeData: TypeData) = typeData.getInput()
override fun get(typeData: TypeData) = typeData.input
}
val OUTPUT = object : Direction() {
override fun get(typeData: TypeData) = typeData.getOutput()
override fun get(typeData: TypeData) = typeData.output
}
}
@@ -80,12 +68,6 @@ class TypeData(private val name: String) {
}
abstract fun resolveImpl(domainGenerator: DomainGenerator): StandaloneTypeBinding?
fun checkResolved() {
if (type == null && !(name == "int" || name == "any")) {
throw RuntimeException()
}
}
}
inner class Output : TypeRef() {
@@ -141,17 +123,4 @@ class TypeData(private val name: String) {
return domainGenerator.createStandaloneInputTypeBinding(type!!)
}
}
}
public val ANY: StandaloneTypeBinding = object : StandaloneTypeBinding {
override fun getJavaType(): BoxableType {
return BoxableType.ANY_STRING
}
override fun generate() {
}
override fun getDirection(): TypeData.Direction? {
return null
}
}
}
@@ -9,34 +9,39 @@ import java.util.ArrayList
*/
class TypeMap {
private val map = THashMap<Pair<String, String>, TypeData>()
private var domainGeneratorMap: Map<String, DomainGenerator>? = null
private val typesToGenerate = ArrayList<StandaloneTypeBinding>()
fun setDomainGeneratorMap(domainGeneratorMap: Map<String, DomainGenerator>) {
this.domainGeneratorMap = domainGeneratorMap
}
var domainGeneratorMap: Map<String, DomainGenerator>? = null
private val typesToGenerate = ArrayList<StandaloneTypeBinding>()
fun resolve(domainName: String, typeName: String, direction: TypeData.Direction): BoxableType? {
val domainGenerator = domainGeneratorMap!!.get(domainName)
if (domainGenerator == null) {
throw RuntimeException("Failed to find domain generator: " + domainName)
}
return getTypeData(domainName, typeName).get(direction).resolve(this, domainGenerator)
return direction.get(getTypeData(domainName, typeName)).resolve(this, domainGenerator)
}
fun addTypeToGenerate(binding: StandaloneTypeBinding) {
typesToGenerate.add(binding)
}
public fun generateRequestedTypes() {
// Size may grow during iteration.
//noinspection ForLoopReplaceableByForEach
for (i in typesToGenerate.indices) {
typesToGenerate.get(i).generate()
}
fun generateRequestedTypes() {
// size may grow during iteration
var list = typesToGenerate.copyToArray()
typesToGenerate.clear()
while (true) {
for (binding in list) {
binding.generate()
}
for (typeData in map.values()) {
typeData.checkComplete()
if (typesToGenerate.isEmpty()) {
break
}
else {
list = typesToGenerate.copyToArray()
typesToGenerate.clear()
}
}
}
@@ -52,7 +52,7 @@ public abstract class OutMessage {
protected void beginArguments() throws IOException {
}
protected final void writeEnum(String name, Enum<?> value) {
public final void writeEnum(String name, Enum<?> value) {
try {
beginArguments();
writer.name(name).value(value.toString());
@@ -62,7 +62,7 @@ public abstract class OutMessage {
}
}
protected final void writeMap(String name, Map<String, String> value) {
public final void writeMap(String name, Map<String, String> value) {
try {
beginArguments();
writer.name(name);
@@ -185,7 +185,7 @@ public abstract class OutMessage {
}
}
protected final <E extends OutMessage> void writeList(String name, List<E> value) {
public final <E extends OutMessage> void writeList(String name, List<E> value) {
if (value == null || value.isEmpty()) {
return;
}
@@ -227,7 +227,7 @@ public abstract class OutMessage {
}
}
protected final void writeStringList(@NotNull String name, @NotNull Collection<String> value) {
public final void writeStringList(@NotNull String name, @NotNull Collection<String> value) {
try {
beginArguments();
JsonWriters.writeStringList(writer, name, value);
@@ -237,6 +237,20 @@ public abstract class OutMessage {
}
}
public final void writeEnumList(@NotNull String name, @NotNull Collection<? extends Enum<?>> values) {
try {
beginArguments();
writer.name(name).beginArray();
for (Enum<?> item : values) {
writer.value(item.toString());
}
writer.endArray();
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void prepareWriteRaw(@NotNull OutMessage message, @NotNull String name) throws IOException {
message.writer.name(name).nullValue();
ByteBuf itemBuffer = message.buffer;
@@ -247,7 +261,7 @@ public abstract class OutMessage {
ByteBufUtilEx.writeUtf8(message.buffer, rawValue);
}
protected final void writeMessage(@NotNull String name, @NotNull OutMessage value) {
public final void writeMessage(@NotNull String name, @NotNull OutMessage value) {
try {
beginArguments();
prepareWriteRaw(this, name);
@@ -317,10 +331,10 @@ public abstract class OutMessage {
}
}
public final void writeNullableString(@NotNull String name, @Nullable String value) {
public final void writeNullableString(@NotNull String name, @Nullable CharSequence value) {
try {
beginArguments();
writer.name(name).value(value);
writer.name(name).value(value.toString());
}
catch (IOException e) {
throw new RuntimeException(e);
@@ -26,5 +26,11 @@ fun appendEnums(enumConstants: List<String>, enumName: String, input: Boolean, o
}
else {
out.semi().newLine()
out.newLine().append("private final String protocolValue;").newLine()
out.newLine().append(enumName).append("(String protocolValue)").openBlock()
out.append("this.protocolValue = protocolValue;").closeBlock()
out.newLine().newLine().append("public String toString()").openBlock()
out.append("return protocolValue;").closeBlock()
out.closeBlock()
}
}
@@ -23,10 +23,12 @@ public class GraphicsConfig {
private final Graphics2D myG;
private final Map myHints;
private final Composite myComposite;
public GraphicsConfig(Graphics g) {
myG = (Graphics2D)g;
myHints = (Map)myG.getRenderingHints().clone();
myComposite = myG.getComposite();
}
public GraphicsConfig setAntialiasing(boolean on) {
@@ -34,11 +36,17 @@ public class GraphicsConfig {
return this;
}
public GraphicsConfig setAlpha(float alpha) {
myG.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
return this;
}
public Graphics2D getG() {
return myG;
}
public void restore() {
myG.setRenderingHints(myHints);
myG.setComposite(myComposite);
}
}
@@ -48,7 +48,7 @@ public class DebuggerConfigurable implements SearchableConfigurable.Parent {
@Override
public String getHelpTopic() {
return myRootConfigurable != null ? myRootConfigurable.getHelpTopic() : null;
return "reference.idesettings.debugger";
}
@Override
@@ -80,6 +80,15 @@ public class UseOfCloneInspection extends BaseInspection {
registerMethodCallError(expression, expression);
}
@Override
public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) {
final PsiElement target = expression.resolve();
if (!(target instanceof PsiMethod) || !CloneUtils.isClone((PsiMethod)target)) {
return;
}
registerError(expression, expression);
}
@Override
public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
final String qualifiedName = reference.getQualifiedName();
@@ -133,7 +133,8 @@ public class DanglingJavadocInspection extends BaseInspection {
return;
}
if (JavaDocUtil.isInsidePackageInfo(comment) &&
PsiTreeUtil.skipSiblingsForward(comment, PsiWhiteSpace.class) instanceof PsiPackageStatement) {
PsiTreeUtil.skipSiblingsForward(comment, PsiWhiteSpace.class) instanceof PsiPackageStatement &&
"package-info.java".equals(comment.getContainingFile().getName())) {
return;
}
registerError(comment.getFirstChild());
@@ -1,5 +1,7 @@
package use_of_clone;
import java.util.concurrent.Callable;
class UseOfClone implements <warning descr="Use of 'Cloneable'">Cloneable</warning> {
void f(int[] is) {
@@ -13,6 +15,10 @@ class UseOfClone implements <warning descr="Use of 'Cloneable'">Cloneable</warni
void g(UseOfClone o) {
o.<warning descr="Call to 'clone()'">clone</warning>();
}
void h() {
Callable r = <warning descr="Use of 'this::clone'">this::clone</warning>;
}
}
interface I extends <warning descr="Use of 'Cloneable'">Cloneable</warning> {
}
@@ -75,7 +75,7 @@ public class DslActivationStatus implements PersistentStateComponent<DslActivati
}
});
public Entry get(@NotNull VirtualFile file) {
public Entry getGdslFileInfo(@NotNull VirtualFile file) {
return myStatus.get(file);
}
@@ -17,6 +17,7 @@ package org.jetbrains.plugins.groovy.dsl;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.Contract;
@@ -27,7 +28,7 @@ public class GdslUtil {
@Override
@Contract("null -> false")
public boolean value(VirtualFile file) {
return file != null && !file.isDirectory() && "gdsl".equals(file.getExtension());
return file != null && !file.isDirectory() && StringUtil.endsWith(file.getNameSequence(), ".gdsl");
}
};
static volatile boolean ourGdslStopped = false;
@@ -144,11 +144,11 @@ public class GroovyDslFileIndex extends ScalarIndexExtension<String> {
@Nullable
public static String getError(VirtualFile file) {
return DslActivationStatus.getInstance().get(file).error;
return DslActivationStatus.getInstance().getGdslFileInfo(file).error;
}
public static boolean isActivated(VirtualFile file) {
return DslActivationStatus.getInstance().get(file).status == Status.ACTIVE;
return DslActivationStatus.getInstance().getGdslFileInfo(file).status == Status.ACTIVE;
}
public static void activate(final VirtualFile vfile) {
@@ -157,7 +157,7 @@ public class GroovyDslFileIndex extends ScalarIndexExtension<String> {
}
public static Status getStatus(final VirtualFile file) {
return DslActivationStatus.getInstance().get(file).status;
return DslActivationStatus.getInstance().getGdslFileInfo(file).status;
}
private static void clearScriptCache() {
@@ -181,7 +181,7 @@ public class GroovyDslFileIndex extends ScalarIndexExtension<String> {
}
private static void setStatusAndError(@NotNull VirtualFile vfile, @NotNull Status status, @Nullable String error) {
final DslActivationStatus.Entry entry = DslActivationStatus.getInstance().get(vfile);
final DslActivationStatus.Entry entry = DslActivationStatus.getInstance().getGdslFileInfo(vfile);
entry.status = status;
entry.error = error;
}
@@ -196,7 +196,7 @@ public class GroovyDslFileIndex extends ScalarIndexExtension<String> {
}
@Nullable
public static PsiClassType pocessScriptSuperClasses(@NotNull GroovyFile scriptFile) {
public static PsiClassType processScriptSuperClasses(@NotNull GroovyFile scriptFile) {
if (!scriptFile.isScript()) return null;
final VirtualFile virtualFile = scriptFile.getVirtualFile();
@@ -310,16 +310,10 @@ public class GroovyDslFileIndex extends ScalarIndexExtension<String> {
}
private static List<VirtualFile> getGdslFiles(final Project project) {
return CachedValuesManager.getManager(project).getCachedValue(project, new CachedValueProvider<List<VirtualFile>>() {
@Nullable
@Override
public Result<List<VirtualFile>> compute() {
final List<VirtualFile> result = ContainerUtil.newArrayList();
result.addAll(getBundledGdslFiles());
result.addAll(getProjectGdslFiles(project));
return Result.create(result, PsiModificationTracker.MODIFICATION_COUNT, ProjectRootManager.getInstance(project));
}
});
final List<VirtualFile> result = ContainerUtil.newArrayList();
result.addAll(getBundledGdslFiles());
result.addAll(getProjectGdslFiles(project));
return result;
}
private static List<VirtualFile> getBundledGdslFiles() {
@@ -180,7 +180,7 @@ public class GroovyScriptClass extends LightElement implements PsiClass, Synthet
return new PsiClassType[]{type};
}
final PsiClassType superClassFromDSL = GroovyDslFileIndex.pocessScriptSuperClasses(myFile);
final PsiClassType superClassFromDSL = GroovyDslFileIndex.processScriptSuperClasses(myFile);
if (superClassFromDSL != null) {
return new PsiClassType[]{superClassFromDSL};
}
@@ -34,10 +34,7 @@ import com.intellij.debugger.impl.GenericDebuggerRunner
import com.intellij.debugger.ui.impl.watch.WatchItemDescriptor
import com.intellij.debugger.ui.tree.render.DescriptorLabelListener
import com.intellij.execution.executors.DefaultDebugExecutor
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.process.OSProcessManager
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.process.*
import com.intellij.execution.runners.ProgramRunner
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
@@ -95,7 +92,10 @@ class GroovyDebuggerTest extends GroovyCompilerTestCase {
def configuration = createScriptConfiguration(script.virtualFile.path, myModule)
edt {
ProgramRunner runner = ProgramRunner.PROGRAM_RUNNER_EP.extensions.find { it.class == GenericDebuggerRunner }
def listener = [onTextAvailable: { ProcessEvent evt, type -> /*println evt.text*/ }] as ProcessAdapter
def listener = [onTextAvailable: { ProcessEvent evt, type ->
if (type == ProcessOutputTypes.STDERR)
println evt.text
}] as ProcessAdapter
runConfiguration(DefaultDebugExecutor, listener, runner, configuration);
}
try {
@@ -403,7 +403,7 @@ trait Introspector { // 1
class FooT implements Introspector {
def a = 1
def b = 3
String toString() { 'fooInstance' }
}
@@ -433,14 +433,16 @@ new FooT().whoAmI()
}
private def resume() {
if (debugSession == null) return
debugProcess.managerThread.invoke(debugProcess.createResumeCommand(debugProcess.suspendManager.pausedContext))
}
private SuspendContextImpl waitForBreakpoint() {
Semaphore semaphore = new Semaphore()
semaphore.down()
def process = debugProcess
// wait for all events processed
debugProcess.managerThread.schedule(new DebuggerCommandImpl() {
process.managerThread.schedule(new DebuggerCommandImpl() {
@Override
protected void action() throws Exception {
semaphore.up();
@@ -450,18 +452,18 @@ new FooT().whoAmI()
assert finished: 'Too long debugger actions'
int i = 0
def suspendManager = debugProcess.suspendManager
while (i++ < ourTimeout / 10 && !suspendManager.pausedContext && !debugProcess.processHandler.processTerminated) {
def suspendManager = process.suspendManager
while (i++ < ourTimeout / 10 && !suspendManager.pausedContext && !process.processHandler.processTerminated) {
Thread.sleep(10)
}
def context = suspendManager.pausedContext
assert context: "too long process, terminated=$debugProcess.processHandler.processTerminated"
assert context: "too long process, terminated=${process.processHandler.processTerminated}"
return context
}
private DebugProcessImpl getDebugProcess() {
return getDebugSession().process
return debugSession?.process
}
private DebuggerSession getDebugSession() {
@@ -24,10 +24,14 @@ import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.light.LightElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilBase;
import com.intellij.psi.util.QualifiedName;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.NotNullPredicate;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.codeInsight.PyCodeInsightSettings;
@@ -38,6 +42,7 @@ import com.jetbrains.python.psi.impl.PyBuiltinCache;
import com.jetbrains.python.psi.impl.PyImportedModule;
import com.jetbrains.python.psi.impl.PyPsiUtils;
import com.jetbrains.python.psi.resolve.QualifiedNameFinder;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -246,32 +251,36 @@ public final class PyClassRefactoringUtil {
}
private static void restoreReference(final PyReferenceExpression node, PsiElement[] otherMovedElements) {
PsiNamedElement target = node.getCopyableUserData(ENCODED_IMPORT);
final String asName = node.getCopyableUserData(ENCODED_IMPORT_AS);
final Boolean useFromImport = node.getCopyableUserData(ENCODED_USE_FROM_IMPORT);
if (target instanceof PsiDirectory) {
target = (PsiNamedElement)PyUtil.getPackageElement((PsiDirectory)target, node);
}
if (target instanceof PyFunction) {
final PyFunction f = (PyFunction)target;
final PyClass c = f.getContainingClass();
if (c != null && c.findInitOrNew(false) == f) {
target = c;
private static void restoreReference(@NotNull PyReferenceExpression node, @NotNull PsiElement[] otherMovedElements) {
try {
PsiNamedElement target = node.getCopyableUserData(ENCODED_IMPORT);
final String asName = node.getCopyableUserData(ENCODED_IMPORT_AS);
final Boolean useFromImport = node.getCopyableUserData(ENCODED_USE_FROM_IMPORT);
if (target instanceof PsiDirectory) {
target = (PsiNamedElement)PyUtil.getPackageElement((PsiDirectory)target, node);
}
if (target instanceof PyFunction) {
final PyFunction f = (PyFunction)target;
final PyClass c = f.getContainingClass();
if (c != null && c.findInitOrNew(false) == f) {
target = c;
}
}
if (target == null) return;
if (PsiTreeUtil.isAncestor(node.getContainingFile(), target, false)) return;
if (ArrayUtil.contains(target, otherMovedElements)) return;
if (target instanceof PyFile || target instanceof PsiDirectory) {
insertImport(node, target, asName, useFromImport != null ? useFromImport : true);
}
else {
insertImport(node, target, asName, true);
}
}
if (target == null) return;
if (PsiTreeUtil.isAncestor(node.getContainingFile(), target, false)) return;
if (ArrayUtil.contains(target, otherMovedElements)) return;
if (target instanceof PyFile || target instanceof PsiDirectory) {
insertImport(node, target, asName, useFromImport != null ? useFromImport : true);
finally {
node.putCopyableUserData(ENCODED_IMPORT, null);
node.putCopyableUserData(ENCODED_IMPORT_AS, null);
node.putCopyableUserData(ENCODED_USE_FROM_IMPORT, null);
}
else {
insertImport(node, target, asName, true);
}
node.putCopyableUserData(ENCODED_IMPORT, null);
node.putCopyableUserData(ENCODED_IMPORT_AS, null);
node.putCopyableUserData(ENCODED_USE_FROM_IMPORT, null);
}
public static void insertImport(PsiElement anchor, Collection<PsiNamedElement> elements) {
@@ -371,12 +380,24 @@ public final class PyClassRefactoringUtil {
if (qualifier != null && !(resolveExpression(qualifier) instanceof PyImportedModule)) {
return;
}
final PsiElement target = resolveExpression(node);
final List<PsiElement> allResolveResults = multiResolveExpression(node);
PsiElement target = ContainerUtil.getFirstItem(allResolveResults);
if (target instanceof PsiNamedElement && !PsiTreeUtil.isAncestor(element, target, false)) {
final NameDefiner importElement = getImportElement(node);
if (!PyUtil.inSameFile(element, target) && importElement == null && !(target instanceof PsiFileSystemItem)) {
return;
}
if (target instanceof PyTargetExpression && PyNames.ALL.equals(((PyTargetExpression)target).getName())) {
for (PsiElement result : allResolveResults) {
if (result instanceof PyImportElement) {
final QualifiedName importedQName = ((PyImportElement)result).getImportedQName();
if (importedQName != null) {
target = new DynamicNamedElement(target.getContainingFile(), importedQName.toString());
break;
}
}
}
}
node.putCopyableUserData(ENCODED_IMPORT, (PsiNamedElement)target);
if (importElement instanceof PyImportElement) {
node.putCopyableUserData(ENCODED_IMPORT_AS, ((PyImportElement)importElement).getAsName());
@@ -407,6 +428,16 @@ public final class PyClassRefactoringUtil {
return null;
}
@NotNull
private static List<PsiElement> multiResolveExpression(@NotNull PyReferenceExpression expr) {
return ContainerUtil.mapNotNull(expr.getReference().multiResolve(false), new Function<ResolveResult, PsiElement>() {
@Override
public PsiElement fun(ResolveResult result) {
return result.getElement();
}
});
}
public static void updateImportOfElement(@NotNull PyImportStatementBase importStatement, @NotNull PsiNamedElement element) {
final String name = getOriginalName(element);
if (name != null) {
@@ -575,4 +606,35 @@ public final class PyClassRefactoringUtil {
//TODO: Add metaclass to the top. Add others between last attributeName and first method
return PyUtil.addElementToStatementList(assignmentStatement, aClass.getStatementList(), true);
}
private static class DynamicNamedElement extends LightElement implements PsiNamedElement {
private final PsiFile myFile;
private final String myName;
public DynamicNamedElement(@NotNull PsiFile file, @NotNull String name) {
super(file.getManager(), file.getLanguage());
myName = name;
myFile = file;
}
@Override
public String toString() {
return "DynamicNamedElement(file='" + getContainingFile().getName() + "', name='" + getName() +"')";
}
@Override
public PsiFile getContainingFile() {
return myFile;
}
@Override
public PsiElement setName(@NonNls @NotNull String name) throws IncorrectOperationException {
return null;
}
@Override
public String getName() {
return myName;
}
}
}
@@ -34,7 +34,7 @@ public class PyMoveSymbolProcessor {
private final List<UsageInfo> myUsages;
private final PsiElement[] myAllMovedElements;
private final List<PsiFile> myOptimizeImportTargets = new ArrayList<PsiFile>();
private final List<ScopeOwner> myScopeOwnersWithGlobal = new ArrayList<ScopeOwner>();
private final Set<ScopeOwner> myScopeOwnersWithGlobal = new HashSet<ScopeOwner>();
public PyMoveSymbolProcessor(@NotNull final PsiNamedElement element,
@NotNull PyFile destination,
@@ -0,0 +1,18 @@
__all__ = ['foo']
class C(object):
def foo(self):
pass
_c = C()
def _init(g):
for name in dir(_c):
if not name.startswith('_'):
g[name] = getattr(_c, name)
_init(globals())
@@ -0,0 +1,5 @@
from b import foo
def use_foo():
print(foo)
@@ -0,0 +1,5 @@
from b import foo
def use_foo():
print(foo)
@@ -0,0 +1,18 @@
__all__ = ['foo']
class C(object):
def foo(self):
pass
_c = C()
def _init(g):
for name in dir(_c):
if not name.startswith('_'):
g[name] = getattr(_c, name)
_init(globals())
@@ -0,0 +1,18 @@
__all__ = ['foo']
class C(object):
def foo(self):
pass
_c = C()
def _init(g):
for name in dir(_c):
if not name.startswith('_'):
g[name] = getattr(_c, name)
_init(globals())
@@ -0,0 +1,5 @@
from b import foo as bar
def use_foo():
print(bar)
@@ -0,0 +1,5 @@
from b import foo as bar
def use_foo():
print(bar)
@@ -0,0 +1,18 @@
__all__ = ['foo']
class C(object):
def foo(self):
pass
_c = C()
def _init(g):
for name in dir(_c):
if not name.startswith('_'):
g[name] = getattr(_c, name)
_init(globals())

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