From cbb5c09d41fa38914b947d4fe74bddc8dbaf9b5f Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Wed, 26 Nov 2014 21:24:00 +0100 Subject: [PATCH 01/27] method refs: use one thread local for all functional expressions --- .../LambdaCanBeMethodReferenceInspection.java | 2 +- .../MethodReferenceCompletionProvider.java | 5 ++-- .../src/com/intellij/psi/LambdaUtil.java | 29 ++++++++++++++----- .../intellij/psi/PsiMethodReferenceUtil.java | 12 -------- .../com/intellij/psi/impl/PsiImplUtil.java | 4 +-- .../InputOutputConstraintFormula.java | 7 +---- ...ethodReferenceCompatibilityConstraint.java | 3 +- .../tree/java/MethodReferenceResolver.java | 12 +------- .../tree/java/PsiLambdaExpressionImpl.java | 23 ++++----------- .../PsiMethodReferenceExpressionImpl.java | 2 +- 10 files changed, 35 insertions(+), 64 deletions(-) diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/LambdaCanBeMethodReferenceInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/LambdaCanBeMethodReferenceInspection.java index 45f3e66fa98c..6a8f24e65ef8 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/LambdaCanBeMethodReferenceInspection.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/LambdaCanBeMethodReferenceInspection.java @@ -101,7 +101,7 @@ public class LambdaCanBeMethodReferenceInspection extends BaseJavaBatchLocalInsp final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(callExpression.getProject()); final PsiMethodReferenceExpression methodReferenceExpression = (PsiMethodReferenceExpression)elementFactory.createExpressionFromText(methodReferenceText, callExpression); - final Map map = PsiMethodReferenceUtil.getFunctionalTypeMap(); + final Map map = LambdaUtil.getFunctionalTypeMap(); try { map.put(methodReferenceExpression, functionalInterfaceType); final JavaResolveResult result = methodReferenceExpression.advancedResolve(false); diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/MethodReferenceCompletionProvider.java b/java/java-impl/src/com/intellij/codeInsight/completion/MethodReferenceCompletionProvider.java index 494ed110b254..4bf336995b1f 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/MethodReferenceCompletionProvider.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/MethodReferenceCompletionProvider.java @@ -50,9 +50,8 @@ public class MethodReferenceCompletionProvider extends CompletionProvider map = PsiMethodReferenceUtil.getFunctionalTypeMap(); + new ExpectedTypeInfoImpl(returnType, ExpectedTypeInfo.TYPE_OR_SUBTYPE, returnType, TailType.UNKNOWN, null, ExpectedTypeInfoImpl.NULL); + final Map map = LambdaUtil.getFunctionalTypeMap(); Consumer noTypeCheck = new Consumer() { @Override public void consume(final LookupElement lookupElement) { diff --git a/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java b/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java index 7f707200d6c6..68e12a637ae1 100644 --- a/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java @@ -22,6 +22,7 @@ import com.intellij.openapi.util.registry.Registry; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.infos.MethodCandidateInfo; import com.intellij.psi.util.*; +import com.intellij.util.containers.HashMap; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -286,6 +287,15 @@ public class LambdaUtil { element = parent; parent = parent.getParent(); } + + final Map map = ourFunctionTypes.get(); + if (map != null) { + final PsiType type = map.get(expression); + if (type != null) { + return type; + } + } + if (parent instanceof PsiArrayInitializerExpression) { final PsiType psiType = ((PsiArrayInitializerExpression)parent).getType(); if (psiType instanceof PsiArrayType) { @@ -327,13 +337,6 @@ public class LambdaUtil { return properties.getSubstitutor().substitute(getNormalizedType(parameters[finalLambdaIdx])); } } - final Map map = ourFunctionTypes.get(); - if (map != null) { - final PsiType type = map.get(expression); - if (type != null) { - return type; - } - } final JavaResolveResult resolveResult = contextCall.resolveMethodGenerics(); final PsiElement resolve = resolveResult.getElement(); if (resolve instanceof PsiMethod) { @@ -518,7 +521,17 @@ public class LambdaUtil { } return false; } - + + @NotNull + public static Map getFunctionalTypeMap() { + Map map = ourFunctionTypes.get(); + if (map == null) { + map = new HashMap(); + ourFunctionTypes.set(map); + } + return map; + } + public static class TypeParamsChecker extends PsiTypeVisitor { private PsiMethod myMethod; private final PsiClass myClass; diff --git a/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java b/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java index 3347d8319c53..6118e1b9bf89 100644 --- a/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java @@ -27,8 +27,6 @@ import java.util.Map; * User: anna */ public class PsiMethodReferenceUtil { - public static ThreadLocal> ourRefs = new ThreadLocal>(); - public static final Logger LOG = Logger.getInstance("#" + PsiMethodReferenceUtil.class.getName()); public static boolean hasReceiver(PsiType[] parameterTypes, QualifierResolveResult qualifierResolveResult, PsiMethodReferenceExpression methodRef) { @@ -97,16 +95,6 @@ public class PsiMethodReferenceUtil { return !varargs || parameterTypes.length - 1 <= argTypes.length - offset; } - @NotNull - public static Map getFunctionalTypeMap() { - Map map = ourRefs.get(); - if (map == null) { - map = new HashMap(); - ourRefs.set(map); - } - return map; - } - public static class QualifierResolveResult { private final PsiClass myContainingClass; private final PsiSubstitutor mySubstitutor; diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java b/java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java index 344ac1627392..7641f629fa24 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java @@ -746,8 +746,8 @@ public class PsiImplUtil { return JavaResolveResult.EMPTY_ARRAY; } if (element instanceof PsiMethodReferenceExpression) { - // method refs: do not cache results during parent conflict resolving - final Map map = PsiMethodReferenceUtil.ourRefs.get(); + // method refs: do not cache results during parent conflict resolving, acceptable checks, etc + final Map map = LambdaUtil.ourFunctionTypes.get(); if (map != null && map.containsKey(element)) { return (JavaResolveResult[])resolver.resolve(element, psiFile, incompleteCode); } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/InputOutputConstraintFormula.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/InputOutputConstraintFormula.java index e5f5a8a8d483..8edb864a2391 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/InputOutputConstraintFormula.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/InputOutputConstraintFormula.java @@ -112,12 +112,7 @@ public abstract class InputOutputConstraintFormula implements ConstraintFormula public void apply(PsiSubstitutor substitutor, boolean cache) { setT(substitutor.substitute(getT())); if (cache) { - Map map = LambdaUtil.ourFunctionTypes.get(); - if (map == null) { - map = new HashMap(); - LambdaUtil.ourFunctionTypes.set(map); - } - map.put(getExpression(), getT()); + LambdaUtil.getFunctionalTypeMap().put(getExpression(), getT()); } } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/PsiMethodReferenceCompatibilityConstraint.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/PsiMethodReferenceCompatibilityConstraint.java index 45018296d888..ac79be8a50ac 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/PsiMethodReferenceCompatibilityConstraint.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/PsiMethodReferenceCompatibilityConstraint.java @@ -21,7 +21,6 @@ import com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfacePa import com.intellij.psi.impl.source.resolve.graphInference.InferenceSession; import com.intellij.psi.impl.source.resolve.graphInference.PsiPolyExpressionUtil; import com.intellij.psi.infos.MethodCandidateInfo; -import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.TypeConversionUtil; @@ -124,7 +123,7 @@ public class PsiMethodReferenceCompatibilityConstraint implements ConstraintForm return true; } - final Map map = PsiMethodReferenceUtil.getFunctionalTypeMap(); + final Map map = LambdaUtil.getFunctionalTypeMap(); final PsiType added = map.put(myExpression, session.startWithFreshVars(groundTargetType)); final JavaResolveResult resolve; try { diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/MethodReferenceResolver.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/MethodReferenceResolver.java index 7b17460255c5..703b1287a6c5 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/MethodReferenceResolver.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/MethodReferenceResolver.java @@ -174,17 +174,7 @@ public class MethodReferenceResolver implements ResolveCache.PolyVariantContextR } protected PsiType getInterfaceType(PsiMethodReferenceExpression reference) { - PsiType functionalInterfaceType = null; - final Map map = PsiMethodReferenceUtil.ourRefs.get(); - if (map != null) { - functionalInterfaceType = FunctionalInterfaceParameterizationUtil.getGroundTargetType(map.get(reference)); - } - - if (functionalInterfaceType == null) { - functionalInterfaceType = reference.getFunctionalInterfaceType(); - } - - return functionalInterfaceType; + return reference.getFunctionalInterfaceType(); } protected PsiConflictResolver createResolver(PsiMethodReferenceExpressionImpl referenceExpression, diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiLambdaExpressionImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiLambdaExpressionImpl.java index 364017055c98..8c738a70fea5 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiLambdaExpressionImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiLambdaExpressionImpl.java @@ -181,11 +181,6 @@ public class PsiLambdaExpressionImpl extends ExpressionPsiElement implements Psi leftType = FunctionalInterfaceParameterizationUtil.getGroundTargetType(leftType, this); final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(leftType); - final PsiClass psiClass = resolveResult.getElement(); - if (psiClass instanceof PsiAnonymousClass) { - return isAcceptable(((PsiAnonymousClass)psiClass).getBaseClassType()); - } - if (MethodCandidateInfo.ourOverloadGuard.currentStack().contains(argsList)) { final MethodCandidateInfo.CurrentCandidateProperties candidateProperties = MethodCandidateInfo.getCurrentMethod(argsList); if (candidateProperties != null) { @@ -200,13 +195,6 @@ public class PsiLambdaExpressionImpl extends ExpressionPsiElement implements Psi } } - final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(resolveResult); - - if (interfaceMethod == null) return false; - - final PsiSubstitutor substitutor = LambdaUtil.getSubstitutor(interfaceMethod, resolveResult); - - assert leftType != null; if (!isPotentiallyCompatible(leftType)) { return false; } @@ -215,7 +203,10 @@ public class PsiLambdaExpressionImpl extends ExpressionPsiElement implements Psi return true; } - + final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(resolveResult); + if (interfaceMethod == null) return false; + + final PsiSubstitutor substitutor = LambdaUtil.getSubstitutor(interfaceMethod, resolveResult); if (hasFormalParameterTypes()) { final PsiParameter[] lambdaParameters = getParameterList().getParameters(); @@ -235,11 +226,7 @@ public class PsiLambdaExpressionImpl extends ExpressionPsiElement implements Psi PsiType methodReturnType = interfaceMethod.getReturnType(); if (methodReturnType != null && methodReturnType != PsiType.VOID) { - Map map = LambdaUtil.ourFunctionTypes.get(); - if (map == null) { - map = new HashMap(); - LambdaUtil.ourFunctionTypes.set(map); - } + Map map = LambdaUtil.getFunctionalTypeMap(); try { if (map.put(this, leftType) != null) { return false; diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java index 32545c51df0d..ab331933b437 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java @@ -409,7 +409,7 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase // the result of applying capture conversion (5.1.10) to the return type of the invocation type (15.12.2.6) of the chosen declaration is R', // where R is the target type that may be used to infer R'; neither R nor R' is void; and R' is compatible with R in an assignment context. - Map map = PsiMethodReferenceUtil.getFunctionalTypeMap(); + Map map = LambdaUtil.getFunctionalTypeMap(); final JavaResolveResult result; try { if (map.put(this, left) != null) { From 25e11f1f2c11badaa6be832e14d2e8a055f90886 Mon Sep 17 00:00:00 2001 From: Dmitry Avdeev Date: Thu, 27 Nov 2014 13:06:31 +0300 Subject: [PATCH 02/27] ensure console view will be disposed --- plugins/junit/src/com/intellij/execution/junit/TestObject.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/plugins/junit/src/com/intellij/execution/junit/TestObject.java b/plugins/junit/src/com/intellij/execution/junit/TestObject.java index 896a1aa24020..70cc1bcd33dc 100644 --- a/plugins/junit/src/com/intellij/execution/junit/TestObject.java +++ b/plugins/junit/src/com/intellij/execution/junit/TestObject.java @@ -289,6 +289,7 @@ public abstract class TestObject implements JavaCommandLine { final TestProxy unboundOutputRoot = new TestProxy(new RootTestInfo()); final JUnitConsoleProperties consoleProperties = new JUnitConsoleProperties(myConfiguration, executor); final JUnitTreeConsoleView consoleView = new JUnitTreeConsoleView(consoleProperties, myEnvironment, unboundOutputRoot); + Disposer.register(myConfiguration.getProject(), consoleView); consoleView.initUI(); consoleView.attachToProcess(handler); unboundOutputRoot.setPrinter(consoleView.getPrinter()); @@ -392,6 +393,7 @@ public abstract class TestObject implements JavaCommandLine { JUNIT_TEST_FRAMEWORK_NAME, testConsoleProperties, myEnvironment, null); + Disposer.register(myConfiguration.getProject(), consoleView); consoleView.attachToProcess(handler); RerunFailedTestsAction rerunFailedTestsAction = new RerunFailedTestsAction(consoleView, testConsoleProperties); From 37c145886b416f53047acd4c2bcb32ba78cef093 Mon Sep 17 00:00:00 2001 From: Sergey Ignatov Date: Thu, 27 Nov 2014 14:02:13 +0300 Subject: [PATCH 03/27] IDEA-133338 Editor: visual defects on mouse over Analysis indicator (traffic light) --- .../com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java | 1 + 1 file changed, 1 insertion(+) diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java index 75c64d6e4f89..3503cb60cb04 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java @@ -472,6 +472,7 @@ public class EditorMarkupModelImpl extends MarkupModelImpl implements EditorMark private class ErrorStripeButton extends JButton { private ErrorStripeButton() { setFocusable(false); + setOpaque(false); } @Override From cabbbe789808b28e946e6ec5d67ce8a926e19729 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yann=20C=C3=A9bron?= Date: Thu, 27 Nov 2014 12:05:21 +0100 Subject: [PATCH 04/27] LocalQuickFix/IntentionAction javadoc: add note about *PriorityAction --- .../codeInsight/intention/IntentionAction.java | 5 ++++- .../com/intellij/codeInspection/LocalQuickFix.java | 11 +++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/platform/analysis-api/src/com/intellij/codeInsight/intention/IntentionAction.java b/platform/analysis-api/src/com/intellij/codeInsight/intention/IntentionAction.java index aad4afca4b40..a76d24820f33 100644 --- a/platform/analysis-api/src/com/intellij/codeInsight/intention/IntentionAction.java +++ b/platform/analysis-api/src/com/intellij/codeInsight/intention/IntentionAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,6 +28,9 @@ import org.jetbrains.annotations.NotNull; *

* Implement {@link com.intellij.openapi.util.Iconable Iconable} interface to * change icon in intention popup menu. + *

+ * Implement {@link com.intellij.codeInsight.intention.HighPriorityAction HighPriorityAction} or + * {@link com.intellij.codeInsight.intention.LowPriorityAction LowPriorityAction} to change ordering. * * @see IntentionManager#registerIntentionAndMetaData(com.intellij.codeInsight.intention.IntentionAction, java.lang.String...) */ diff --git a/platform/analysis-api/src/com/intellij/codeInspection/LocalQuickFix.java b/platform/analysis-api/src/com/intellij/codeInspection/LocalQuickFix.java index bf0a35c14983..585e89de8f38 100644 --- a/platform/analysis-api/src/com/intellij/codeInspection/LocalQuickFix.java +++ b/platform/analysis-api/src/com/intellij/codeInspection/LocalQuickFix.java @@ -17,15 +17,18 @@ package com.intellij.codeInspection; /** * QuickFix based on {@link com.intellij.codeInspection.ProblemDescriptor ProblemDescriptor} - * - * Implement {@link com.intellij.openapi.util.Iconable Iconable} interface to - * change icon in quick fix popup menu - * + *

* N.B. Please DO NOT store PSI elements inside the LocalQuickFix instance, to avoid holding too much PSI files during inspection. * Instead, use the {@link ProblemDescriptor#getPsiElement()} * in {@link QuickFix#applyFix(com.intellij.openapi.project.Project, CommonProblemDescriptor)} * to retrieve the PSI context the fix will work on. * See also {@link LocalQuickFixOnPsiElement} which uses {@link com.intellij.psi.SmartPsiElementPointer} instead of storing PSI elements. + *

+ * Implement {@link com.intellij.openapi.util.Iconable Iconable} interface to + * change icon in quick fix popup menu. + *

+ * Implement {@link com.intellij.codeInsight.intention.HighPriorityAction HighPriorityAction} or + * {@link com.intellij.codeInsight.intention.LowPriorityAction LowPriorityAction} to change ordering. * * @author max * @see LocalQuickFixBase From 4a7f9dd72f56cd6195018a10b8b6f1e48dfcd045 Mon Sep 17 00:00:00 2001 From: Denis Fokin Date: Thu, 27 Nov 2014 14:12:48 +0300 Subject: [PATCH 05/27] IDEA-106716 Don't steal focus (refactoring) --- .../intellij/openapi/ui/impl/DialogWrapperPeerImpl.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/impl/DialogWrapperPeerImpl.java b/platform/platform-impl/src/com/intellij/openapi/ui/impl/DialogWrapperPeerImpl.java index 7a1606f816b9..edeacb23222c 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/impl/DialogWrapperPeerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/impl/DialogWrapperPeerImpl.java @@ -203,10 +203,6 @@ public class DialogWrapperPeerImpl extends DialogWrapperPeer implements FocusTra } myDialog.setModalityType(modalityType); } - - if (Registry.is("suppress.focus.stealing")) { - setAutoRequestFocus(false); - } } /** @see DialogWrapper#DialogWrapper(boolean, boolean) @@ -248,6 +244,11 @@ public class DialogWrapperPeerImpl extends DialogWrapperPeer implements FocusTra } myDialog = new MyDialog(owner, myWrapper, myProject, myWindowFocusedCallback, myTypeAheadDone, myTypeAheadCallback); + + if (Registry.is("suppress.focus.stealing")) { + setAutoRequestFocus(false); + } + myDialog.setModalityType(ideModalityType.toAwtModality()); myCanBeParent = canBeParent; From 6d423dc8b20e72ff48aaa425dc2a81c8ed4d5868 Mon Sep 17 00:00:00 2001 From: Konstantin Bulenkov Date: Thu, 27 Nov 2014 12:18:19 +0100 Subject: [PATCH 06/27] IDEA-133150 VersionControl tool window: with ShowViewsAsTabs==false and some History tab active tool window title looks confusing --- .../src/com/intellij/ui/content/impl/TabbedContentImpl.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/platform/platform-impl/src/com/intellij/ui/content/impl/TabbedContentImpl.java b/platform/platform-impl/src/com/intellij/ui/content/impl/TabbedContentImpl.java index 1738391baaf4..7c9951a5e056 100644 --- a/platform/platform-impl/src/com/intellij/ui/content/impl/TabbedContentImpl.java +++ b/platform/platform-impl/src/com/intellij/ui/content/impl/TabbedContentImpl.java @@ -80,6 +80,11 @@ public class TabbedContentImpl extends ContentImpl implements TabbedContent { } } + @Override + public String getDisplayName() { + return getTabName(); + } + @Override public void selectContent(int index) { Pair tab = myTabs.get(index); From fe53c402c883b83991f9829cccf06613905578b3 Mon Sep 17 00:00:00 2001 From: Sergey Ignatov Date: Thu, 27 Nov 2014 14:23:18 +0300 Subject: [PATCH 07/27] IDEA-131616 Clicking inspection status square in scrollbar scrolls up one line at a time but shouldn't --- .../com/intellij/util/ui/ButtonlessScrollBarUI.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/platform/platform-api/src/com/intellij/util/ui/ButtonlessScrollBarUI.java b/platform/platform-api/src/com/intellij/util/ui/ButtonlessScrollBarUI.java index 5279e83357c7..60c5bc326a79 100644 --- a/platform/platform-api/src/com/intellij/util/ui/ButtonlessScrollBarUI.java +++ b/platform/platform-api/src/com/intellij/util/ui/ButtonlessScrollBarUI.java @@ -250,6 +250,19 @@ public class ButtonlessScrollBarUI extends BasicScrollBarUI { }; } + @Override + protected ArrowButtonListener createArrowButtonListener() { + return new ArrowButtonListener() { + @Override + public void mousePressed(MouseEvent event) { + } + + @Override + public void mouseReleased(MouseEvent event) { + } + }; + } + protected boolean isMacOverlayScrollbar() { return myMacScrollerStyle == NSScrollerHelper.Style.Overlay && isMacOverlayScrollbarSupported(); } From 6814553c6f11358e494ce6ef9afef15fccf9cbc6 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Thu, 27 Nov 2014 14:19:08 +0300 Subject: [PATCH 08/27] replaced String literal "UTF-8" with charset instance --- .../actions/GenerateAntBuildAction.java | 7 ++--- .../templates/LocalArchivedTemplate.java | 5 ++-- .../templates/RemoteTemplatesFactory.java | 5 ++-- .../SaveProjectAsTemplateAction.java | 5 ++-- .../templates/TemplateModuleBuilder.java | 7 +++-- .../com/intellij/TestClassesFilterTest.java | 5 ++-- .../intellij/psi/SrcRepositoryUseTest.java | 6 ++--- .../java/AbstractJavaFormatterTest.java | 3 ++- .../quickFix/LightQuickFixTestCase.java | 2 +- .../com/intellij/util/CompressionUtil.java | 26 +++++++++++------- .../test/ExternalSystemTestCase.java | 13 +++++---- .../documentation/AbstractExternalFilter.java | 4 +-- .../ex/GlobalInspectionContextImpl.java | 5 ++-- .../ui/DefaultInspectionToolPresentation.java | 3 ++- .../ide/fileTemplates/impl/FTManager.java | 16 ++--------- .../impl/FileTemplatesLoader.java | 5 ++-- .../impl/providers/EncryptionUtil.java | 18 +++---------- .../masterKey/MasterKeyPasswordSafe.java | 9 ++----- .../application/impl/ApplicationImpl.java | 3 ++- .../impl/stores/ProjectStoreImpl.java | 4 +-- .../updateSettings/impl/UpdateChecker.java | 9 ++++--- .../intellij/openapi/wm/impl/X11UiUtil.java | 3 ++- .../integration/IntegrationTestCase.java | 8 +++--- .../testSrc/com/intellij/ide/LocatorTest.java | 5 ++-- .../FileDocumentManagerImplTest.java | 12 ++++----- .../com/intellij/openapi/vfs/VfsUtilTest.java | 2 +- .../vfs/local/LocalFileSystemTest.java | 2 +- .../LightPlatformCodeInsightTestCase.java | 6 +++-- .../testFramework/UsefulTestCase.java | 2 +- .../intellij/openapi/util/io/FileUtilRt.java | 13 ++++++++- .../openapi/diagnostic/Attachment.java | 11 ++------ .../intellij/openapi/util/io/FileUtil.java | 10 +++++-- .../intellij/openapi/util/io/StreamUtil.java | 10 +++++-- .../src/com/intellij/util/ResourceUtil.java | 6 ++--- .../util/io/RandomAccessDataFile.java | 26 ++++++------------ .../src/com/intellij/util/io/URLUtil.java | 3 +-- .../util/io/FileAttributesReadingTest.java | 3 ++- .../intellij/openapi/util/io/IoTestUtil.java | 3 ++- .../intellij/coverage/JavaCoverageRunner.java | 18 ++++++++++++- .../configmanagement/EncodingManager.java | 7 ++--- .../template/TemplateResourceLocator.java | 3 ++- plugins/git4idea/src/git4idea/GitUtil.java | 11 +------- .../src/git4idea/branch/GitBranchUtil.java | 5 ++-- .../git4idea/commands/GitBinaryHandler.java | 4 +-- .../src/git4idea/commands/GitHandler.java | 9 ++++--- .../src/git4idea/commands/GitTextHandler.java | 9 ++++--- .../src/git4idea/config/GitConfigUtil.java | 4 +-- .../git4idea/merge/MergeChangeCollector.java | 5 ++-- .../src/git4idea/rebase/GitRebaseUtils.java | 7 ++--- .../src/git4idea/rebase/GitRebaser.java | 5 ++-- .../src/git4idea/stash/GitStashUtils.java | 4 +-- .../src/git4idea/ui/GitTagDialog.java | 5 ++-- .../plugins/github/api/GithubApiUtil.java | 18 ++++++++++++- .../plugins/github/api/GithubConnection.java | 19 +++++++++++-- .../compiler/ManifestGenerationTest.java | 2 +- .../idea/svn/svnkit/SvnKitDebugLogger.java | 9 ++----- .../tasks/context/WorkingContextManager.java | 5 ++-- .../tasks/generic/GenericRepository.java | 18 ++++++++++++- .../tasks/impl/httpclient/ResponseUtil.java | 17 +++++++++++- .../tasks/youtrack/YouTrackRepository.java | 18 ++++++++++++- .../terminal/LocalTerminalDirectRunner.java | 18 ++++++++++++- .../lang/xpath/xslt/run/OutputTabAdapter.java | 3 ++- .../ui/actions/OpenOutputAction.java | 27 +++++++++---------- .../python/debugger/pydev/RemoteDebugger.java | 4 +-- .../psi/impl/PyElementGeneratorImpl.java | 3 ++- .../intellij/spellchecker/StreamLoader.java | 6 ++--- .../spellchecker/inspector/SplitterTest.java | 5 ++-- 67 files changed, 329 insertions(+), 224 deletions(-) diff --git a/java/compiler/impl/src/com/intellij/compiler/actions/GenerateAntBuildAction.java b/java/compiler/impl/src/com/intellij/compiler/actions/GenerateAntBuildAction.java index b7d10df7a6cb..afb6a9035a20 100644 --- a/java/compiler/impl/src/com/intellij/compiler/actions/GenerateAntBuildAction.java +++ b/java/compiler/impl/src/com/intellij/compiler/actions/GenerateAntBuildAction.java @@ -32,10 +32,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.ReadonlyStatusHandler; -import com.intellij.openapi.vfs.VfsUtil; -import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.openapi.vfs.*; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -274,7 +271,7 @@ public class GenerateAntBuildAction extends CompileActionBase { * @throws FileNotFoundException if file not found */ private static PrintWriter makeWriter(final File buildxmlFile) throws UnsupportedEncodingException, FileNotFoundException { - return new PrintWriter(new OutputStreamWriter(new FileOutputStream(buildxmlFile), "UTF-8")); + return new PrintWriter(new OutputStreamWriter(new FileOutputStream(buildxmlFile), CharsetToolkit.UTF8_CHARSET)); } private void ensureFilesWritable(Project project, File[] files) throws IOException { diff --git a/java/idea-ui/src/com/intellij/platform/templates/LocalArchivedTemplate.java b/java/idea-ui/src/com/intellij/platform/templates/LocalArchivedTemplate.java index 7dede7c97755..8d69635b3cbb 100644 --- a/java/idea-ui/src/com/intellij/platform/templates/LocalArchivedTemplate.java +++ b/java/idea-ui/src/com/intellij/platform/templates/LocalArchivedTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.io.StreamUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import org.jdom.Document; import org.jdom.Element; import org.jdom.Namespace; @@ -104,7 +105,7 @@ public class LocalArchivedTemplate extends ArchivedProjectTemplate { ZipEntry entry; while ((entry = stream.getNextEntry()) != null) { if (condition.value(entry)) { - return StreamUtil.readText(stream, TemplateModuleBuilder.UTF_8); + return StreamUtil.readText(stream, CharsetToolkit.UTF8_CHARSET); } } } diff --git a/java/idea-ui/src/com/intellij/platform/templates/RemoteTemplatesFactory.java b/java/idea-ui/src/com/intellij/platform/templates/RemoteTemplatesFactory.java index bcdd02433832..956108b951f0 100644 --- a/java/idea-ui/src/com/intellij/platform/templates/RemoteTemplatesFactory.java +++ b/java/idea-ui/src/com/intellij/platform/templates/RemoteTemplatesFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import com.intellij.openapi.module.ModuleTypeManager; import com.intellij.openapi.util.ClearableLazyValue; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.io.StreamUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.platform.ProjectTemplate; import com.intellij.platform.ProjectTemplatesFactory; import com.intellij.util.ArrayUtil; @@ -92,7 +93,7 @@ public class RemoteTemplatesFactory extends ProjectTemplatesFactory { try { connection = getConnection(code + "_templates.xml"); stream = connection.getInputStream(); - String text = StreamUtil.readText(stream, TemplateModuleBuilder.UTF_8); + String text = StreamUtil.readText(stream, CharsetToolkit.UTF8_CHARSET); return createFromText(text); } catch (IOException ex) { // timeouts, lost connection etc diff --git a/java/idea-ui/src/com/intellij/platform/templates/SaveProjectAsTemplateAction.java b/java/idea-ui/src/com/intellij/platform/templates/SaveProjectAsTemplateAction.java index 328eda553ac1..c50c7605fbe4 100644 --- a/java/idea-ui/src/com/intellij/platform/templates/SaveProjectAsTemplateAction.java +++ b/java/idea-ui/src/com/intellij/platform/templates/SaveProjectAsTemplateAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,6 +42,7 @@ import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.StreamUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; @@ -177,7 +178,7 @@ public class SaveProjectAsTemplateAction extends AnAction { public InputStream getContent(final File file) throws IOException { if (virtualFile.getFileType().isBinary() || PROJECT_TEMPLATE_XML.equals(virtualFile.getName())) return STANDARD.getContent(file); String result = getEncodedContent(virtualFile, project, parameters); - return new ByteArrayInputStream(result.getBytes(TemplateModuleBuilder.UTF_8)); + return new ByteArrayInputStream(result.getBytes(CharsetToolkit.UTF8_CHARSET)); } }); } diff --git a/java/idea-ui/src/com/intellij/platform/templates/TemplateModuleBuilder.java b/java/idea-ui/src/com/intellij/platform/templates/TemplateModuleBuilder.java index 08f44ab9d3d2..645d861533af 100644 --- a/java/idea-ui/src/com/intellij/platform/templates/TemplateModuleBuilder.java +++ b/java/idea-ui/src/com/intellij/platform/templates/TemplateModuleBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,8 +66,6 @@ import java.util.zip.ZipInputStream; */ public class TemplateModuleBuilder extends ModuleBuilder { - public static final String UTF_8 = "UTF-8"; - private final ModuleType myType; private List myAdditionalFields; private ArchivedProjectTemplate myTemplate; @@ -272,7 +270,8 @@ public class TemplateModuleBuilder extends ModuleBuilder { properties.put(ProjectTemplateParameterFactory.IJ_PROJECT_NAME, projectName); } String merged = FileTemplateUtil.mergeTemplate(properties, content, true); - return StringUtilRt.convertLineSeparators(merged.replace("\\$", "$").replace("\\#", "#"), SystemInfo.isWindows ? "\r\n" : "\n").getBytes(UTF_8); + return StringUtilRt.convertLineSeparators(merged.replace("\\$", "$").replace("\\#", "#"), SystemInfo.isWindows ? "\r\n" : "\n").getBytes( + CharsetToolkit.UTF8_CHARSET); } @Nullable diff --git a/java/java-tests/testSrc/com/intellij/TestClassesFilterTest.java b/java/java-tests/testSrc/com/intellij/TestClassesFilterTest.java index 802189ddff83..d7ea86525bde 100644 --- a/java/java-tests/testSrc/com/intellij/TestClassesFilterTest.java +++ b/java/java-tests/testSrc/com/intellij/TestClassesFilterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package com.intellij; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.vfs.CharsetToolkit; import org.junit.Test; import java.io.ByteArrayInputStream; @@ -98,7 +99,7 @@ public class TestClassesFilterTest { } private static InputStreamReader getReader(String filterText) throws UnsupportedEncodingException { - return new InputStreamReader(new ByteArrayInputStream(filterText.getBytes("UTF-8"))); + return new InputStreamReader(new ByteArrayInputStream(filterText.getBytes(CharsetToolkit.UTF8_CHARSET))); } private static void checkForAllExcludedDefinedGroup(TestClassesFilter classesFilter) { diff --git a/java/java-tests/testSrc/com/intellij/psi/SrcRepositoryUseTest.java b/java/java-tests/testSrc/com/intellij/psi/SrcRepositoryUseTest.java index 5ef9f2408e90..bbf4056c70d8 100644 --- a/java/java-tests/testSrc/com/intellij/psi/SrcRepositoryUseTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/SrcRepositoryUseTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,12 +20,12 @@ import com.intellij.openapi.application.ex.PathManagerEx; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; -import com.intellij.openapi.projectRoots.impl.JavaSdkImpl; import com.intellij.openapi.projectRoots.impl.ProjectRootUtil; import com.intellij.openapi.roots.*; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileFilter; @@ -801,7 +801,7 @@ public class SrcRepositoryUseTest extends PsiTestCase{ } private static void rewriteFileExternally(VirtualFile vFile, String text) throws IOException { - FileUtil.writeToFile(new File(vFile.getPath()), text.getBytes("UTF-8")); + FileUtil.writeToFile(new File(vFile.getPath()), text.getBytes(CharsetToolkit.UTF8_CHARSET)); vFile.refresh(false, false); } diff --git a/java/java-tests/testSrc/com/intellij/psi/formatter/java/AbstractJavaFormatterTest.java b/java/java-tests/testSrc/com/intellij/psi/formatter/java/AbstractJavaFormatterTest.java index 5ea25a991a06..42ae8be5f958 100644 --- a/java/java-tests/testSrc/com/intellij/psi/formatter/java/AbstractJavaFormatterTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/formatter/java/AbstractJavaFormatterTest.java @@ -27,6 +27,7 @@ import com.intellij.openapi.roots.LanguageLevelProjectExtension; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; @@ -58,7 +59,7 @@ public abstract class AbstractJavaFormatterTest extends LightIdeaTestCase { StringBuilder result = new StringBuilder(initial.length()); List lines; try { - LineReader reader = new LineReader(new ByteArrayInputStream(initial.getBytes("UTF-8"))); + LineReader reader = new LineReader(new ByteArrayInputStream(initial.getBytes(CharsetToolkit.UTF8_CHARSET))); lines = reader.readLines(); } catch (IOException e) { diff --git a/java/testFramework/src/com/intellij/codeInsight/daemon/quickFix/LightQuickFixTestCase.java b/java/testFramework/src/com/intellij/codeInsight/daemon/quickFix/LightQuickFixTestCase.java index 26a52c661cf6..3b92d873e8ca 100644 --- a/java/testFramework/src/com/intellij/codeInsight/daemon/quickFix/LightQuickFixTestCase.java +++ b/java/testFramework/src/com/intellij/codeInsight/daemon/quickFix/LightQuickFixTestCase.java @@ -74,7 +74,7 @@ public abstract class LightQuickFixTestCase extends LightDaemonAnalyzerTestCase @Override public void run() { try { - String contents = StringUtil.convertLineSeparators(FileUtil.loadFile(testFile, CharsetToolkit.UTF8)); + String contents = StringUtil.convertLineSeparators(FileUtil.loadFile(testFile, CharsetToolkit.UTF8_CHARSET)); quickFixTestCase.configureFromFileText(testFile.getName(), contents); quickFixTestCase.bringRealEditorBack(); final Pair pair = quickFixTestCase.parseActionHintImpl(quickFixTestCase.getFile(), contents); diff --git a/platform/core-impl/src/com/intellij/util/CompressionUtil.java b/platform/core-impl/src/com/intellij/util/CompressionUtil.java index 92be79b57f7e..b754c543a5aa 100644 --- a/platform/core-impl/src/com/intellij/util/CompressionUtil.java +++ b/platform/core-impl/src/com/intellij/util/CompressionUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ import com.intellij.openapi.util.ThreadLocalCachedByteArray; import com.intellij.util.io.DataInputOutputUtil; import org.iq80.snappy.CorruptionException; import org.iq80.snappy.Snappy; +import org.jetbrains.annotations.NotNull; import java.io.DataInput; import java.io.DataOutput; @@ -33,7 +34,7 @@ public class CompressionUtil { private static final int COMPRESSION_THRESHOLD = 64; private static final ThreadLocalCachedByteArray spareBufferLocal = new ThreadLocalCachedByteArray(); - public static int writeCompressed(DataOutput out, byte[] bytes, int length) throws IOException { + public static int writeCompressed(@NotNull DataOutput out, @NotNull byte[] bytes, int length) throws IOException { if (length > COMPRESSION_THRESHOLD) { final byte[] compressedOutputBuffer = spareBufferLocal.getBuffer(Snappy.maxCompressedLength(length)); @@ -41,20 +42,23 @@ public class CompressionUtil { DataInputOutputUtil.writeINT(out, -compressedSize); out.write(compressedOutputBuffer, 0, compressedSize); return compressedSize; - } else { + } + else { DataInputOutputUtil.writeINT(out, length); out.write(bytes, 0, length); return length; } } - public static byte[] readCompressed(DataInput in) throws IOException { + @NotNull + public static byte[] readCompressed(@NotNull DataInput in) throws IOException { int size = DataInputOutputUtil.readINT(in); if (size < 0) { byte[] bytes = spareBufferLocal.getBuffer(-size); in.readFully(bytes, 0, -size); return Snappy.uncompress(bytes, 0, -size); - } else { + } + else { byte[] bytes = new byte[size]; in.readFully(bytes); return bytes; @@ -63,7 +67,8 @@ public class CompressionUtil { private static final int STRING_COMPRESSION_THRESHOLD = 1024; - public static CharSequence uncompressCharSequence(Object string, Charset charset) { + @NotNull + public static CharSequence uncompressCharSequence(@NotNull Object string, @NotNull Charset charset) { if (string instanceof CharSequence) return (CharSequence)string; byte[] b = (byte[])string; try { @@ -71,12 +76,14 @@ public class CompressionUtil { byte[] bytes = spareBufferLocal.getBuffer(uncompressedLength); int bytesLength = Snappy.uncompress(b, 0, b.length, bytes, 0); return new String(bytes, 0, bytesLength, charset); - } catch (CorruptionException ex) { + } + catch (CorruptionException ex) { throw new RuntimeException(ex); } } - public static Object compressCharSequence(CharSequence string, Charset charset) { + @NotNull + public static Object compressCharSequence(@NotNull CharSequence string, @NotNull Charset charset) { if (string.length() < STRING_COMPRESSION_THRESHOLD) { if (string instanceof CharBuffer && ((CharBuffer)string).capacity() > STRING_COMPRESSION_THRESHOLD) { string = string.toString(); // shrink to size @@ -85,7 +92,8 @@ public class CompressionUtil { } try { return Snappy.compress(string.toString().getBytes(charset)); - } catch (CorruptionException ex) { + } + catch (CorruptionException ex) { ex.printStackTrace(); return string; } diff --git a/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/test/ExternalSystemTestCase.java b/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/test/ExternalSystemTestCase.java index b4d45ef03ec8..3fc82be53f46 100644 --- a/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/test/ExternalSystemTestCase.java +++ b/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/test/ExternalSystemTestCase.java @@ -38,10 +38,7 @@ import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.ByteSequence; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; -import com.intellij.openapi.vfs.JarFileSystem; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VfsUtilCore; -import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.openapi.vfs.*; import com.intellij.packaging.artifacts.Artifact; import com.intellij.packaging.impl.compiler.ArtifactCompileScope; import com.intellij.testFramework.*; @@ -55,7 +52,9 @@ import org.junit.After; import org.junit.Before; import java.awt.*; -import java.io.*; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.*; @@ -490,10 +489,10 @@ public abstract class ExternalSystemTestCase extends UsefulTestCase { @Override protected void run(@NotNull Result result) throws Throwable { if (advanceStamps) { - file.setBinaryContent(content.getBytes("UTF-8"), -1, file.getTimeStamp() + 4000); + file.setBinaryContent(content.getBytes(CharsetToolkit.UTF8_CHARSET), -1, file.getTimeStamp() + 4000); } else { - file.setBinaryContent(content.getBytes("UTF-8"), file.getModificationStamp(), file.getTimeStamp()); + file.setBinaryContent(content.getBytes(CharsetToolkit.UTF8_CHARSET), file.getModificationStamp(), file.getTimeStamp()); } } }.execute().getResultObject(); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/documentation/AbstractExternalFilter.java b/platform/lang-impl/src/com/intellij/codeInsight/documentation/AbstractExternalFilter.java index d8d9b7cbbe50..3cc859da0d25 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/documentation/AbstractExternalFilter.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/documentation/AbstractExternalFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -361,7 +361,7 @@ public abstract class AbstractExternalFilter { while (read != null && !startSection.matcher(StringUtil.toUpperCase(read)).find()); if (input instanceof MyReader && contentEncoding != null) { - if (!contentEncoding.equalsIgnoreCase("UTF-8") && + if (!contentEncoding.equalsIgnoreCase(CharsetToolkit.UTF8) && !contentEncoding.equals(((MyReader)input).getEncoding())) { //restart page parsing with correct encoding Reader stream; diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java index 7e5f84686865..b98ae92731a2 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java @@ -54,6 +54,7 @@ import com.intellij.openapi.util.NotNullLazyValue; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.openapi.wm.ToolWindowManager; @@ -185,7 +186,7 @@ public class GlobalInspectionContextImpl extends GlobalInspectionContextBase imp new File(outputPath).mkdirs(); final File file = new File(outputPath, toolName + ext); inspectionsResults.add(file); - FileUtil.writeToFile(file, ("").getBytes("UTF-8"), true); + FileUtil.writeToFile(file, ("").getBytes(CharsetToolkit.UTF8_CHARSET), true); } catch (IOException e) { LOG.error(e); @@ -221,7 +222,7 @@ public class GlobalInspectionContextImpl extends GlobalInspectionContextBase imp final File file = new File(outputPath, toolName + ext); inspectionsResults.add(file); - OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); + OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), CharsetToolkit.UTF8_CHARSET); try { JDOMUtil.writeDocument(doc, writer, "\n"); } diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/DefaultInspectionToolPresentation.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/DefaultInspectionToolPresentation.java index 131c8002af70..66fcefae01f7 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ui/DefaultInspectionToolPresentation.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/DefaultInspectionToolPresentation.java @@ -32,6 +32,7 @@ import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FileStatus; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.profile.codeInspection.InspectionProjectProfileManagerImpl; import com.intellij.psi.PsiElement; @@ -287,7 +288,7 @@ public class DefaultInspectionToolPresentation implements ProblemDescriptionsPro pathMacroManager.collapsePaths(element); JDOMUtil.writeElement(element, writer, "\n"); } - printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName, true), "UTF-8"))); + printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName, true), CharsetToolkit.UTF8_CHARSET))); printWriter.append("\n"); printWriter.append(writer.toString()); } diff --git a/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FTManager.java b/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FTManager.java index 910dddce6391..0fad9adde99b 100644 --- a/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FTManager.java +++ b/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FTManager.java @@ -15,13 +15,10 @@ */ package com.intellij.ide.fileTemplates.impl; -import com.intellij.CommonBundle; -import com.intellij.ide.IdeBundle; import com.intellij.ide.fileTemplates.FileTemplate; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.ex.ProjectManagerEx; -import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; @@ -247,7 +244,7 @@ class FTManager { else { // both customized content on disk and corresponding template are present try { - final String diskText = StringUtil.convertLineSeparators(FileUtil.loadFile(customizedTemplateFile, CONTENT_ENCODING)); + final String diskText = StringUtil.convertLineSeparators(FileUtil.loadFile(customizedTemplateFile, CharsetToolkit.UTF8_CHARSET)); final String templateText = templateToSave.getText(); if (!diskText.equals(templateText)) { // save only if texts differ to avoid unnecessary file touching @@ -278,16 +275,7 @@ class FTManager { FileUtil.delete(templateFile); fileOutputStream = new FileOutputStream(templateFile); } - OutputStreamWriter outputStreamWriter; - try{ - outputStreamWriter = new OutputStreamWriter(fileOutputStream, CONTENT_ENCODING); - } - catch (UnsupportedEncodingException e){ - Messages.showMessageDialog(IdeBundle.message("error.unable.to.save.file.template.using.encoding", template.getName(), - CONTENT_ENCODING), - CommonBundle.getErrorTitle(), Messages.getErrorIcon()); - outputStreamWriter = new OutputStreamWriter(fileOutputStream); - } + OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, CharsetToolkit.UTF8_CHARSET); String content = template.getText(); if (!lineSeparator.equals("\n")){ diff --git a/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FileTemplatesLoader.java b/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FileTemplatesLoader.java index 8054891ca0af..6e7deed2b82d 100644 --- a/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FileTemplatesLoader.java +++ b/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FileTemplatesLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.util.lang.UrlClassLoader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -235,7 +236,7 @@ public class FileTemplatesLoader { return; } try { - final String text = FileUtil.loadFile(file, FTManager.CONTENT_ENCODING); + final String text = FileUtil.loadFile(file, CharsetToolkit.UTF8_CHARSET); manager.addTemplate(templateQName, extension).setText(text); } catch (IOException e) { diff --git a/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/EncryptionUtil.java b/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/EncryptionUtil.java index 7bbb8bc80789..37b049c48eb0 100644 --- a/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/EncryptionUtil.java +++ b/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/EncryptionUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,12 +15,12 @@ */ package com.intellij.ide.passwordSafe.impl.providers; +import com.intellij.openapi.vfs.CharsetToolkit; import org.jetbrains.annotations.NotNull; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; -import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -224,12 +224,7 @@ public class EncryptionUtil { if (len < 0 || len > plain.length - 4) { throw new IllegalStateException("Unmatched password is used"); } - try { - return new String(plain, 4, len, "UTF-8"); - } - catch (UnsupportedEncodingException e) { - throw new IllegalStateException("UTF-8 is not available", e); - } + return new String(plain, 4, len, CharsetToolkit.UTF8_CHARSET); } /** @@ -239,12 +234,7 @@ public class EncryptionUtil { * @return the UTF-8 encoded string */ public static byte[] getUTF8Bytes(String string) { - try { - return string.getBytes("UTF-8"); - } - catch (UnsupportedEncodingException e) { - throw new IllegalStateException("UTF-8 encoding is not available", e); - } + return string.getBytes(CharsetToolkit.UTF8_CHARSET); } /** diff --git a/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/MasterKeyPasswordSafe.java b/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/MasterKeyPasswordSafe.java index 6fa03d5c393e..aa061fa8521e 100644 --- a/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/MasterKeyPasswordSafe.java +++ b/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/MasterKeyPasswordSafe.java @@ -31,13 +31,13 @@ import com.intellij.openapi.progress.ProgressIndicatorProvider; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.util.ArrayUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; @@ -338,12 +338,7 @@ public class MasterKeyPasswordSafe extends BasePasswordSafeProvider { private static String decryptPassword(byte[] pw) throws MasterPasswordUnavailableException { if (!SystemInfo.isWindows) throw new AssertionError("Windows OS expected"); - try { - return new String(WindowsCryptUtils.unprotect(pw), "UTF-8"); - } - catch (UnsupportedEncodingException e) { - throw new IllegalStateException("UTF-8 not available", e); - } + return new String(WindowsCryptUtils.unprotect(pw), CharsetToolkit.UTF8_CHARSET); } public boolean isPasswordEncrypted() { diff --git a/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java b/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java index 0280ed7ce4bd..512ee8729dca 100644 --- a/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java @@ -56,6 +56,7 @@ import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.WindowManager; import com.intellij.psi.PsiLock; @@ -519,7 +520,7 @@ public class ApplicationImpl extends PlatformComponentManagerImpl implements App private static void createLocatorFile() { File locatorFile = new File(PathManager.getSystemPath() + "/" + ApplicationEx.LOCATOR_FILE_NAME); try { - byte[] data = PathManager.getHomePath().getBytes("UTF-8"); + byte[] data = PathManager.getHomePath().getBytes(CharsetToolkit.UTF8_CHARSET); FileUtil.writeToFile(locatorFile, data); } catch (IOException e) { diff --git a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/ProjectStoreImpl.java b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/ProjectStoreImpl.java index 1087519a8d0f..098bbb8ce552 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/ProjectStoreImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/ProjectStoreImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -281,7 +281,7 @@ class ProjectStoreImpl extends BaseFileConfigurableStoreImpl implements IProject final VirtualFile nameFile = ideaDir.findChild(ProjectImpl.NAME_FILE); if (nameFile != null && nameFile.isValid()) { try { - BufferedReader in = new BufferedReader(new InputStreamReader(nameFile.getInputStream(), "UTF-8")); + BufferedReader in = new BufferedReader(new InputStreamReader(nameFile.getInputStream(), CharsetToolkit.UTF8_CHARSET)); try { final String name = in.readLine(); if (name != null && name.length() > 0) { diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.java index 12d5708f9f78..f3e4b137d5e3 100644 --- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.java +++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.java @@ -36,9 +36,12 @@ import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.StandardFileSystems; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.*; +import com.intellij.util.Function; +import com.intellij.util.PlatformUtils; +import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.HttpRequests; import com.intellij.util.io.UrlConnectionUtil; @@ -648,11 +651,11 @@ public final class UpdateChecker { args.append('&'); } - args.append(URLEncoder.encode(name, "UTF-8")); + args.append(URLEncoder.encode(name, CharsetToolkit.UTF8)); String value = ourAdditionalRequestOptions.get(name); if (!StringUtil.isEmpty(value)) { - args.append('=').append(URLEncoder.encode(value, "UTF-8")); + args.append('=').append(URLEncoder.encode(value, CharsetToolkit.UTF8)); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/X11UiUtil.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/X11UiUtil.java index 2df2582626b4..4cfa1d02bf5a 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/X11UiUtil.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/X11UiUtil.java @@ -21,6 +21,7 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.WindowManager; import org.jetbrains.annotations.Nullable; @@ -150,7 +151,7 @@ public class X11UiUtil { @Nullable private String getUtfStringProperty(long window, long name) throws Exception { byte[] bytes = getWindowProperty(window, name, UTF8_STRING, FORMAT_BYTE); - return bytes != null ? new String(bytes, "UTF-8") : null; + return bytes != null ? new String(bytes, CharsetToolkit.UTF8_CHARSET) : null; } @Nullable diff --git a/platform/platform-tests/testSrc/com/intellij/history/integration/IntegrationTestCase.java b/platform/platform-tests/testSrc/com/intellij/history/integration/IntegrationTestCase.java index 61ecc2d15270..e0e7e29018f3 100644 --- a/platform/platform-tests/testSrc/com/intellij/history/integration/IntegrationTestCase.java +++ b/platform/platform-tests/testSrc/com/intellij/history/integration/IntegrationTestCase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -115,7 +115,7 @@ public abstract class IntegrationTestCase extends PlatformTestCase { } protected void setContent(VirtualFile f, String content, long timestamp) throws IOException { - f.setBinaryContent(content.getBytes("UTF-8"), -1, timestamp); + f.setBinaryContent(content.getBytes(CharsetToolkit.UTF8_CHARSET), -1, timestamp); } protected String createFileExternally(String name) throws IOException { @@ -126,7 +126,7 @@ public abstract class IntegrationTestCase extends PlatformTestCase { File f = new File(myRoot.getPath(), name); assertTrue(f.getPath(), f.getParentFile().mkdirs() || f.getParentFile().isDirectory()); assertTrue(f.getPath(), f.createNewFile() || f.exists()); - if (content != null) FileUtil.writeToFile(f, content.getBytes("UTF-8")); + if (content != null) FileUtil.writeToFile(f, content.getBytes(CharsetToolkit.UTF8_CHARSET)); return FileUtil.toSystemIndependentName(f.getPath()); } @@ -138,7 +138,7 @@ public abstract class IntegrationTestCase extends PlatformTestCase { protected void setContentExternally(String path, String content) throws IOException { File f = new File(path); - FileUtil.writeToFile(f, content.getBytes("UTF-8")); + FileUtil.writeToFile(f, content.getBytes(CharsetToolkit.UTF8_CHARSET)); assertTrue(f.getPath(), f.setLastModified(f.lastModified() + 2000)); } diff --git a/platform/platform-tests/testSrc/com/intellij/ide/LocatorTest.java b/platform/platform-tests/testSrc/com/intellij/ide/LocatorTest.java index 09c94c5ef174..efb8cc4b8ddb 100644 --- a/platform/platform-tests/testSrc/com/intellij/ide/LocatorTest.java +++ b/platform/platform-tests/testSrc/com/intellij/ide/LocatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.testFramework.PlatformLangTestCase; import java.io.File; @@ -29,7 +30,7 @@ public class LocatorTest extends PlatformLangTestCase { assertTrue("doesn't exist: " + locatorFile.getPath(), locatorFile.exists()); assertTrue("can't read: " + locatorFile.getPath(), locatorFile.canRead()); - String home = FileUtil.loadFile(locatorFile, "UTF-8"); + String home = FileUtil.loadFile(locatorFile, CharsetToolkit.UTF8_CHARSET); assertTrue(home, StringUtil.isNotEmpty(home)); assertEquals(home, PathManager.getHomePath()); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/FileDocumentManagerImplTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/FileDocumentManagerImplTest.java index 4acf5edb5892..de3d6eda6340 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/FileDocumentManagerImplTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/FileDocumentManagerImplTest.java @@ -150,7 +150,7 @@ public class FileDocumentManagerImplTest extends PlatformLangTestCase { final Document[] unsavedDocuments = myDocumentManager.getUnsavedDocuments(); assertEquals(1, unsavedDocuments.length); assertSame(document, unsavedDocuments[0]); - assertEquals("test", new String(file.contentsToByteArray(), "UTF-8")); + assertEquals("test", new String(file.contentsToByteArray(), CharsetToolkit.UTF8_CHARSET)); } public void testGetUnsavedDocuments_afterSaveAllDocuments() throws Exception { @@ -218,7 +218,7 @@ public class FileDocumentManagerImplTest extends PlatformLangTestCase { final Document[] unsavedDocuments = myDocumentManager.getUnsavedDocuments(); assertEquals(1, unsavedDocuments.length); assertSame(document, unsavedDocuments[0]); - assertEquals("test", new String(file.contentsToByteArray(), "UTF-8")); + assertEquals("test", new String(file.contentsToByteArray(), CharsetToolkit.UTF8_CHARSET)); } finally { myDocumentManager.dropAllUnsavedDocuments(); @@ -296,7 +296,7 @@ public class FileDocumentManagerImplTest extends PlatformLangTestCase { myDocumentManager.saveDocument(document); assertTrue(stamp != file.getModificationStamp()); assertEquals(document.getModificationStamp(), file.getModificationStamp()); - assertEquals("xxx test", new String(file.contentsToByteArray(), "UTF-8")); + assertEquals("xxx test", new String(file.contentsToByteArray(), CharsetToolkit.UTF8_CHARSET)); } public void testSaveAllDocuments_DocumentWasChanged() throws Exception { @@ -313,7 +313,7 @@ public class FileDocumentManagerImplTest extends PlatformLangTestCase { myDocumentManager.saveAllDocuments(); assertNotEquals(stamp, file.getModificationStamp()); - assertEquals("xxx test", new String(file.contentsToByteArray(), "UTF-8")); + assertEquals("xxx test", new String(file.contentsToByteArray(), CharsetToolkit.UTF8_CHARSET)); } public void testGetFile() throws Exception { @@ -342,7 +342,7 @@ public class FileDocumentManagerImplTest extends PlatformLangTestCase { }); myDocumentManager.saveAllDocuments(); - assertEquals("xxx test\rtest", new String(file.contentsToByteArray(), "UTF-8")); + assertEquals("xxx test\rtest", new String(file.contentsToByteArray(), CharsetToolkit.UTF8_CHARSET)); } public void testContentChanged_noDocument() throws Exception { @@ -532,7 +532,7 @@ public class FileDocumentManagerImplTest extends PlatformLangTestCase { assertEquals("old test", document.getText()); assertEquals(file.getModificationStamp(), document.getModificationStamp()); - assertEquals("old test", new String(file.contentsToByteArray(), "UTF-8")); + assertEquals("old test", new String(file.contentsToByteArray(), CharsetToolkit.UTF8_CHARSET)); assertEquals(documentStamp, document.getModificationStamp()); } diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/vfs/VfsUtilTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/vfs/VfsUtilTest.java index 1691a2894f23..753e262b5abd 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/vfs/VfsUtilTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/vfs/VfsUtilTest.java @@ -195,7 +195,7 @@ public class VfsUtilTest extends PlatformLangTestCase { private static void doAsyncRefreshTest(File temp) throws Exception { final int N = 1000; - final byte[] data = "xxx".getBytes("UTF-8"); + final byte[] data = "xxx".getBytes(CharsetToolkit.UTF8_CHARSET); LocalFileSystem fs = LocalFileSystem.getInstance(); VirtualFile vTemp = fs.findFileByIoFile(temp); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/vfs/local/LocalFileSystemTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/vfs/local/LocalFileSystemTest.java index 1a0d9c37388e..82bda836bf89 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/vfs/local/LocalFileSystemTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/vfs/local/LocalFileSystemTest.java @@ -284,7 +284,7 @@ public class LocalFileSystemTest extends PlatformLangTestCase { final VirtualFile file = myFS.refreshAndFindFileByIoFile(targetFile); assertNotNull(file); - file.setBinaryContent("hello".getBytes("UTF-8"), 0, 0, requestor); + file.setBinaryContent("hello".getBytes(CharsetToolkit.UTF8_CHARSET), 0, 0, requestor); assertTrue(file.getLength() > 0); final VirtualFile check = myFS.refreshAndFindFileByIoFile(hardLinkFile); diff --git a/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java b/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java index 524b9dc31a4b..40d8994e1cb1 100644 --- a/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java @@ -20,7 +20,9 @@ import com.intellij.codeInsight.generation.actions.CommentByLineCommentAction; import com.intellij.ide.DataManager; import com.intellij.injected.editor.DocumentWindow; import com.intellij.injected.editor.EditorWindow; -import com.intellij.openapi.actionSystem.*; +import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.application.ex.PathManagerEx; @@ -291,7 +293,7 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest assertTrue(getMessage("Cannot find file " + fullPath, message), ioFile.exists()); String fileText = null; try { - fileText = FileUtil.loadFile(ioFile, CharsetToolkit.UTF8); + fileText = FileUtil.loadFile(ioFile, CharsetToolkit.UTF8_CHARSET); } catch (IOException e) { LOG.error(e); } diff --git a/platform/testFramework/src/com/intellij/testFramework/UsefulTestCase.java b/platform/testFramework/src/com/intellij/testFramework/UsefulTestCase.java index 907a3238d564..082351e06892 100644 --- a/platform/testFramework/src/com/intellij/testFramework/UsefulTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/UsefulTestCase.java @@ -732,7 +732,7 @@ public abstract class UsefulTestCase extends TestCase { VfsTestUtil.overwriteTestData(filePath, actualText); System.out.println("File " + filePath + " created."); } - fileText = FileUtil.loadFile(new File(filePath), CharsetToolkit.UTF8); + fileText = FileUtil.loadFile(new File(filePath), CharsetToolkit.UTF8_CHARSET); } catch (FileNotFoundException e) { VfsTestUtil.overwriteTestData(filePath, actualText); diff --git a/platform/util-rt/src/com/intellij/openapi/util/io/FileUtilRt.java b/platform/util-rt/src/com/intellij/openapi/util/io/FileUtilRt.java index 50419dedb557..8a5be88690e1 100644 --- a/platform/util-rt/src/com/intellij/openapi/util/io/FileUtilRt.java +++ b/platform/util-rt/src/com/intellij/openapi/util/io/FileUtilRt.java @@ -25,6 +25,7 @@ import org.jetbrains.annotations.TestOnly; import java.io.*; import java.nio.channels.FileChannel; +import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.UUID; @@ -381,7 +382,7 @@ public class FileUtilRt { @NotNull public static char[] loadFileText(@NotNull File file) throws IOException { - return loadFileText(file, null); + return loadFileText(file, (String)null); } @NotNull @@ -396,6 +397,16 @@ public class FileUtilRt { reader.close(); } } + @NotNull + public static char[] loadFileText(@NotNull File file, @NotNull @NonNls Charset encoding) throws IOException { + Reader reader = new InputStreamReader(new FileInputStream(file), encoding); + try { + return loadText(reader, (int)file.length()); + } + finally { + reader.close(); + } + } @NotNull public static char[] loadText(@NotNull Reader reader, int length) throws IOException { diff --git a/platform/util/src/com/intellij/openapi/diagnostic/Attachment.java b/platform/util/src/com/intellij/openapi/diagnostic/Attachment.java index 50d8508261ab..df2c3975d673 100644 --- a/platform/util/src/com/intellij/openapi/diagnostic/Attachment.java +++ b/platform/util/src/com/intellij/openapi/diagnostic/Attachment.java @@ -15,13 +15,11 @@ */ package com.intellij.openapi.diagnostic; -import com.intellij.util.ArrayUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.util.Base64Converter; import com.intellij.util.PathUtilRt; import org.jetbrains.annotations.NotNull; -import java.io.UnsupportedEncodingException; - public class Attachment { public static final Attachment[] EMPTY_ARRAY = new Attachment[0]; private final String myPath; @@ -43,12 +41,7 @@ public class Attachment { @NotNull public static byte[] getBytes(@NotNull String content) { - try { - return content.getBytes("UTF-8"); - } - catch (UnsupportedEncodingException ignored) { - return ArrayUtil.EMPTY_BYTE_ARRAY; - } + return content.getBytes(CharsetToolkit.UTF8_CHARSET); } @NotNull diff --git a/platform/util/src/com/intellij/openapi/util/io/FileUtil.java b/platform/util/src/com/intellij/openapi/util/io/FileUtil.java index e1ab3edae329..c836c771bea5 100644 --- a/platform/util/src/com/intellij/openapi/util/io/FileUtil.java +++ b/platform/util/src/com/intellij/openapi/util/io/FileUtil.java @@ -19,6 +19,7 @@ import com.intellij.CommonBundle; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.util.*; import com.intellij.util.concurrency.FixedFuture; import com.intellij.util.containers.ContainerUtil; @@ -32,6 +33,7 @@ import org.jetbrains.annotations.*; import java.io.*; import java.lang.reflect.Method; +import java.nio.charset.Charset; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; @@ -1116,7 +1118,7 @@ public class FileUtil extends FileUtilRt { } public static void appendToFile(@NotNull File file, @NotNull String text) throws IOException { - writeToFile(file, text.getBytes("UTF-8"), true); + writeToFile(file, text.getBytes(CharsetToolkit.UTF8_CHARSET), true); } public static void writeToFile(@NotNull File file, @NotNull byte[] text) throws IOException { @@ -1124,7 +1126,7 @@ public class FileUtil extends FileUtilRt { } public static void writeToFile(@NotNull File file, @NotNull String text) throws IOException { - writeToFile(file, text.getBytes("UTF-8"), false); + writeToFile(file, text.getBytes(CharsetToolkit.UTF8_CHARSET), false); } public static void writeToFile(@NotNull File file, @NotNull byte[] text, int off, int len) throws IOException { @@ -1421,6 +1423,10 @@ public class FileUtil extends FileUtilRt { public static String loadFile(@NotNull File file, @Nullable @NonNls String encoding) throws IOException { return FileUtilRt.loadFile(file, encoding); } + @NotNull + public static String loadFile(@NotNull File file, @NotNull @NonNls Charset encoding) throws IOException { + return String.valueOf(FileUtilRt.loadFileText(file, encoding)); + } @NotNull public static String loadFile(@NotNull File file, @Nullable @NonNls String encoding, boolean convertLineSeparators) throws IOException { diff --git a/platform/util/src/com/intellij/openapi/util/io/StreamUtil.java b/platform/util/src/com/intellij/openapi/util/io/StreamUtil.java index 72754ddf5898..319191e523dd 100644 --- a/platform/util/src/com/intellij/openapi/util/io/StreamUtil.java +++ b/platform/util/src/com/intellij/openapi/util/io/StreamUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,9 +18,11 @@ package com.intellij.openapi.util.io; import com.intellij.openapi.diagnostic.Logger; import com.intellij.util.io.UnsyncByteArrayOutputStream; import com.intellij.util.text.StringFactory; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; +import java.nio.charset.Charset; public class StreamUtil { private StreamUtil() { @@ -64,7 +66,11 @@ public class StreamUtil { return new String(data); } - public static String readText(InputStream inputStream, String encoding) throws IOException { + public static String readText(InputStream inputStream, @NotNull String encoding) throws IOException { + final byte[] data = loadFromStream(inputStream); + return new String(data, encoding); + } + public static String readText(InputStream inputStream, @NotNull Charset encoding) throws IOException { final byte[] data = loadFromStream(inputStream); return new String(data, encoding); } diff --git a/platform/util/src/com/intellij/util/ResourceUtil.java b/platform/util/src/com/intellij/util/ResourceUtil.java index a2a857b8687c..390084d1644c 100644 --- a/platform/util/src/com/intellij/util/ResourceUtil.java +++ b/platform/util/src/com/intellij/util/ResourceUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package com.intellij.util; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.util.io.URLUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -33,7 +34,6 @@ import java.util.Locale; * @author max */ public class ResourceUtil { - @NonNls private static final String ENCODING_UTF_8 = "UTF-8"; private ResourceUtil() { } @@ -113,7 +113,7 @@ public class ResourceUtil { public static String loadText(@NotNull URL url) throws IOException { InputStream inputStream = new BufferedInputStream(URLUtil.openStream(url)); - InputStreamReader reader = new InputStreamReader(inputStream, ENCODING_UTF_8); + InputStreamReader reader = new InputStreamReader(inputStream, CharsetToolkit.UTF8_CHARSET); try { StringBuilder text = new StringBuilder(); char[] buf = new char[5000]; diff --git a/platform/util/src/com/intellij/util/io/RandomAccessDataFile.java b/platform/util/src/com/intellij/util/io/RandomAccessDataFile.java index d4383a55d03e..bcf2d1d0d77d 100644 --- a/platform/util/src/com/intellij/util/io/RandomAccessDataFile.java +++ b/platform/util/src/com/intellij/util/io/RandomAccessDataFile.java @@ -21,6 +21,7 @@ package com.intellij.util.io; import com.intellij.openapi.Forceable; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.vfs.CharsetToolkit; import org.jetbrains.annotations.NotNull; import java.io.*; @@ -138,27 +139,16 @@ public class RandomAccessDataFile implements Forceable, Closeable { } public String getUTF(long addr) { - try { - int len = getInt(addr); - byte[] bytes = new byte[len]; - get(addr + 4, bytes, 0, len); - return new String(bytes, "UTF-8"); - } - catch (UnsupportedEncodingException e) { - // Can't be - return ""; - } + int len = getInt(addr); + byte[] bytes = new byte[len]; + get(addr + 4, bytes, 0, len); + return new String(bytes, CharsetToolkit.UTF8_CHARSET); } public void putUTF(long addr, String value) { - try { - final byte[] bytes = value.getBytes("UTF-8"); - putInt(addr, bytes.length); - put(addr + 4, bytes, 0, bytes.length); - } - catch (UnsupportedEncodingException e) { - // Can't be - } + final byte[] bytes = value.getBytes(CharsetToolkit.UTF8_CHARSET); + putInt(addr, bytes.length); + put(addr + 4, bytes, 0, bytes.length); } public long length() { diff --git a/platform/util/src/com/intellij/util/io/URLUtil.java b/platform/util/src/com/intellij/util/io/URLUtil.java index 1a6e633a3266..f46b7a1884d0 100644 --- a/platform/util/src/com/intellij/util/io/URLUtil.java +++ b/platform/util/src/com/intellij/util/io/URLUtil.java @@ -31,7 +31,6 @@ import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; -import java.nio.charset.Charset; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; @@ -169,7 +168,7 @@ public class URLUtil { for (int j = 0; j < bytes.size(); j++) { bytesArray[j] = (byte)bytes.getQuick(j); } - decoded.append(new String(bytesArray, Charset.forName("UTF-8"))); + decoded.append(new String(bytesArray, CharsetToolkit.UTF8_CHARSET)); continue; } } diff --git a/platform/util/testSrc/com/intellij/openapi/util/io/FileAttributesReadingTest.java b/platform/util/testSrc/com/intellij/openapi/util/io/FileAttributesReadingTest.java index 752dec025ae0..da4d8618580a 100644 --- a/platform/util/testSrc/com/intellij/openapi/util/io/FileAttributesReadingTest.java +++ b/platform/util/testSrc/com/intellij/openapi/util/io/FileAttributesReadingTest.java @@ -19,6 +19,7 @@ import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.win32.FileInfo; import com.intellij.openapi.util.io.win32.IdeaWin32; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.util.SystemProperties; import com.intellij.util.TimeoutUtil; import org.jetbrains.annotations.NotNull; @@ -355,7 +356,7 @@ public class FileAttributesReadingTest { assertTrue(getAttributes(dir).isDirectory()); file = new File(dir, "file.txt"); - FileUtil.writeToFile(file, "test".getBytes("UTF-8")); + FileUtil.writeToFile(file, "test".getBytes(CharsetToolkit.UTF8_CHARSET)); assertTrue(file.exists()); assertFileAttributes(file); diff --git a/platform/util/testSrc/com/intellij/openapi/util/io/IoTestUtil.java b/platform/util/testSrc/com/intellij/openapi/util/io/IoTestUtil.java index 1669c5eca11a..f20aab66b4b0 100644 --- a/platform/util/testSrc/com/intellij/openapi/util/io/IoTestUtil.java +++ b/platform/util/testSrc/com/intellij/openapi/util/io/IoTestUtil.java @@ -17,6 +17,7 @@ package com.intellij.openapi.util.io; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.util.Function; import com.intellij.util.ObjectUtils; import com.intellij.util.Processor; @@ -228,7 +229,7 @@ public class IoTestUtil { try { for (int i = 0; i < data.length; i += 2) { stream.putNextEntry(new ZipEntry(data[i])); - stream.write(data[i + 1].getBytes("UTF-8")); + stream.write(data[i + 1].getBytes(CharsetToolkit.UTF8_CHARSET)); stream.closeEntry(); } } diff --git a/plugins/coverage/src/com/intellij/coverage/JavaCoverageRunner.java b/plugins/coverage/src/com/intellij/coverage/JavaCoverageRunner.java index 314e07c23a8f..182e26ccc3bf 100644 --- a/plugins/coverage/src/com/intellij/coverage/JavaCoverageRunner.java +++ b/plugins/coverage/src/com/intellij/coverage/JavaCoverageRunner.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.coverage; import com.intellij.execution.configurations.SimpleJavaParameters; @@ -5,6 +20,7 @@ import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -67,7 +83,7 @@ public abstract class JavaCoverageRunner extends CoverageRunner { } protected static void write2file(File tempFile, String arg) throws IOException { - FileUtil.writeToFile(tempFile, (arg + "\n").getBytes("UTF-8"), true); + FileUtil.writeToFile(tempFile, (arg + "\n").getBytes(CharsetToolkit.UTF8_CHARSET), true); } protected static File createTempFile() throws IOException { diff --git a/plugins/editorconfig/src/org/editorconfig/configmanagement/EncodingManager.java b/plugins/editorconfig/src/org/editorconfig/configmanagement/EncodingManager.java index 278b684e10d2..3aec6497f144 100644 --- a/plugins/editorconfig/src/org/editorconfig/configmanagement/EncodingManager.java +++ b/plugins/editorconfig/src/org/editorconfig/configmanagement/EncodingManager.java @@ -5,6 +5,7 @@ import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileDocumentManagerAdapter; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.encoding.EncodingProjectManager; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; @@ -30,9 +31,9 @@ public class EncodingManager extends FileDocumentManagerAdapter { static { Map map = new HashMap(); map.put("latin1", Charset.forName("ISO-8859-1")); - map.put("utf-8", Charset.forName("UTF-8")); - map.put("utf-16be", Charset.forName("UTF-16BE")); - map.put("utf-16le", Charset.forName("UTF-16LE")); + map.put("utf-8", CharsetToolkit.UTF8_CHARSET); + map.put("utf-16be", CharsetToolkit.UTF_16BE_CHARSET); + map.put("utf-16le", CharsetToolkit.UTF_16LE_CHARSET); encodingMap = Collections.unmodifiableMap(map); } diff --git a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/TemplateResourceLocator.java b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/TemplateResourceLocator.java index 98aedf820084..82cff7dca1cc 100644 --- a/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/TemplateResourceLocator.java +++ b/plugins/generate-tostring/src/org/jetbrains/generate/tostring/template/TemplateResourceLocator.java @@ -17,6 +17,7 @@ package org.jetbrains.generate.tostring.template; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import org.jetbrains.generate.tostring.exception.TemplateResourceException; import java.io.BufferedInputStream; @@ -70,6 +71,6 @@ public class TemplateResourceLocator { */ private static String readFile(String resource) throws IOException { BufferedInputStream in = new BufferedInputStream(TemplateResourceLocator.class.getResourceAsStream(resource)); - return StringUtil.convertLineSeparators(FileUtil.loadTextAndClose(new InputStreamReader(in, "UTF-8"))); + return StringUtil.convertLineSeparators(FileUtil.loadTextAndClose(new InputStreamReader(in, CharsetToolkit.UTF8_CHARSET))); } } diff --git a/plugins/git4idea/src/git4idea/GitUtil.java b/plugins/git4idea/src/git4idea/GitUtil.java index c0790eb6496b..245dc4ab48ee 100644 --- a/plugins/git4idea/src/git4idea/GitUtil.java +++ b/plugins/git4idea/src/git4idea/GitUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,7 +63,6 @@ import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; import java.util.*; /** @@ -87,14 +86,6 @@ public class GitUtil { return o1.getPresentableUrl().compareTo(o2.getPresentableUrl()); } }; - /** - * The UTF-8 encoding name - */ - public static final String UTF8_ENCODING = "UTF-8"; - /** - * The UTF8 charset - */ - public static final Charset UTF8_CHARSET = Charset.forName(UTF8_ENCODING); public static final String DOT_GIT = ".git"; public static final String ORIGIN_HEAD = "origin/HEAD"; diff --git a/plugins/git4idea/src/git4idea/branch/GitBranchUtil.java b/plugins/git4idea/src/git4idea/branch/GitBranchUtil.java index e07755239d45..ceddd8fca5aa 100644 --- a/plugins/git4idea/src/git4idea/branch/GitBranchUtil.java +++ b/plugins/git4idea/src/git4idea/branch/GitBranchUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,6 +26,7 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vcs.AbstractVcs; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vcs.VcsException; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.containers.ContainerUtil; @@ -436,7 +437,7 @@ public class GitBranchUtil { // the case after git init and before first commit - there is no branch and no output, and we'll take refs/heads/master String head; try { - head = FileUtil.loadFile(new File(root.getPath(), GitRepositoryFiles.GIT_HEAD), GitUtil.UTF8_ENCODING).trim(); + head = FileUtil.loadFile(new File(root.getPath(), GitRepositoryFiles.GIT_HEAD), CharsetToolkit.UTF8_CHARSET).trim(); final String prefix = "ref: refs/heads/"; return head.startsWith(prefix) ? Collections.singletonList(head.substring(prefix.length())) : diff --git a/plugins/git4idea/src/git4idea/commands/GitBinaryHandler.java b/plugins/git4idea/src/git4idea/commands/GitBinaryHandler.java index 7b935044d05e..678cf7120b97 100644 --- a/plugins/git4idea/src/git4idea/commands/GitBinaryHandler.java +++ b/plugins/git4idea/src/git4idea/commands/GitBinaryHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ import com.intellij.ide.IdeBundle; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vfs.VirtualFile; -import git4idea.GitUtil; import git4idea.GitVcs; import org.jetbrains.annotations.NotNull; @@ -126,7 +125,6 @@ public class GitBinaryHandler extends GitHandler { public void processTerminated(int exitCode) { if (exitCode != 0 && !isIgnoredErrorCode(exitCode)) { Charset cs = getCharset(); - cs = cs == null ? GitUtil.UTF8_CHARSET : cs; String message = new String(myStderr.toByteArray(), cs); if (message.length() == 0) { //noinspection ThrowableResultOfMethodCallIgnored diff --git a/plugins/git4idea/src/git4idea/commands/GitHandler.java b/plugins/git4idea/src/git4idea/commands/GitHandler.java index a1cf820e97db..94389491c9c5 100644 --- a/plugins/git4idea/src/git4idea/commands/GitHandler.java +++ b/plugins/git4idea/src/git4idea/commands/GitHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.ProcessEventListener; import com.intellij.openapi.vcs.VcsException; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; @@ -87,7 +88,8 @@ public abstract class GitHandler { @SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"}) @NonNls - private Charset myCharset = Charset.forName("UTF-8"); // Character set to use for IO + @NotNull + private Charset myCharset = CharsetToolkit.UTF8_CHARSET; // Character set to use for IO private final EventDispatcher myListeners = EventDispatcher.create(ProcessEventListener.class); @SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"}) @@ -622,6 +624,7 @@ public abstract class GitHandler { /** * @return a character set to use for IO */ + @NotNull public Charset getCharset() { return myCharset; } @@ -632,7 +635,7 @@ public abstract class GitHandler { * @param charset a character set */ @SuppressWarnings({"SameParameterValue"}) - public void setCharset(final Charset charset) { + public void setCharset(@NotNull Charset charset) { myCharset = charset; } diff --git a/plugins/git4idea/src/git4idea/commands/GitTextHandler.java b/plugins/git4idea/src/git4idea/commands/GitTextHandler.java index 7dd759f40ebd..1de385c0d4e0 100644 --- a/plugins/git4idea/src/git4idea/commands/GitTextHandler.java +++ b/plugins/git4idea/src/git4idea/commands/GitTextHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -127,17 +127,18 @@ public abstract class GitTextHandler extends GitHandler { } private static class MyOSProcessHandler extends OSProcessHandler { + @NotNull private final Charset myCharset; - public MyOSProcessHandler(Process process, GeneralCommandLine commandLine, Charset charset) { + public MyOSProcessHandler(Process process, GeneralCommandLine commandLine, @NotNull Charset charset) { super(process, commandLine.getCommandLineString()); myCharset = charset; } + @NotNull @Override public Charset getCharset() { - Charset charset = myCharset; - return charset == null ? super.getCharset() : charset; + return myCharset; } } diff --git a/plugins/git4idea/src/git4idea/config/GitConfigUtil.java b/plugins/git4idea/src/git4idea/config/GitConfigUtil.java index 4870a368c9d3..73be454a7116 100644 --- a/plugins/git4idea/src/git4idea/config/GitConfigUtil.java +++ b/plugins/git4idea/src/git4idea/config/GitConfigUtil.java @@ -19,8 +19,8 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Couple; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vcs.VcsException; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; -import git4idea.GitUtil; import git4idea.commands.GitCommand; import git4idea.commands.GitSimpleHandler; import org.jetbrains.annotations.NonNls; @@ -177,7 +177,7 @@ public class GitConfigUtil { // ignore exception } if (encoding == null || encoding.length() == 0) { - encoding = GitUtil.UTF8_ENCODING; + encoding = CharsetToolkit.UTF8; } return encoding; } diff --git a/plugins/git4idea/src/git4idea/merge/MergeChangeCollector.java b/plugins/git4idea/src/git4idea/merge/MergeChangeCollector.java index c72e738851fa..6402895e08c2 100644 --- a/plugins/git4idea/src/git4idea/merge/MergeChangeCollector.java +++ b/plugins/git4idea/src/git4idea/merge/MergeChangeCollector.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.VcsKey; import com.intellij.openapi.vcs.update.FileGroup; import com.intellij.openapi.vcs.update.UpdatedFiles; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; import git4idea.GitRevisionNumber; import git4idea.GitUtil; @@ -122,7 +123,7 @@ public class MergeChangeCollector { File mergeHeadsFile = new File(root, GitRepositoryFiles.GIT_MERGE_HEAD); try { if (mergeHeadsFile.exists()) { - String mergeHeads = new String(FileUtil.loadFileText(mergeHeadsFile, GitUtil.UTF8_ENCODING)); + String mergeHeads = new String(FileUtil.loadFileText(mergeHeadsFile, CharsetToolkit.UTF8)); for (StringScanner s = new StringScanner(mergeHeads); s.hasMoreData();) { String head = s.line(); if (head.length() == 0) { diff --git a/plugins/git4idea/src/git4idea/rebase/GitRebaseUtils.java b/plugins/git4idea/src/git4idea/rebase/GitRebaseUtils.java index e159027039b5..798472f162ef 100644 --- a/plugins/git4idea/src/git4idea/rebase/GitRebaseUtils.java +++ b/plugins/git4idea/src/git4idea/rebase/GitRebaseUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package git4idea.rebase; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import git4idea.GitRevisionNumber; @@ -93,7 +94,7 @@ public class GitRebaseUtils { File nextFile = new File(rebaseDir, "next"); int next; try { - next = Integer.parseInt(FileUtil.loadFile(nextFile, GitUtil.UTF8_ENCODING).trim()); + next = Integer.parseInt(FileUtil.loadFile(nextFile, CharsetToolkit.UTF8_CHARSET).trim()); } catch (Exception e) { if (LOG.isDebugEnabled()) { @@ -105,7 +106,7 @@ public class GitRebaseUtils { String hash = null; String subject = null; try { - BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(commitFile), GitUtil.UTF8_CHARSET)); + BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(commitFile), CharsetToolkit.UTF8_CHARSET)); try { String line; while ((line = in.readLine()) != null) { diff --git a/plugins/git4idea/src/git4idea/rebase/GitRebaser.java b/plugins/git4idea/src/git4idea/rebase/GitRebaser.java index 75e28742b965..d6aee63a9fda 100644 --- a/plugins/git4idea/src/git4idea/rebase/GitRebaser.java +++ b/plugins/git4idea/src/git4idea/rebase/GitRebaser.java @@ -24,6 +24,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vcs.VcsException; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; import git4idea.GitPlatformFacade; import git4idea.GitUtil; @@ -430,7 +431,7 @@ public class GitRebaser { } try { TreeMap pickLines = new TreeMap(); - StringScanner s = new StringScanner(new String(FileUtil.loadFileText(new File(path), GitUtil.UTF8_ENCODING))); + StringScanner s = new StringScanner(new String(FileUtil.loadFileText(new File(path), CharsetToolkit.UTF8))); while (s.hasMoreData()) { if (!s.tryConsume("pick ")) { s.line(); @@ -439,7 +440,7 @@ public class GitRebaser { String commit = s.spaceToken(); pickLines.put(commit, "pick " + commit + " " + s.line()); } - PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(path), GitUtil.UTF8_ENCODING)); + PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(path), CharsetToolkit.UTF8)); try { for (String commit : myCommits) { String key = pickLines.headMap(commit + "\u0000").lastKey(); diff --git a/plugins/git4idea/src/git4idea/stash/GitStashUtils.java b/plugins/git4idea/src/git4idea/stash/GitStashUtils.java index e1da8a349d8a..bc575ce048a0 100644 --- a/plugins/git4idea/src/git4idea/stash/GitStashUtils.java +++ b/plugins/git4idea/src/git4idea/stash/GitStashUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ public class GitStashUtils { loadStashStack(project, root, Charset.forName(GitConfigUtil.getLogEncoding(project, root)), consumer); } - public static void loadStashStack(@NotNull Project project, @NotNull VirtualFile root, final Charset charset, + public static void loadStashStack(@NotNull Project project, @NotNull VirtualFile root, @NotNull Charset charset, final Consumer consumer) { GitSimpleHandler h = new GitSimpleHandler(project, root, GitCommand.STASH.readLockingCommand()); h.setSilent(true); diff --git a/plugins/git4idea/src/git4idea/ui/GitTagDialog.java b/plugins/git4idea/src/git4idea/ui/GitTagDialog.java index 7d1c8f5f4f19..9a6d15c8ab23 100644 --- a/plugins/git4idea/src/git4idea/ui/GitTagDialog.java +++ b/plugins/git4idea/src/git4idea/ui/GitTagDialog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.VcsNotifier; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.DocumentAdapter; @@ -106,7 +107,7 @@ public class GitTagDialog extends DialogWrapper { /** * Encoding for the message file */ - @NonNls private static final String MESSAGE_FILE_ENCODING = "UTF-8"; + @NonNls private static final String MESSAGE_FILE_ENCODING = CharsetToolkit.UTF8; /** * A constructor diff --git a/plugins/github/src/org/jetbrains/plugins/github/api/GithubApiUtil.java b/plugins/github/src/org/jetbrains/plugins/github/api/GithubApiUtil.java index 063ad3bc7bb6..7ac0b46dda15 100644 --- a/plugins/github/src/org/jetbrains/plugins/github/api/GithubApiUtil.java +++ b/plugins/github/src/org/jetbrains/plugins/github/api/GithubApiUtil.java @@ -1,8 +1,24 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.jetbrains.plugins.github.api; import com.google.gson.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.message.BasicHeader; @@ -469,7 +485,7 @@ public class GithubApiUtil { boolean withClosed) throws IOException { try { String state = withClosed ? "" : " state:open"; - query = URLEncoder.encode("repo:" + user + "/" + repo + " " + query + state, "UTF-8"); + query = URLEncoder.encode("repo:" + user + "/" + repo + " " + query + state, CharsetToolkit.UTF8); String path = "/search/issues?q=" + query; //TODO: Use bodyHtml for issues - GitHub does not support this feature for SearchApi yet diff --git a/plugins/github/src/org/jetbrains/plugins/github/api/GithubConnection.java b/plugins/github/src/org/jetbrains/plugins/github/api/GithubConnection.java index 35b4a50c7a7b..3163e3dc63eb 100644 --- a/plugins/github/src/org/jetbrains/plugins/github/api/GithubConnection.java +++ b/plugins/github/src/org/jetbrains/plugins/github/api/GithubConnection.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.jetbrains.plugins.github.api; import com.google.gson.JsonElement; @@ -5,7 +20,7 @@ import com.google.gson.JsonParseException; import com.google.gson.JsonParser; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.util.net.HttpConfigurable; import com.intellij.util.net.ssl.CertificateManager; import org.apache.http.*; @@ -361,7 +376,7 @@ public class GithubConnection { @NotNull private static JsonElement parseResponse(@NotNull InputStream githubResponse) throws IOException { - Reader reader = new InputStreamReader(githubResponse, "UTF-8"); + Reader reader = new InputStreamReader(githubResponse, CharsetToolkit.UTF8_CHARSET); try { return new JsonParser().parse(reader); } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ManifestGenerationTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ManifestGenerationTest.java index 786cded84d73..65b78491237a 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ManifestGenerationTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ManifestGenerationTest.java @@ -234,7 +234,7 @@ public class ManifestGenerationTest extends MavenCompilingTestCase { VfsTestUtil.overwriteTestData(filePath, actualText); System.out.println("File " + filePath + " created."); } - fileText = FileUtil.loadFile(new File(filePath), CharsetToolkit.UTF8); + fileText = FileUtil.loadFile(new File(filePath), CharsetToolkit.UTF8_CHARSET); } catch (FileNotFoundException e) { VfsTestUtil.overwriteTestData(filePath, actualText); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/svnkit/SvnKitDebugLogger.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/svnkit/SvnKitDebugLogger.java index a70658108066..c2b958dd6e7d 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/svnkit/SvnKitDebugLogger.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/svnkit/SvnKitDebugLogger.java @@ -19,6 +19,7 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.popup.util.PopupUtil; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import org.jetbrains.idea.svn.NativeLogReader; import org.jetbrains.idea.svn.SSLExceptionsHelper; import org.jetbrains.idea.svn.SvnNativeLogParser; @@ -29,7 +30,6 @@ import org.tmatesoft.svn.util.SVNLogType; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLProtocolException; -import java.io.UnsupportedEncodingException; import java.security.cert.CertificateException; import java.util.concurrent.TimeUnit; import java.util.logging.Level; @@ -121,12 +121,7 @@ public class SvnKitDebugLogger extends SVNDebugLogAdapter { public void log(final SVNLogType logType, final String message, final byte[] data) { if (shouldLog(logType)) { if (data != null) { - try { - myLog.info(message + "\n" + new String(data, "UTF-8")); - } - catch (UnsupportedEncodingException e) { - myLog.info(message + "\n" + new String(data)); - } + myLog.info(message + "\n" + new String(data, CharsetToolkit.UTF8_CHARSET)); } else { myLog.info(message); diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/context/WorkingContextManager.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/context/WorkingContextManager.java index 9aff1234b3af..66054c8f0429 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/context/WorkingContextManager.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/context/WorkingContextManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,6 +29,7 @@ import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.tasks.Task; import com.intellij.util.NullableFunction; import com.intellij.util.containers.ContainerUtil; @@ -134,7 +135,7 @@ public class WorkingContextManager { Element element = new Element("context"); saveContext(element); String s = new XMLOutputter().outputString(element); - entry.setData(s.getBytes("UTF-8")); + entry.setData(s.getBytes(CharsetToolkit.UTF8_CHARSET)); } catch (IOException e) { LOG.error(e); diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/generic/GenericRepository.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/generic/GenericRepository.java index 566191172e58..0dae8cf2429d 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/generic/GenericRepository.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/generic/GenericRepository.java @@ -1,9 +1,25 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.tasks.generic; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.io.StreamUtil; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.tasks.Task; import com.intellij.tasks.TaskRepositorySubtype; import com.intellij.tasks.TaskRepositoryType; @@ -211,7 +227,7 @@ public class GenericRepository extends BaseRepositoryImpl { } else { InputStream stream = method.getResponseBodyAsStream(); - responseBody = stream == null ? "" : StreamUtil.readText(stream, "utf-8"); + responseBody = stream == null ? "" : StreamUtil.readText(stream, CharsetToolkit.UTF8_CHARSET); } switch (getResponseType()) { case XML: diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/httpclient/ResponseUtil.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/httpclient/ResponseUtil.java index bb040139a9e4..e512ff04a15b 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/httpclient/ResponseUtil.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/httpclient/ResponseUtil.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.tasks.impl.httpclient; import com.google.gson.Gson; @@ -67,7 +82,7 @@ public class ResponseUtil { } else { InputStream stream = response.getResponseBodyAsStream(); - return stream == null ? "" : StreamUtil.readText(stream, DEFAULT_CHARSET_NAME); + return stream == null ? "" : StreamUtil.readText(stream, DEFAULT_CHARSET); } } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/youtrack/YouTrackRepository.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/youtrack/YouTrackRepository.java index 2093a179b461..5da18ef96d21 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/youtrack/YouTrackRepository.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/youtrack/YouTrackRepository.java @@ -1,9 +1,25 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.tasks.youtrack; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.io.StreamUtil; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.tasks.*; import com.intellij.tasks.impl.BaseRepository; import com.intellij.tasks.impl.BaseRepositoryImpl; @@ -85,7 +101,7 @@ public class YouTrackRepository extends BaseRepositoryImpl { InputStream stream = method.getResponseBodyAsStream(); // todo workaround for http://youtrack.jetbrains.net/issue/JT-7984 - String s = StreamUtil.readText(stream, "UTF-8"); + String s = StreamUtil.readText(stream, CharsetToolkit.UTF8_CHARSET); for (int i = 0; i < s.length(); i++) { if (!XMLChar.isValid(s.charAt(i))) { s = s.replace(s.charAt(i), ' '); diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java index 8a5f75b36594..55aef7a7c9f0 100644 --- a/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java +++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.jetbrains.plugins.terminal; import com.intellij.execution.TaskExecutor; @@ -9,6 +24,7 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.SystemInfo; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Consumer; import com.intellij.util.containers.HashMap; @@ -37,7 +53,7 @@ public class LocalTerminalDirectRunner extends AbstractTerminalRunner Date: Thu, 27 Nov 2014 14:21:01 +0300 Subject: [PATCH 09/27] IDEA-131468 Settings / File Encoding / Project Encoding = System default: new files are created with IDE encoding; use EncodingProjectManager instead of EncodingManager wherever possible --- .../compiler/server/BuildManager.java | 16 +-- .../configurations/JavaParameters.java | 6 +- .../com/intellij/openapi/vfs/VirtualFile.java | 1 + .../openapi/vfs/encoding/EncodingManager.java | 16 +-- .../vfs/encoding/EncodingProjectManager.java | 19 ++++ .../vfs/encoding/EncodingRegistry.java | 2 +- .../testFramework/LightVirtualFile.java | 2 +- .../intellij/core/CoreEncodingRegistry.java | 1 + .../openapi/fileEditor/impl/LoadTextUtil.java | 104 +++++++++--------- .../openapi/projectRoots/JdkUtil.java | 8 +- .../impl/ConsoleViewRunningState.java | 6 +- .../encoding/FileEncodingConfigurable.java | 46 ++++---- .../debugger/extensions/PlaybackDebugger.java | 13 +-- .../EncodingEnvironmentUtil.java | 14 +-- .../com/intellij/ide/diff/DiffElement.java | 3 +- .../intellij/openapi/diff/BinaryContent.java | 15 +-- .../execution/process/ScriptRunnerUtil.java | 6 +- .../vfs/encoding/EncodingManagerImpl.java | 25 +---- .../encoding/EncodingProjectManagerImpl.java | 32 +++--- .../PlatformFileEncodingConfigurable.java | 17 ++- .../newvfs/impl/VirtualFileSystemEntry.java | 3 +- .../src/messages/IdeBundle.properties | 3 +- .../testFramework/PlatformTestCase.java | 4 +- .../src/com/intellij/openapi/util/Pair.java | 14 +++ .../intellij/openapi/vfs/CharsetToolkit.java | 33 ++---- .../openapi/vcs/vfs/VcsVirtualFile.java | 3 +- .../com/intellij/openapi/vcs/FilePath.java | 2 + .../intellij/openapi/vcs/FilePathImpl.java | 16 ++- .../vcs/changes/VcsCurrentRevisionProxy.java | 2 - .../patch/CreatePatchConfigurationPanel.java | 15 +-- .../vcs/update/ShowUpdatedDiffAction.java | 39 ++++--- .../changeBrowser/CvsContentRevision.java | 5 +- .../lang/properties/PropertiesFileType.java | 2 +- .../idea/svn/diff/DiffContentRevision.java | 5 +- .../python/console/PydevConsoleRunner.java | 10 +- .../PyStructuredDocstringFormatter.java | 1 - .../python/run/PythonCommandLineState.java | 2 +- .../run/PythonScriptCommandLineState.java | 4 +- .../python/sdk/flavors/PythonSdkFlavor.java | 13 +-- .../convert/ConvertSchemaSettingsImpl.java | 10 +- .../plugins/relaxNG/convert/IdeaDriver.java | 4 +- 41 files changed, 265 insertions(+), 277 deletions(-) rename platform/{platform-api => core-api}/src/com/intellij/openapi/vfs/encoding/EncodingManager.java (82%) rename platform/{platform-api => core-api}/src/com/intellij/openapi/vfs/encoding/EncodingProjectManager.java (66%) diff --git a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java index 94238840c443..219678ffadbe 100644 --- a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java +++ b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -104,8 +104,7 @@ import org.jetbrains.jps.cmdline.ClasspathBootstrap; import org.jetbrains.jps.incremental.Utils; import org.jetbrains.jps.model.serialization.JpsGlobalLoader; -import javax.tools.JavaCompiler; -import javax.tools.ToolProvider; +import javax.tools.*; import java.awt.*; import java.io.File; import java.io.IOException; @@ -211,14 +210,13 @@ public class BuildManager implements ApplicationComponent{ private final BuildMessageDispatcher myMessageDispatcher = new BuildMessageDispatcher(); private volatile int myListenPort = -1; - @Nullable - private final Charset mySystemCharset; + @NotNull + private final Charset mySystemCharset = CharsetToolkit.getDefaultSystemCharset(); public BuildManager(final ProjectManager projectManager) { final Application application = ApplicationManager.getApplication(); IS_UNIT_TEST_MODE = application.isUnitTestMode(); myProjectManager = projectManager; - mySystemCharset = CharsetToolkit.getDefaultSystemCharset(); final String systemPath = PathManager.getSystemPath(); File system = new File(systemPath); try { @@ -994,10 +992,8 @@ public class BuildManager implements ApplicationComponent{ } // javac's VM should use the same default locale that IDEA uses in order for javac to print messages in 'correct' language - if (mySystemCharset != null) { - cmdLine.setCharset(mySystemCharset); - cmdLine.addParameter("-D" + CharsetToolkit.FILE_ENCODING_PROPERTY + "=" + mySystemCharset.name()); - } + cmdLine.setCharset(mySystemCharset); + cmdLine.addParameter("-D" + CharsetToolkit.FILE_ENCODING_PROPERTY + "=" + mySystemCharset.name()); cmdLine.addParameter("-D" + JpsGlobalLoader.FILE_TYPES_COMPONENT_NAME_KEY + "=" + FileTypeManagerImpl.getFileTypeComponentName()); for (String name : new String[]{"user.language", "user.country", "user.region", PathManager.PROPERTY_PATHS_SELECTOR}) { final String value = System.getProperty(name); diff --git a/java/execution/openapi/src/com/intellij/execution/configurations/JavaParameters.java b/java/execution/openapi/src/com/intellij/execution/configurations/JavaParameters.java index bf89d82ea5c1..7025dc3188ff 100644 --- a/java/execution/openapi/src/com/intellij/execution/configurations/JavaParameters.java +++ b/java/execution/openapi/src/com/intellij/execution/configurations/JavaParameters.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -107,9 +107,7 @@ public class JavaParameters extends SimpleJavaParameters { public void setDefaultCharset(final Project project) { Charset encoding = EncodingProjectManager.getInstance(project).getDefaultCharset(); - if (encoding != null) { - setCharset(encoding); - } + setCharset(encoding); } public void configureByModule(final Module module, diff --git a/platform/core-api/src/com/intellij/openapi/vfs/VirtualFile.java b/platform/core-api/src/com/intellij/openapi/vfs/VirtualFile.java index f32b49567c43..86716af5904a 100644 --- a/platform/core-api/src/com/intellij/openapi/vfs/VirtualFile.java +++ b/platform/core-api/src/com/intellij/openapi/vfs/VirtualFile.java @@ -506,6 +506,7 @@ public abstract class VirtualFile extends UserDataHolderBase implements Modifica /** * @return Retrieve the charset file has been loaded with (if loaded) and would be saved with (if would). */ + @NotNull public Charset getCharset() { Charset charset = getStoredCharset(); if (charset == null) { diff --git a/platform/platform-api/src/com/intellij/openapi/vfs/encoding/EncodingManager.java b/platform/core-api/src/com/intellij/openapi/vfs/encoding/EncodingManager.java similarity index 82% rename from platform/platform-api/src/com/intellij/openapi/vfs/encoding/EncodingManager.java rename to platform/core-api/src/com/intellij/openapi/vfs/encoding/EncodingManager.java index a8e353c141ce..c54556f73dd5 100644 --- a/platform/platform-api/src/com/intellij/openapi/vfs/encoding/EncodingManager.java +++ b/platform/core-api/src/com/intellij/openapi/vfs/encoding/EncodingManager.java @@ -42,19 +42,14 @@ public abstract class EncodingManager extends EncodingRegistry { @NotNull public abstract Collection getFavorites(); - @Deprecated // does nothing - public abstract void setUseUTFGuessing(VirtualFile virtualFile, boolean useUTFGuessing); - + @Override public abstract boolean isNative2AsciiForPropertiesFiles(); public abstract void setNative2AsciiForPropertiesFiles(VirtualFile virtualFile, boolean native2Ascii); - @Nullable + @NotNull // returns empty for system default - public String getDefaultCharsetName() { - Charset charset = getDefaultCharset(); - return charset == null ? null : charset.displayName(); - } + public abstract String getDefaultCharsetName(); public void setDefaultCharsetName(@NotNull String name) { throw new UnsupportedOperationException("Not implemented"); @@ -63,14 +58,11 @@ public abstract class EncodingManager extends EncodingRegistry { /** * @return null for system-default */ + @Override @Nullable public abstract Charset getDefaultCharsetForPropertiesFiles(@Nullable VirtualFile virtualFile); public abstract void setDefaultCharsetForPropertiesFiles(@Nullable VirtualFile virtualFile, @Nullable Charset charset); - /** - * @deprecated use {@link EncodingManager#addPropertyChangeListener(java.beans.PropertyChangeListener, com.intellij.openapi.Disposable)} instead - */ - public abstract void addPropertyChangeListener(@NotNull PropertyChangeListener listener); public abstract void addPropertyChangeListener(@NotNull PropertyChangeListener listener, @NotNull Disposable parentDisposable); public abstract void removePropertyChangeListener(@NotNull PropertyChangeListener listener); diff --git a/platform/platform-api/src/com/intellij/openapi/vfs/encoding/EncodingProjectManager.java b/platform/core-api/src/com/intellij/openapi/vfs/encoding/EncodingProjectManager.java similarity index 66% rename from platform/platform-api/src/com/intellij/openapi/vfs/encoding/EncodingProjectManager.java rename to platform/core-api/src/com/intellij/openapi/vfs/encoding/EncodingProjectManager.java index 93fe7293efc5..6798fb82fb27 100644 --- a/platform/platform-api/src/com/intellij/openapi/vfs/encoding/EncodingProjectManager.java +++ b/platform/core-api/src/com/intellij/openapi/vfs/encoding/EncodingProjectManager.java @@ -35,4 +35,23 @@ public abstract class EncodingProjectManager extends EncodingManager { public abstract void setMapping(@NotNull Map result); + /** + * @return Project encoding name (configured in Settings|File Encodings|Project Encoding) or empty string if it's configured to "System Default" + */ + @NotNull + @Override + public abstract String getDefaultCharsetName(); + + /** + * @return Project encoding (configured in Settings|File Encodings|Project Encoding) + */ + @NotNull + @Override + public abstract Charset getDefaultCharset(); + + /** + * Sets Project encoding (configured in Settings|File Encodings|Project Encoding). Use empty string to specify "System Default" + */ + @Override + public abstract void setDefaultCharsetName(@NotNull String name); } diff --git a/platform/core-api/src/com/intellij/openapi/vfs/encoding/EncodingRegistry.java b/platform/core-api/src/com/intellij/openapi/vfs/encoding/EncodingRegistry.java index 48f5c2796b9a..6f1891747511 100644 --- a/platform/core-api/src/com/intellij/openapi/vfs/encoding/EncodingRegistry.java +++ b/platform/core-api/src/com/intellij/openapi/vfs/encoding/EncodingRegistry.java @@ -37,7 +37,7 @@ public abstract class EncodingRegistry { /** * @return charset configured in Settings|File Encodings|IDE encoding */ - @Nullable + @NotNull public abstract Charset getDefaultCharset(); /** diff --git a/platform/core-api/src/com/intellij/testFramework/LightVirtualFile.java b/platform/core-api/src/com/intellij/testFramework/LightVirtualFile.java index 982d921b9e97..3b85a6aa7e42 100644 --- a/platform/core-api/src/com/intellij/testFramework/LightVirtualFile.java +++ b/platform/core-api/src/com/intellij/testFramework/LightVirtualFile.java @@ -254,7 +254,7 @@ public class LightVirtualFile extends VirtualFile { public byte[] contentsToByteArray() throws IOException { final Charset charset = getCharset(); final String s = getContent().toString(); - return charset != null ? s.getBytes(charset.name()) : s.getBytes(); + return s.getBytes(charset.name()); } @Override diff --git a/platform/core-impl/src/com/intellij/core/CoreEncodingRegistry.java b/platform/core-impl/src/com/intellij/core/CoreEncodingRegistry.java index 466a50c3471f..22442df71b1c 100644 --- a/platform/core-impl/src/com/intellij/core/CoreEncodingRegistry.java +++ b/platform/core-impl/src/com/intellij/core/CoreEncodingRegistry.java @@ -32,6 +32,7 @@ public class CoreEncodingRegistry extends EncodingRegistry { return false; } + @NotNull @Override public Charset getDefaultCharset() { return CharsetToolkit.getDefaultSystemCharset(); diff --git a/platform/core-impl/src/com/intellij/openapi/fileEditor/impl/LoadTextUtil.java b/platform/core-impl/src/com/intellij/openapi/fileEditor/impl/LoadTextUtil.java index 6f1d24e4a8c3..bd8ec7c9a1e1 100644 --- a/platform/core-impl/src/com/intellij/openapi/fileEditor/impl/LoadTextUtil.java +++ b/platform/core-impl/src/com/intellij/openapi/fileEditor/impl/LoadTextUtil.java @@ -34,10 +34,12 @@ import com.intellij.openapi.util.Trinity; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.openapi.vfs.encoding.EncodingManager; import com.intellij.openapi.vfs.encoding.EncodingRegistry; import com.intellij.testFramework.LightVirtualFile; import com.intellij.util.ArrayUtil; import com.intellij.util.ExceptionUtil; +import com.intellij.util.ObjectUtils; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; @@ -121,6 +123,7 @@ public final class LoadTextUtil { return Pair.create(result, detectedLineSeparator); } + @NotNull public static Charset detectCharset(@NotNull VirtualFile virtualFile, @NotNull byte[] content, @NotNull FileType fileType) { Charset charset = null; @@ -142,7 +145,9 @@ public final class LoadTextUtil { } } - charset = charset == null ? EncodingRegistry.getInstance().getDefaultCharset() : charset; + if (charset == null) { + charset = EncodingRegistry.getInstance().getDefaultCharset(); + } if (fileType.getName().equals("Properties") && EncodingRegistry.getInstance().isNative2AsciiForPropertiesFiles()) { charset = Native2AsciiCharset.wrap(charset); } @@ -156,15 +161,15 @@ public final class LoadTextUtil { } @NotNull - private static Pair doDetectCharsetAndSetBOM(@NotNull VirtualFile virtualFile, @NotNull byte[] content, boolean saveBOM) { + private static Pair.NonNull doDetectCharsetAndSetBOM(@NotNull VirtualFile virtualFile, @NotNull byte[] content, boolean saveBOM) { return doDetectCharsetAndSetBOM(virtualFile, content, saveBOM, virtualFile.getFileType()); } @NotNull - private static Pair doDetectCharsetAndSetBOM(@NotNull VirtualFile virtualFile, @NotNull byte[] content, boolean saveBOM, @NotNull FileType fileType) { - Charset charset = virtualFile.isCharsetSet() ? virtualFile.getCharset() : detectCharset(virtualFile, content,fileType); - Pair bomAndCharset = getBOMAndCharset(content, charset); + private static Pair.NonNull doDetectCharsetAndSetBOM(@NotNull VirtualFile virtualFile, @NotNull byte[] content, boolean saveBOM, @NotNull FileType fileType) { + @NotNull Charset charset = virtualFile.isCharsetSet() ? virtualFile.getCharset() : detectCharset(virtualFile, content,fileType); + Pair.NonNull bomAndCharset = getCharsetAndBOM(content, charset); final byte[] bom = bomAndCharset.second; - if (saveBOM && bom != null && bom.length != 0) { + if (saveBOM && bom.length != 0) { virtualFile.setBOM(bom); setCharsetWasDetectedFromBytes(virtualFile, AUTO_DETECTED_FROM_BOM); } @@ -175,7 +180,8 @@ public final class LoadTextUtil { @Nullable("null means no luck, otherwise it's tuple(guessed encoding, hint about content if was unable to guess, BOM)") public static Trinity guessFromContent(@NotNull VirtualFile virtualFile, @NotNull byte[] content, int length) { - CharsetToolkit toolkit = GUESS_UTF ? new CharsetToolkit(content, EncodingRegistry.getInstance().getDefaultCharset()) : null; + Charset defaultCharset = ObjectUtils.notNull(EncodingManager.getInstance().getEncoding(virtualFile, true), CharsetToolkit.getDefaultSystemCharset()); + CharsetToolkit toolkit = GUESS_UTF ? new CharsetToolkit(content, defaultCharset) : null; String detectedFromBytes = null; try { if (GUESS_UTF) { @@ -183,8 +189,7 @@ public final class LoadTextUtil { Charset charset = toolkit.guessFromBOM(); if (charset != null) { detectedFromBytes = AUTO_DETECTED_FROM_BOM; - byte[] bom = CharsetToolkit.getMandatoryBom(charset); - if (bom == null) bom = CharsetToolkit.UTF8_BOM; + byte[] bom = ObjectUtils.notNull(CharsetToolkit.getMandatoryBom(charset), CharsetToolkit.UTF8_BOM); return Trinity.create(charset, null, bom); } CharsetToolkit.GuessedEncoding guessed = toolkit.guessFromContent(length); @@ -204,20 +209,20 @@ public final class LoadTextUtil { } @NotNull - private static Pair getBOMAndCharset(@NotNull byte[] content, final Charset charset) { - if (charset != null && charset.name().contains(CharsetToolkit.UTF8) && CharsetToolkit.hasUTF8Bom(content)) { - return Pair.create(charset, CharsetToolkit.UTF8_BOM); + private static Pair.NonNull getCharsetAndBOM(@NotNull byte[] content, @NotNull Charset charset) { + if (charset.name().contains(CharsetToolkit.UTF8) && CharsetToolkit.hasUTF8Bom(content)) { + return Pair.createNonNull(charset, CharsetToolkit.UTF8_BOM); } try { Charset fromBOM = CharsetToolkit.guessFromBOM(content); if (fromBOM != null) { - return Pair.create(fromBOM, CharsetToolkit.getMandatoryBom(fromBOM)); + return Pair.createNonNull(fromBOM, ObjectUtils.notNull(CharsetToolkit.getMandatoryBom(fromBOM), ArrayUtil.EMPTY_BYTE_ARRAY)); } } catch (UnsupportedCharsetException ignore) { } - return Pair.create(charset, ArrayUtil.EMPTY_BYTE_ARRAY); + return Pair.createNonNull(charset, ArrayUtil.EMPTY_BYTE_ARRAY); } public static void changeLineSeparators(@Nullable Project project, @@ -254,13 +259,11 @@ public final class LoadTextUtil { @NotNull String text, long newModificationStamp) throws IOException { Charset existing = virtualFile.getCharset(); - Pair chosen = charsetForWriting(project, virtualFile, text, existing); + Pair.NonNull chosen = charsetForWriting(project, virtualFile, text, existing); Charset charset = chosen.first; byte[] buffer = chosen.second; - if (charset != null) { - if (!charset.equals(existing)) { - virtualFile.setCharset(charset); - } + if (!charset.equals(existing)) { + virtualFile.setCharset(charset); } setDetectedFromBytesFlagBack(virtualFile, buffer); @@ -274,12 +277,12 @@ public final class LoadTextUtil { } @NotNull - private static Pair charsetForWriting(@Nullable Project project, + private static Pair.NonNull charsetForWriting(@Nullable Project project, @NotNull VirtualFile virtualFile, @NotNull String text, - @Nullable Charset existing) { + @NotNull Charset existing) { Charset specified = extractCharsetFromFileContent(project, virtualFile, text); - Pair chosen = chooseMostlyHarmlessCharset(existing, specified, text); + Pair.NonNull chosen = chooseMostlyHarmlessCharset(existing, specified, text); Charset charset = chosen.first; // in case of "UTF-16", OutputStreamWriter sometimes adds BOM on it's own. @@ -287,7 +290,7 @@ public final class LoadTextUtil { byte[] bom = virtualFile.getBOM(); Charset fromBom = bom == null ? null : CharsetToolkit.guessFromBOM(bom); if (fromBom != null && !fromBom.equals(charset)) { - chosen = Pair.create(fromBom, toBytes(text, fromBom)); + chosen = Pair.createNonNull(fromBom, toBytes(text, fromBom)); } return chosen; } @@ -303,19 +306,24 @@ public final class LoadTextUtil { } @NotNull - public static Pair chooseMostlyHarmlessCharset(Charset existing, Charset specified, @NotNull String text) { + public static Pair.NonNull chooseMostlyHarmlessCharset(@NotNull Charset existing, @NotNull Charset specified, @NotNull String text) { try { - if (existing == null) return Pair.create(specified, toBytes(text, specified)); - if (specified == null || specified.equals(existing)) return Pair.create(specified, toBytes(text, existing)); + if (specified.equals(existing)) { + return Pair.createNonNull(specified, toBytes(text, existing)); + } byte[] out = isSupported(specified, text); - if (out != null) return Pair.create(specified, out); //if explicitly specified encoding is safe, return it + if (out != null) { + return Pair.createNonNull(specified, out); //if explicitly specified encoding is safe, return it + } out = isSupported(existing, text); - if (out != null) return Pair.create(existing, out); //otherwise stick to the old encoding if it's ok - return Pair.create(specified, toBytes(text, specified)); //if both are bad there is no difference + if (out != null) { + return Pair.createNonNull(existing, out); //otherwise stick to the old encoding if it's ok + } + return Pair.createNonNull(specified, toBytes(text, specified)); //if both are bad there is no difference } catch (RuntimeException e) { - return Pair.create(Charset.defaultCharset(), toBytes(text, null)); //if both are bad and there is no hope, use the default charset + return Pair.createNonNull(Charset.defaultCharset(), toBytes(text, null)); //if both are bad and there is no hope, use the default charset } } @@ -341,18 +349,9 @@ public final class LoadTextUtil { } } + @NotNull public static Charset extractCharsetFromFileContent(@Nullable Project project, @NotNull VirtualFile virtualFile, @NotNull String text) { - Charset charset = charsetFromContentOrNull(project, virtualFile, text); - if (charset == null) charset = virtualFile.getCharset(); - return charset; - } - - /** - * @deprecated use {@link #charsetFromContentOrNull(com.intellij.openapi.project.Project, com.intellij.openapi.vfs.VirtualFile, CharSequence)} - */ - @Nullable("returns null if cannot determine from content") - public static Charset charsetFromContentOrNull(@Nullable Project project, @NotNull VirtualFile virtualFile, @NotNull String text) { - return CharsetUtil.extractCharsetFromFileContent(project, virtualFile, virtualFile.getFileType(), text); + return ObjectUtils.notNull(charsetFromContentOrNull(project, virtualFile, text), virtualFile.getCharset()); } @Nullable("returns null if cannot determine from content") @@ -436,11 +435,12 @@ public final class LoadTextUtil { public static CharSequence getTextByBinaryPresentation(@NotNull byte[] bytes, @NotNull VirtualFile virtualFile, boolean saveDetectedSeparators, - boolean saveBOM, @NotNull FileType fileType) { - Pair pair = doDetectCharsetAndSetBOM(virtualFile, bytes, saveBOM, fileType); + boolean saveBOM, + @NotNull FileType fileType) { + Pair.NonNull pair = doDetectCharsetAndSetBOM(virtualFile, bytes, saveBOM, fileType); Charset charset = pair.getFirst(); byte[] bom = pair.getSecond(); - int offset = bom == null ? 0 : bom.length; + int offset = bom.length; Pair result = convertBytes(bytes, charset, offset); if (saveDetectedSeparators) { @@ -476,26 +476,20 @@ public final class LoadTextUtil { } @NotNull - public static CharSequence getTextByBinaryPresentation(@NotNull byte[] bytes, Charset charset) { - Pair pair = getBOMAndCharset(bytes, charset); + public static CharSequence getTextByBinaryPresentation(@NotNull byte[] bytes, @NotNull Charset charset) { + Pair.NonNull pair = getCharsetAndBOM(bytes, charset); byte[] bom = pair.getSecond(); - int offset = bom == null ? 0 : bom.length; + int offset = bom.length; - final Pair result = convertBytes(bytes, charset, offset); + final Pair result = convertBytes(bytes, pair.first, offset); return result.getFirst(); } // do not need to think about BOM here. it is processed outside @NotNull - private static Pair convertBytes(@NotNull byte[] bytes, Charset charset, final int startOffset) { + private static Pair convertBytes(@NotNull byte[] bytes, @NotNull Charset charset, final int startOffset) { ByteBuffer byteBuffer = ByteBuffer.wrap(bytes, startOffset, bytes.length - startOffset); - if (charset == null) { - charset = CharsetToolkit.getDefaultSystemCharset(); - } - if (charset == null) { - charset = Charset.forName("ISO-8859-1"); - } CharBuffer charBuffer; try { charBuffer = charset.decode(byteBuffer); diff --git a/platform/lang-api/src/com/intellij/openapi/projectRoots/JdkUtil.java b/platform/lang-api/src/com/intellij/openapi/projectRoots/JdkUtil.java index 5772c4c1e19c..f7691316df2d 100644 --- a/platform/lang-api/src/com/intellij/openapi/projectRoots/JdkUtil.java +++ b/platform/lang-api/src/com/intellij/openapi/projectRoots/JdkUtil.java @@ -27,7 +27,6 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtilRt; -import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.encoding.EncodingManager; @@ -271,11 +270,8 @@ public class JdkUtil { if (encoding == null) { Charset charset = javaParameters.getCharset(); if (charset == null) charset = EncodingManager.getInstance().getDefaultCharset(); - if (charset == null) charset = CharsetToolkit.getDefaultSystemCharset(); - if (charset != null) { - commandLine.addParameter("-Dfile.encoding=" + charset.name()); - commandLine.withCharset(charset); - } + commandLine.addParameter("-Dfile.encoding=" + charset.name()); + commandLine.withCharset(charset); } else { try { diff --git a/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewRunningState.java b/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewRunningState.java index e080d165092a..63d0376d2b09 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewRunningState.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewRunningState.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +22,7 @@ import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.openapi.util.Key; -import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.encoding.EncodingManager; -import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NotNull; import java.io.IOException; @@ -76,7 +74,7 @@ public class ConsoleViewRunningState extends ConsoleState { charset = ((OSProcessHandler)processHandler).getCharset(); } if (charset == null) { - charset = ObjectUtils.notNull(EncodingManager.getInstance().getDefaultCharset(), CharsetToolkit.UTF8_CHARSET); + charset = EncodingManager.getInstance().getDefaultCharset(); } return new OutputStreamWriter(processInput, charset); } diff --git a/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurable.java b/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurable.java index e6c1ae903265..e3157d5626c0 100644 --- a/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurable.java +++ b/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurable.java @@ -28,7 +28,7 @@ import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Ref; -import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.table.JBTable; @@ -52,8 +52,8 @@ public class FileEncodingConfigurable implements SearchableConfigurable, Optiona private JCheckBox myTransparentNativeToAsciiCheckBox; private JPanel myPropertiesFilesEncodingCombo; private final Ref mySelectedCharsetForPropertiesFiles = new Ref(); - private final Ref mySelectedIdeCharset = new Ref(); - private final Ref mySelectedProjectCharset = new Ref(); + private final Ref mySelectedIdeCharset = new Ref(); // IDE encoding or null if "System Default" + private final Ref mySelectedProjectCharset = new Ref(); // Project encoding or null if "System Default" private JLabel myTitleLabel; private JPanel myIdeEncodingsListCombo; private JPanel myProjectEncodingListCombo; @@ -90,13 +90,14 @@ public class FileEncodingConfigurable implements SearchableConfigurable, Optiona return null; } + @NotNull private static ChooseFileEncodingAction installChooseEncodingCombo(@NotNull JPanel parentPanel, @NotNull final Ref selected) { ChooseFileEncodingAction myAction = new ChooseFileEncodingAction(null) { @Override public void update(final AnActionEvent e) { getTemplatePresentation().setEnabled(true); Charset charset = selected.get(); - getTemplatePresentation().setText(charset == null ? IdeBundle.message("encoding.name.system.default") : charset.displayName()); + getTemplatePresentation().setText(charset == null ? IdeBundle.message("encoding.name.system.default", CharsetToolkit.getDefaultSystemCharset().displayName()) : charset.displayName()); } @Override @@ -150,33 +151,30 @@ public class FileEncodingConfigurable implements SearchableConfigurable, Optiona } private boolean isIdeEncodingModified() { - Charset charset = mySelectedIdeCharset.get(); - if (null == charset) { - return !StringUtil.isEmpty(EncodingManager.getInstance().getDefaultCharsetName()); - } - - return !Comparing.equal(charset, EncodingManager.getInstance().getDefaultCharset()); + String charsetName = getSelectedCharsetName(mySelectedIdeCharset); + return !charsetName.equals(EncodingManager.getInstance().getDefaultCharsetName()); } private boolean isProjectEncodingModified() { - Charset charset = mySelectedProjectCharset.get(); - return !Comparing.equal(charset, EncodingProjectManager.getInstance(myProject).getEncoding(null, false)); + String charsetName = getSelectedCharsetName(mySelectedProjectCharset); + return !charsetName.equals(EncodingProjectManager.getInstance(myProject).getDefaultCharsetName()); + } + + @NotNull // charset name or empty for System Default + private static String getSelectedCharsetName(@NotNull Ref selectedCharset) { + Charset charset = selectedCharset.get(); + return charset == null ? "" : charset.name(); } @Override public void apply() throws ConfigurationException { - Charset projectCharset = mySelectedProjectCharset.get(); + String projectCharsetName = getSelectedCharsetName(mySelectedProjectCharset); Map result = myTreeView.getValues(); - if (projectCharset == null) { - result.remove(null); - } - else { - result.put(null, projectCharset); - } - EncodingProjectManager encodingManager = EncodingProjectManager.getInstance(myProject); - encodingManager.setMapping(result); - encodingManager.setDefaultCharsetForPropertiesFiles(null, mySelectedCharsetForPropertiesFiles.get()); - encodingManager.setNative2AsciiForPropertiesFiles(null, myTransparentNativeToAsciiCheckBox.isSelected()); + EncodingProjectManager encodingProjectManager = EncodingProjectManager.getInstance(myProject); + encodingProjectManager.setMapping(result); + encodingProjectManager.setDefaultCharsetName(projectCharsetName); + encodingProjectManager.setDefaultCharsetForPropertiesFiles(null, mySelectedCharsetForPropertiesFiles.get()); + encodingProjectManager.setNative2AsciiForPropertiesFiles(null, myTransparentNativeToAsciiCheckBox.isSelected()); Charset ideCharset = mySelectedIdeCharset.get(); EncodingManager.getInstance().setDefaultCharsetName(ideCharset == null ? "" : ideCharset.name()); @@ -190,7 +188,7 @@ public class FileEncodingConfigurable implements SearchableConfigurable, Optiona mySelectedCharsetForPropertiesFiles.set(encodingManager.getDefaultCharsetForPropertiesFiles(null)); mySelectedIdeCharset.set(EncodingManager.getInstance().getDefaultCharsetName().isEmpty() ? null : EncodingManager.getInstance().getDefaultCharset()); - mySelectedProjectCharset.set(EncodingProjectManager.getInstance(myProject).getEncoding(null, false)); + mySelectedProjectCharset.set(EncodingProjectManager.getInstance(myProject).getDefaultCharsetName().isEmpty() ? null : EncodingProjectManager.getInstance(myProject).getDefaultCharset()); myPropertiesEncodingAction.update(null); myIdeEncodingAction.update(null); myProjectEncodingAction.update(null); diff --git a/platform/lang-impl/src/com/intellij/ui/debugger/extensions/PlaybackDebugger.java b/platform/lang-impl/src/com/intellij/ui/debugger/extensions/PlaybackDebugger.java index 5dc6cca3a1f5..3177196a090b 100644 --- a/platform/lang-impl/src/com/intellij/ui/debugger/extensions/PlaybackDebugger.java +++ b/platform/lang-impl/src/com/intellij/ui/debugger/extensions/PlaybackDebugger.java @@ -25,13 +25,13 @@ import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileElement; import com.intellij.openapi.fileChooser.ex.FileChooserKeys; +import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.Splitter; import com.intellij.openapi.ui.playback.PlaybackContext; import com.intellij.openapi.ui.playback.PlaybackRunner; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; -import com.intellij.openapi.vfs.encoding.EncodingRegistry; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.WindowManager; import com.intellij.openapi.wm.ex.WindowManagerEx; @@ -275,14 +275,9 @@ public class PlaybackDebugger implements UiDebuggerExtension, PlaybackRunner.Sta } private void loadFrom(@NotNull VirtualFile file) { - try { - final String text = CharsetToolkit.bytesToString(file.contentsToByteArray(), EncodingRegistry.getInstance().getDefaultCharset()); - fillDocument(text); - myChanged = false; - } - catch (IOException e) { - Messages.showErrorDialog(e.getMessage(), "Cannot load file"); - } + final String text = LoadTextUtil.loadText(file).toString(); + fillDocument(text); + myChanged = false; } private File getScriptsFile() { diff --git a/platform/platform-api/src/com/intellij/execution/configurations/EncodingEnvironmentUtil.java b/platform/platform-api/src/com/intellij/execution/configurations/EncodingEnvironmentUtil.java index e8999b1fabd7..d728cab1b188 100644 --- a/platform/platform-api/src/com/intellij/execution/configurations/EncodingEnvironmentUtil.java +++ b/platform/platform-api/src/com/intellij/execution/configurations/EncodingEnvironmentUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ package com.intellij.execution.configurations; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.SystemInfo; -import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.encoding.EncodingManager; import com.intellij.openapi.vfs.encoding.EncodingProjectManager; import com.intellij.util.EnvironmentUtil; @@ -138,15 +137,12 @@ public class EncodingEnvironmentUtil { @NotNull private static Charset getCharset(@Nullable Project project) { - Charset charset = null; - if (project != null) { - charset = EncodingProjectManager.getInstance(project).getDefaultCharset(); - } - if (charset == null) { + Charset charset; + if (project == null) { charset = EncodingManager.getInstance().getDefaultCharset(); } - if (charset == null) { - charset = CharsetToolkit.UTF8_CHARSET; + else { + charset = EncodingProjectManager.getInstance(project).getDefaultCharset(); } return charset; } diff --git a/platform/platform-api/src/com/intellij/ide/diff/DiffElement.java b/platform/platform-api/src/com/intellij/ide/diff/DiffElement.java index 3fccaad7bc78..185c9ebe55a9 100644 --- a/platform/platform-api/src/com/intellij/ide/diff/DiffElement.java +++ b/platform/platform-api/src/com/intellij/ide/diff/DiffElement.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -80,6 +80,7 @@ public abstract class DiffElement /*implements Disposable */{ @Nullable public abstract byte[] getContent() throws IOException; + @NotNull public Charset getCharset() { return EncodingManager.getInstance().getDefaultCharset(); } diff --git a/platform/platform-api/src/com/intellij/openapi/diff/BinaryContent.java b/platform/platform-api/src/com/intellij/openapi/diff/BinaryContent.java index b73c59e3ab2f..d4f9a388e33c 100644 --- a/platform/platform-api/src/com/intellij/openapi/diff/BinaryContent.java +++ b/platform/platform-api/src/com/intellij/openapi/diff/BinaryContent.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,9 @@ import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.encoding.EncodingRegistry; +import com.intellij.openapi.vfs.encoding.EncodingProjectManager; import com.intellij.testFramework.LightVirtualFile; +import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -45,7 +46,7 @@ public class BinaryContent extends DiffContent { private final byte[] myBytes; private final Charset myCharset; private Document myDocument = null; - private String myFilePath; + private final String myFilePath; /** * @param charset use to convert bytes to String. null means bytes can't be converted to text. Has no sense if fileType.isBinary() @@ -88,12 +89,8 @@ public class BinaryContent extends DiffContent { String text = null; try { - if (myCharset == null) { - text = CharsetToolkit.bytesToString(myBytes, EncodingRegistry.getInstance().getDefaultCharset()); - } - else { - text = CharsetToolkit.bytesToString(myBytes, myCharset); - } + Charset charset = ObjectUtils.notNull(myCharset, EncodingProjectManager.getInstance(myProject).getDefaultCharset()); + text = CharsetToolkit.bytesToString(myBytes, charset); } catch (IllegalCharsetNameException e) { } diff --git a/platform/platform-impl/src/com/intellij/execution/process/ScriptRunnerUtil.java b/platform/platform-impl/src/com/intellij/execution/process/ScriptRunnerUtil.java index 9933dd59f46a..4edb5caadc45 100644 --- a/platform/platform-impl/src/com/intellij/execution/process/ScriptRunnerUtil.java +++ b/platform/platform-impl/src/com/intellij/execution/process/ScriptRunnerUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,10 +25,8 @@ import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Conditions; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.encoding.EncodingManager; -import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -138,7 +136,7 @@ public final class ScriptRunnerUtil { LOG.debug("Command line env: ", commandLine.getEnvironment()); if (charset == null) { - charset = ObjectUtils.notNull(EncodingManager.getInstance().getDefaultCharset(), CharsetToolkit.UTF8_CHARSET); + charset = EncodingManager.getInstance().getDefaultCharset(); } final OSProcessHandler processHandler = new ColoredProcessHandler(commandLine.createProcess(), commandLine.getCommandLineString(), diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingManagerImpl.java index 01924432c178..294efab550b1 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingManagerImpl.java @@ -47,6 +47,7 @@ import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Alarm; +import com.intellij.util.ObjectUtils; import com.intellij.util.Processor; import com.intellij.util.xmlb.annotations.Attribute; import gnu.trove.Equality; @@ -83,6 +84,7 @@ public class EncodingManagerImpl extends EncodingManager implements PersistentSt private final PropertyChangeSupport myPropertyChangeSupport = new PropertyChangeSupport(this); static class State { + @NotNull private Charset myDefaultEncoding = CharsetToolkit.UTF8_CHARSET; @Attribute("default_encoding") @@ -92,17 +94,9 @@ public class EncodingManagerImpl extends EncodingManager implements PersistentSt } public void setDefaultCharsetName(@NotNull String name) { - if (name.isEmpty()) { - myDefaultEncoding = ChooseFileEncodingAction.NO_ENCODING; - return; - } - myDefaultEncoding = CharsetToolkit.forName(name); - if (myDefaultEncoding == null) { - myDefaultEncoding = CharsetToolkit.getDefaultSystemCharset(); - } - if (myDefaultEncoding == null) { - myDefaultEncoding = CharsetToolkit.UTF8_CHARSET; - } + myDefaultEncoding = name.isEmpty() + ? ChooseFileEncodingAction.NO_ENCODING + : ObjectUtils.notNull(CharsetToolkit.forName(name), CharsetToolkit.getDefaultSystemCharset()); } } @@ -250,10 +244,6 @@ public class EncodingManagerImpl extends EncodingManager implements PersistentSt return true; } - @Override - public void setUseUTFGuessing(final VirtualFile virtualFile, final boolean useUTFGuessing) { - } - @Override public boolean isNative2Ascii(@NotNull final VirtualFile virtualFile) { Project project = guessProject(virtualFile); @@ -305,11 +295,6 @@ public class EncodingManagerImpl extends EncodingManager implements PersistentSt EncodingProjectManager.getInstance(project).setDefaultCharsetForPropertiesFiles(virtualFile, charset); } - @Override - public void addPropertyChangeListener(@NotNull PropertyChangeListener listener){ - myPropertyChangeSupport.addPropertyChangeListener(listener); - } - @Override public void addPropertyChangeListener(@NotNull final PropertyChangeListener listener, @NotNull Disposable parentDisposable) { myPropertyChangeSupport.addPropertyChangeListener(listener); diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingProjectManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingProjectManagerImpl.java index 81bc32b511af..37c01c3a512c 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingProjectManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingProjectManagerImpl.java @@ -171,7 +171,8 @@ public class EncodingProjectManagerImpl extends EncodingProjectManager implement if (parent == null) break; parent = parent.getParent(); } - return null; + + return getDefaultCharset(); } @NotNull @@ -331,7 +332,7 @@ public class EncodingProjectManagerImpl extends EncodingProjectManager implement }; } - private boolean processSubFiles(@Nullable("null means in the project") VirtualFile file, @NotNull final Processor processor) { + private boolean processSubFiles(@Nullable("null means all in the project") VirtualFile file, @NotNull final Processor processor) { if (file == null) { for (VirtualFile virtualFile : ProjectRootManager.getInstance(myProject).getContentRoots()) { if (!processSubFiles(virtualFile, processor)) return false; @@ -349,10 +350,10 @@ public class EncodingProjectManagerImpl extends EncodingProjectManager implement //retrieves encoding for the Project node @Override - @Nullable + @NotNull public Charset getDefaultCharset() { Charset charset = getEncoding(null, false); - return charset == null ? EncodingManager.getInstance().getDefaultCharset() : charset; + return charset == null ? Charset.defaultCharset() : charset; } @Override @@ -360,10 +361,6 @@ public class EncodingProjectManagerImpl extends EncodingProjectManager implement return true; } - @Override - public void setUseUTFGuessing(final VirtualFile virtualFile, final boolean useUTFGuessing) { - } - private static final ThreadLocal SUPPRESS_RELOAD = new ThreadLocal(); static void suppressReloadDuring(@NotNull Runnable action) { Boolean old = SUPPRESS_RELOAD.get(); @@ -388,7 +385,7 @@ public class EncodingProjectManagerImpl extends EncodingProjectManager implement }, "Reload Files", false, myProject); } - private void reloadAllFilesUnder(final VirtualFile root) { + private void reloadAllFilesUnder(@Nullable final VirtualFile root) { tryStartReloadWithProgress(new Runnable() { @Override public void run() { @@ -435,6 +432,18 @@ public class EncodingProjectManagerImpl extends EncodingProjectManager implement } } + @NotNull // empty means system default + @Override + public String getDefaultCharsetName() { + Charset charset = getEncoding(null, false); + return charset == null ? "" : charset.name(); + } + + @Override + public void setDefaultCharsetName(@NotNull String name) { + setEncoding(null, name.isEmpty() ? null : CharsetToolkit.forName(name)); + } + @Override @Nullable public Charset getDefaultCharsetForPropertiesFiles(@Nullable final VirtualFile virtualFile) { @@ -450,11 +459,6 @@ public class EncodingProjectManagerImpl extends EncodingProjectManager implement } } - @Override - public void addPropertyChangeListener(@NotNull PropertyChangeListener listener){ - EncodingManager.getInstance().addPropertyChangeListener(listener); - } - @Override public void addPropertyChangeListener(@NotNull PropertyChangeListener listener, @NotNull Disposable parentDisposable) { EncodingManager.getInstance().addPropertyChangeListener(listener,parentDisposable); diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/PlatformFileEncodingConfigurable.java b/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/PlatformFileEncodingConfigurable.java index 5da2387c2899..8ae9aadb0dd1 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/PlatformFileEncodingConfigurable.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/PlatformFileEncodingConfigurable.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.openapi.vfs.encoding; import com.intellij.ide.IdeBundle; @@ -19,7 +34,7 @@ import java.nio.charset.Charset; * @author yole */ public class PlatformFileEncodingConfigurable implements SearchableConfigurable { - private static final String SYSTEM_DEFAULT = IdeBundle.message("encoding.name.system.default"); + private static final String SYSTEM_DEFAULT = IdeBundle.message("encoding.name.system.default", CharsetToolkit.getDefaultSystemCharset().displayName()); private PlatformEncodingOptionsPanel myPanel; @Override diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualFileSystemEntry.java b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualFileSystemEntry.java index 00fbdc5dd724..6aa95de1668e 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualFileSystemEntry.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualFileSystemEntry.java @@ -21,7 +21,6 @@ import com.intellij.openapi.util.Key; import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.io.FileTooBigException; import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VFileProperty; import com.intellij.openapi.vfs.VfsBundle; @@ -346,11 +345,13 @@ public abstract class VirtualFileSystemEntry extends NewVirtualFile { VfsData.invalidateFile(myId); } + @NotNull @Override public Charset getCharset() { return isCharsetSet() ? super.getCharset() : computeCharset(); } + @NotNull private Charset computeCharset() { Charset charset; if (isDirectory()) { diff --git a/platform/platform-resources-en/src/messages/IdeBundle.properties b/platform/platform-resources-en/src/messages/IdeBundle.properties index 7442f86d09fd..e5edab33cbf6 100644 --- a/platform/platform-resources-en/src/messages/IdeBundle.properties +++ b/platform/platform-resources-en/src/messages/IdeBundle.properties @@ -26,7 +26,6 @@ title.select.path.to.browser=Select Path to Browser title.general=System Settings editbox.default.encoding.for.properties.files=Default encoding for properties files: checkbox.transparent.native.to.ascii.conversion=Transparent native-to-ascii conversion -checkbox.autodetect.utf=Autodetect UTF-encoded files group.http.proxy=HTTP Proxy group.web.browser=Web Browser group.general.options=General Options @@ -1091,7 +1090,7 @@ file.encodings.not.configured=Encodings are not configured encodings.dialog.caption=To change encoding $productName uses for a file or directory, click an item and then select encoding from the Default Encoding list.

\ Built-in file encoding (e.g. JSP, HTML or XML) overrides encoding you specify here.
\ If not specified, files and directories inherit encoding settings from the parent directory or from the Project Encoding. -encoding.name.system.default= +encoding.name.system.default= (now {0}) quick.lists.presentable.name=Quick lists error.saving.statistics=Error saving system information: {0} diff --git a/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java b/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java index 13b6c70ee97b..5784d76fbac8 100644 --- a/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java @@ -783,7 +783,7 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro return file; } - public static void setContentOnDisk(File file, byte[] bom, String content, Charset charset) throws IOException { + public static void setContentOnDisk(@NotNull File file, byte[] bom, @NotNull String content, @NotNull Charset charset) throws IOException { FileOutputStream stream = new FileOutputStream(file); if (bom != null) { stream.write(bom); @@ -797,7 +797,7 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro } } - public static VirtualFile createTempFile(@NonNls String ext, @Nullable byte[] bom, @NonNls String content, Charset charset) throws IOException { + public static VirtualFile createTempFile(@NonNls @NotNull String ext, @Nullable byte[] bom, @NonNls @NotNull String content, @NotNull Charset charset) throws IOException { File temp = FileUtil.createTempFile("copy", "." + ext); setContentOnDisk(temp, bom, content, charset); diff --git a/platform/util-rt/src/com/intellij/openapi/util/Pair.java b/platform/util-rt/src/com/intellij/openapi/util/Pair.java index 9e74659bdb8c..a8b2a7c8f8e1 100644 --- a/platform/util-rt/src/com/intellij/openapi/util/Pair.java +++ b/platform/util-rt/src/com/intellij/openapi/util/Pair.java @@ -27,6 +27,10 @@ public class Pair { //noinspection DontUsePairConstructor return new Pair(first, second); } + @NotNull + public static NonNull createNonNull(@NotNull A first, @NotNull B second) { + return new NonNull(first, second); + } @NotNull @SuppressWarnings("MethodNamesDifferingOnlyByCase") @@ -38,6 +42,7 @@ public class Pair { @NotNull public static Function> createFunction(final B value) { return new Function>() { + @Override public Pair fun(A a) { return create(a, value); } @@ -73,17 +78,26 @@ public class Pair { return second; } + @Override public final boolean equals(Object o) { return o instanceof Pair && Comparing.equal(first, ((Pair)o).first) && Comparing.equal(second, ((Pair)o).second); } + @Override public int hashCode() { int result = first != null ? first.hashCode() : 0; result = 31 * result + (second != null ? second.hashCode() : 0); return result; } + @Override public String toString() { return "<" + first + "," + second + ">"; } + + public static class NonNull extends Pair { + public NonNull(@NotNull A first, @NotNull B second) { + super(first, second); + } + } } diff --git a/platform/util/src/com/intellij/openapi/vfs/CharsetToolkit.java b/platform/util/src/com/intellij/openapi/vfs/CharsetToolkit.java index b7f95c525168..0efb83543847 100644 --- a/platform/util/src/com/intellij/openapi/vfs/CharsetToolkit.java +++ b/platform/util/src/com/intellij/openapi/vfs/CharsetToolkit.java @@ -88,6 +88,7 @@ public class CharsetToolkit { private static final int BINARY_THRESHOLD = 9; // characters with codes below this considered to be binary private final byte[] buffer; + @NotNull private final Charset defaultCharset; private boolean enforce8Bit = false; @@ -122,9 +123,9 @@ public class CharsetToolkit { * @param buffer the byte buffer of which we want to know the encoding. * @param defaultCharset the default Charset to use in case an 8-bit charset is recognized. */ - public CharsetToolkit(@NotNull byte[] buffer, Charset defaultCharset) { + public CharsetToolkit(@NotNull byte[] buffer, @NotNull Charset defaultCharset) { this.buffer = buffer; - this.defaultCharset = defaultCharset == null ? getDefaultSystemCharset() : defaultCharset; + this.defaultCharset = defaultCharset; } @NotNull @@ -240,6 +241,7 @@ public class CharsetToolkit { /** * Retrieves the default Charset */ + @NotNull public Charset getDefaultCharset() { return defaultCharset; } @@ -268,7 +270,7 @@ public class CharsetToolkit { * * @return the Charset recognized. */ - public Charset guessEncoding(int guess_length, Charset defaultCharset) { + public Charset guessEncoding(int guess_length, @NotNull Charset defaultCharset) { // if the file has a Byte Order Marker, we can assume the file is in UTF-xx // otherwise, the file would not be human readable Charset charset = guessFromBOM(); @@ -436,7 +438,7 @@ public class CharsetToolkit { return guessEncoding(guess_length, defaultCharset); } - public static Charset guessEncoding(@NotNull File f, int bufferLength, Charset defaultCharset) throws IOException { + public static Charset guessEncoding(@NotNull File f, int bufferLength, @NotNull Charset defaultCharset) throws IOException { byte[] buffer = new byte[bufferLength]; int read; FileInputStream fis = new FileInputStream(f); @@ -515,16 +517,9 @@ public class CharsetToolkit { * * @return the default Charset. */ - @Nullable + @NotNull public static Charset getDefaultSystemCharset() { - Charset charset = null; - try { - charset = Charset.forName(System.getProperty(FILE_ENCODING_PROPERTY)); - } catch (Exception ignored) { - // Null is OK here. - } - - return charset; + return Charset.defaultCharset(); } /** @@ -587,8 +582,8 @@ public class CharsetToolkit { } } - public static int getBOMLength(@NotNull byte[] content, Charset charset) { - if (charset != null && charset.name().contains(UTF8) && hasUTF8Bom(content)) { + public static int getBOMLength(@NotNull byte[] content, @NotNull Charset charset) { + if (charset.name().contains(UTF8) && hasUTF8Bom(content)) { return UTF8_BOM.length; } if (hasUTF32BEBom(content)) { @@ -606,14 +601,6 @@ public class CharsetToolkit { return 0; } - /** - * @deprecated use {@link CharsetToolkit#getMandatoryBom(java.nio.charset.Charset)} - */ - @Nullable - public static byte[] getBom(@NotNull Charset charset) { - return getMandatoryBom(charset); - } - /** * @return BOM which is associated with this charset and the charset must have this BOM, or null otherwise. * Currently these are UTF-16xx and UTF-32xx families. diff --git a/platform/vcs-api/src/com/intellij/openapi/vcs/vfs/VcsVirtualFile.java b/platform/vcs-api/src/com/intellij/openapi/vcs/vfs/VcsVirtualFile.java index 4a1953f02f4c..0ff553bbc036 100644 --- a/platform/vcs-api/src/com/intellij/openapi/vcs/vfs/VcsVirtualFile.java +++ b/platform/vcs-api/src/com/intellij/openapi/vcs/vfs/VcsVirtualFile.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -122,6 +122,7 @@ public class VcsVirtualFile extends AbstractVcsVirtualFile { } + @NotNull @Override public Charset getCharset() { if (myCharset != null) return myCharset; diff --git a/platform/vcs-api/vcs-api-core/src/com/intellij/openapi/vcs/FilePath.java b/platform/vcs-api/vcs-api-core/src/com/intellij/openapi/vcs/FilePath.java index 1ca489c0d128..701dd5838af0 100644 --- a/platform/vcs-api/vcs-api-core/src/com/intellij/openapi/vcs/FilePath.java +++ b/platform/vcs-api/vcs-api-core/src/com/intellij/openapi/vcs/FilePath.java @@ -59,6 +59,7 @@ public interface FilePath { @Nullable Document getDocument(); + @NotNull Charset getCharset(); /** @@ -67,6 +68,7 @@ public interface FilePath { * @param project the project which settings will be consulted * @return the character set of the file */ + @NotNull Charset getCharset(Project project); /** diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/FilePathImpl.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/FilePathImpl.java index 5c8e0abac81f..1f00a7c77b3b 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/FilePathImpl.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/FilePathImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -144,6 +144,7 @@ public class FilePathImpl implements FilePath { } } + @NotNull @Override public String getPath() { final VirtualFile virtualFile = myVirtualFile; @@ -221,6 +222,7 @@ public class FilePathImpl implements FilePath { return myFile; } + @NotNull @Override public String getName() { return myName; @@ -246,11 +248,13 @@ public class FilePathImpl implements FilePath { } @Override + @NotNull public Charset getCharset() { return getCharset(null); } @Override + @NotNull public Charset getCharset(Project project) { // try to find existing virtual file VirtualFile existing = myVirtualFile != null && myVirtualFile.isValid() ? myVirtualFile : null; @@ -264,15 +268,9 @@ public class FilePathImpl implements FilePath { } } if (existing != null) { - Charset rc = existing.getCharset(); - if (rc != null) { - return rc; - } - } - EncodingManager e = project != null ? EncodingProjectManager.getInstance(project) : null; - if (e == null) { - e = EncodingManager.getInstance(); + return existing.getCharset(); } + EncodingManager e = project == null ? EncodingManager.getInstance() : EncodingProjectManager.getInstance(project); return e.getDefaultCharset(); } diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsCurrentRevisionProxy.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsCurrentRevisionProxy.java index 16ef7515a738..92aff9207c9a 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsCurrentRevisionProxy.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsCurrentRevisionProxy.java @@ -23,7 +23,6 @@ import com.intellij.openapi.vcs.history.VcsRevisionNumber; import com.intellij.openapi.vcs.impl.ContentRevisionCache; import com.intellij.openapi.vcs.impl.CurrentRevisionProvider; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.encoding.EncodingManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -134,7 +133,6 @@ public class VcsCurrentRevisionProxy implements ContentRevision { throw new VcsException("Failed to create content for current revision"); } Charset charset = myFile.getCharset(); - charset = charset == null ? EncodingManager.getInstance().getDefaultCharset() : charset; return Pair.create(currentRevision, contentRevision.getContent().getBytes(charset)); } } diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/CreatePatchConfigurationPanel.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/CreatePatchConfigurationPanel.java index 2fb12e914799..c02b25e80d91 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/CreatePatchConfigurationPanel.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/CreatePatchConfigurationPanel.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,10 +38,11 @@ import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileWrapper; -import com.intellij.openapi.vfs.encoding.EncodingManager; +import com.intellij.openapi.vfs.encoding.EncodingProjectManager; import com.intellij.ui.HideableTitledPanel; import com.intellij.util.Consumer; import com.intellij.util.ui.FormBuilder; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; @@ -54,7 +55,7 @@ import java.util.Collection; import java.util.List; public class CreatePatchConfigurationPanel { - private static final String SYSTEM_DEFAULT = IdeBundle.message("encoding.name.system.default"); + private static final String SYSTEM_DEFAULT = IdeBundle.message("encoding.name.system.default", CharsetToolkit.getDefaultSystemCharset().displayName()); public static final String ALL = "(All)"; private JPanel myMainPanel; @@ -73,7 +74,7 @@ public class CreatePatchConfigurationPanel { private JPanel myPanelWithSelectedFiles; private boolean myExecute; - public CreatePatchConfigurationPanel(final Project project) { + public CreatePatchConfigurationPanel(@NotNull final Project project) { myProject = project; initMainPanel(); @@ -130,12 +131,12 @@ public class CreatePatchConfigurationPanel { encodingsModel.insertElementAt(SYSTEM_DEFAULT, 0); myEncoding.setModel(encodingsModel); - final String name = EncodingManager.getInstance().getDefaultCharsetName(); + final String name = EncodingProjectManager.getInstance(myProject).getDefaultCharsetName(); if (StringUtil.isEmpty(name)) { myEncoding.setSelectedItem(SYSTEM_DEFAULT); } else { - myEncoding.setSelectedItem(EncodingManager.getInstance().getDefaultCharset()); + myEncoding.setSelectedItem(EncodingProjectManager.getInstance(myProject).getDefaultCharset()); } } @@ -143,7 +144,7 @@ public class CreatePatchConfigurationPanel { public Charset getEncoding() { final Object selectedItem = myEncoding.getSelectedItem(); if (SYSTEM_DEFAULT.equals(selectedItem)) { - return EncodingManager.getInstance().getDefaultCharset(); + return CharsetToolkit.getDefaultSystemCharset(); } return (Charset)selectedItem; } diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/update/ShowUpdatedDiffAction.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/update/ShowUpdatedDiffAction.java index d6158c594e4f..0bdb4efc7c2e 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/update/ShowUpdatedDiffAction.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/update/ShowUpdatedDiffAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ import com.intellij.openapi.vcs.changes.actions.ShowDiffAction; import com.intellij.openapi.vcs.changes.actions.ShowDiffUIContext; import com.intellij.openapi.vcs.history.VcsRevisionNumber; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.encoding.EncodingManager; +import com.intellij.openapi.vfs.encoding.EncodingProjectManager; import com.intellij.openapi.vfs.pointers.VirtualFilePointer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -72,7 +72,7 @@ public class ShowUpdatedDiffAction extends AnAction implements DumbAware { final String selectedUrl = VcsDataKeys.UPDATE_VIEW_SELECTED_PATH.getData(dc); - ShowDiffAction.showDiffForChange(new MyIterableWrapper(iterable.iterator(), before, after), new MySelectionMarker(selectedUrl), + ShowDiffAction.showDiffForChange(new MyIterableWrapper(iterable.iterator(), before, after, project), new MySelectionMarker(selectedUrl), project, new ShowDiffUIContext(true)); } @@ -102,15 +102,20 @@ public class ShowUpdatedDiffAction extends AnAction implements DumbAware { private final Iterator> myVfIterator; private final Label myBefore; private final Label myAfter; + @NotNull private final Project myProject; - private MyIterableWrapper(Iterator> vfIterator, final Label before, final Label after) { + private MyIterableWrapper(Iterator> vfIterator, + final Label before, + final Label after, + @NotNull Project project) { myVfIterator = vfIterator; myBefore = before; myAfter = after; + myProject = project; } public Iterator iterator() { - return new MyIteratorWrapper(myVfIterator, myBefore, myAfter); + return new MyIteratorWrapper(myVfIterator, myBefore, myAfter, myProject); } } @@ -122,7 +127,7 @@ public class ShowUpdatedDiffAction extends AnAction implements DumbAware { } @Nullable - public String convert(final VirtualFilePointer pointer) { + public String convert(final VirtualFilePointer pointer, @NotNull Project project) { if (pointer == null) return null; final String path = pointer.getPresentableUrl(); final ByteContent byteContent = myLabel.getByteContent(FileUtil.toSystemIndependentName(path)); @@ -131,8 +136,9 @@ public class ShowUpdatedDiffAction extends AnAction implements DumbAware { } final VirtualFile vf = pointer.getFile(); if (vf == null) { - return LoadTextUtil.getTextByBinaryPresentation(byteContent.getBytes(), EncodingManager.getInstance().getDefaultCharset()).toString(); - } else { + return LoadTextUtil.getTextByBinaryPresentation(byteContent.getBytes(), EncodingProjectManager.getInstance(project).getDefaultCharset()).toString(); + } + else { return LoadTextUtil.getTextByBinaryPresentation(byteContent.getBytes(), vf).toString(); } } @@ -143,11 +149,13 @@ public class ShowUpdatedDiffAction extends AnAction implements DumbAware { private final MyLoader myLoader; private final VirtualFilePointer myPointer; private final boolean myBefore; + @NotNull private final Project myProject; - private MyCheckpointContentRevision(final VirtualFilePointer pointer, final MyLoader loader, final boolean before) { + private MyCheckpointContentRevision(final VirtualFilePointer pointer, final MyLoader loader, final boolean before, @NotNull Project project) { myLoader = loader; myPointer = pointer; myBefore = before; + myProject = project; } public String getContent() throws VcsException { @@ -156,7 +164,7 @@ public class ShowUpdatedDiffAction extends AnAction implements DumbAware { return s; } - final String loaded = myLoader.convert(myPointer); + final String loaded = myLoader.convert(myPointer, myProject); myContent = new SoftReference(loaded); return loaded; @@ -193,9 +201,14 @@ public class ShowUpdatedDiffAction extends AnAction implements DumbAware { private final MyLoader myBeforeLoader; private final MyLoader myAfterLoader; private final Iterator> myVfIterator; + @NotNull private final Project myProject; - public MyIteratorWrapper(final Iterator> vfIterator, final Label before, final Label after) { + public MyIteratorWrapper(final Iterator> vfIterator, + final Label before, + final Label after, + @NotNull Project project) { myVfIterator = vfIterator; + myProject = project; myBeforeLoader = new MyLoader(before); myAfterLoader = new MyLoader(after); } @@ -208,8 +221,8 @@ public class ShowUpdatedDiffAction extends AnAction implements DumbAware { final Pair pair = myVfIterator.next(); final VirtualFilePointer pointer = pair.getFirst(); - MyCheckpointContentRevision before = new MyCheckpointContentRevision(pointer, myBeforeLoader, true); - MyCheckpointContentRevision after = new MyCheckpointContentRevision(pointer, myAfterLoader, false); + MyCheckpointContentRevision before = new MyCheckpointContentRevision(pointer, myBeforeLoader, true, myProject); + MyCheckpointContentRevision after = new MyCheckpointContentRevision(pointer, myAfterLoader, false, myProject); if (FileStatus.ADDED.equals(pair.getSecond())) { before = null; } else if (FileStatus.DELETED.equals(pair.getSecond())) { diff --git a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/changeBrowser/CvsContentRevision.java b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/changeBrowser/CvsContentRevision.java index 10788cb563e6..25063be661e2 100644 --- a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/changeBrowser/CvsContentRevision.java +++ b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/changeBrowser/CvsContentRevision.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,6 @@ import com.intellij.openapi.vcs.actions.VcsContextFactory; import com.intellij.openapi.vcs.changes.ContentRevision; import com.intellij.openapi.vcs.history.VcsRevisionNumber; import com.intellij.openapi.vfs.CharsetToolkit; -import com.intellij.openapi.vfs.encoding.EncodingRegistry; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -73,7 +72,7 @@ public class CvsContentRevision implements ContentRevision { byte[] content = loadContent(); if (content != null) { final Charset charset = myLocalFile.getCharset(); - myContent = charset == null ? CharsetToolkit.bytesToString(content, EncodingRegistry.getInstance().getDefaultCharset()) : CharsetToolkit.bytesToString(content, charset); + myContent = CharsetToolkit.bytesToString(content, charset); } } return myContent; diff --git a/plugins/properties/properties-psi-api/src/com/intellij/lang/properties/PropertiesFileType.java b/plugins/properties/properties-psi-api/src/com/intellij/lang/properties/PropertiesFileType.java index 8173aa4915ca..d9b57434d57c 100644 --- a/plugins/properties/properties-psi-api/src/com/intellij/lang/properties/PropertiesFileType.java +++ b/plugins/properties/properties-psi-api/src/com/intellij/lang/properties/PropertiesFileType.java @@ -67,6 +67,6 @@ public class PropertiesFileType extends LanguageFileType { if (charset == null) { charset = CharsetToolkit.getDefaultSystemCharset(); } - return charset != null ? charset.name() : null; + return charset.name(); } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/diff/DiffContentRevision.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/diff/DiffContentRevision.java index 6d360fe1c685..24d92183f00e 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/diff/DiffContentRevision.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/diff/DiffContentRevision.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,6 @@ import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.changes.ContentRevision; import com.intellij.openapi.vcs.history.VcsRevisionNumber; import com.intellij.openapi.vfs.CharsetToolkit; -import com.intellij.openapi.vfs.encoding.EncodingRegistry; import com.intellij.vcsUtil.VcsUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -60,7 +59,7 @@ public class DiffContentRevision implements ContentRevision { } final byte[] bytes = bos.toByteArray(); final Charset charset = myFilePath.getCharset(); - myContents = charset == null ? CharsetToolkit.bytesToString(bytes, EncodingRegistry.getInstance().getDefaultCharset()) : CharsetToolkit.bytesToString(bytes, charset); + myContents = CharsetToolkit.bytesToString(bytes, charset); } return myContents; } diff --git a/python/src/com/jetbrains/python/console/PydevConsoleRunner.java b/python/src/com/jetbrains/python/console/PydevConsoleRunner.java index adae12303a0c..aab118a4bbae 100644 --- a/python/src/com/jetbrains/python/console/PydevConsoleRunner.java +++ b/python/src/com/jetbrains/python/console/PydevConsoleRunner.java @@ -64,7 +64,7 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.StreamUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.encoding.EncodingManager; +import com.intellij.openapi.vfs.encoding.EncodingProjectManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.impl.source.tree.FileElement; @@ -243,10 +243,10 @@ public class PydevConsoleRunner extends AbstractConsoleRunnerWithHistory addDefaultEnvironments(Sdk sdk, Map envs) { - Charset defaultCharset = EncodingManager.getInstance().getDefaultCharset(); + public static Map addDefaultEnvironments(Sdk sdk, Map envs, @NotNull Project project) { + Charset defaultCharset = EncodingProjectManager.getInstance(project).getDefaultCharset(); - final String encoding = defaultCharset != null ? defaultCharset.name() : "utf-8"; + final String encoding = defaultCharset.name(); setPythonIOEncoding(setPythonUnbuffered(envs), encoding); PythonSdkFlavor.initPythonPath(envs, true, PythonCommandLineState.getAddedPaths(sdk)); @@ -392,7 +392,7 @@ public class PydevConsoleRunner extends AbstractConsoleRunnerWithHistory getAdditionalEnvs() { - return addDefaultEnvironments(sdk, environmentVariables); + return addDefaultEnvironments(sdk, environmentVariables,getProject()); } }; } diff --git a/python/src/com/jetbrains/python/documentation/PyStructuredDocstringFormatter.java b/python/src/com/jetbrains/python/documentation/PyStructuredDocstringFormatter.java index 43786cf3542f..e533f98609e9 100644 --- a/python/src/com/jetbrains/python/documentation/PyStructuredDocstringFormatter.java +++ b/python/src/com/jetbrains/python/documentation/PyStructuredDocstringFormatter.java @@ -100,7 +100,6 @@ public class PyStructuredDocstringFormatter { if (sdkHome == null) return null; final Charset charset = EncodingProjectManager.getInstance(module.getProject()).getDefaultCharset(); - if (charset == null) return null; final ByteBuffer encoded = charset.encode(docstring); final byte[] data = new byte[encoded.limit()]; diff --git a/python/src/com/jetbrains/python/run/PythonCommandLineState.java b/python/src/com/jetbrains/python/run/PythonCommandLineState.java index 476b8646bed9..c6615604b61b 100644 --- a/python/src/com/jetbrains/python/run/PythonCommandLineState.java +++ b/python/src/com/jetbrains/python/run/PythonCommandLineState.java @@ -269,7 +269,7 @@ public abstract class PythonCommandLineState extends CommandLineState { public void addPredefinedEnvironmentVariables(Map envs, boolean passParentEnvs) { final PythonSdkFlavor flavor = PythonSdkFlavor.getFlavor(myConfig.getInterpreterPath()); if (flavor != null) { - flavor.addPredefinedEnvironmentVariables(envs); + flavor.addPredefinedEnvironmentVariables(envs, myConfig.getProject()); } } diff --git a/python/src/com/jetbrains/python/run/PythonScriptCommandLineState.java b/python/src/com/jetbrains/python/run/PythonScriptCommandLineState.java index bc3a19082087..fd3423ebd07b 100644 --- a/python/src/com/jetbrains/python/run/PythonScriptCommandLineState.java +++ b/python/src/com/jetbrains/python/run/PythonScriptCommandLineState.java @@ -24,9 +24,9 @@ import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.configurations.ParametersList; import com.intellij.execution.configurations.ParamsGroup; import com.intellij.execution.executors.DefaultDebugExecutor; +import com.intellij.execution.process.CommandLineArgumentsProvider; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.execution.process.CommandLineArgumentsProvider; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.util.io.FileUtil; @@ -158,7 +158,7 @@ public class PythonScriptCommandLineState extends PythonCommandLineState { @Override public Map getAdditionalEnvs() { - Map map = addDefaultEnvironments(sdk, environmentVariables); + Map map = addDefaultEnvironments(sdk, environmentVariables,getProject()); map.putAll(cmd.getEnvironment()); return map; } diff --git a/python/src/com/jetbrains/python/sdk/flavors/PythonSdkFlavor.java b/python/src/com/jetbrains/python/sdk/flavors/PythonSdkFlavor.java index 3e61178f1ad6..0f33f555a359 100644 --- a/python/src/com/jetbrains/python/sdk/flavors/PythonSdkFlavor.java +++ b/python/src/com/jetbrains/python/sdk/flavors/PythonSdkFlavor.java @@ -19,13 +19,14 @@ import com.google.common.collect.Lists; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.process.ProcessOutput; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.SdkAdditionalData; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.encoding.EncodingManager; +import com.intellij.openapi.vfs.encoding.EncodingProjectManager; import com.intellij.util.PatternUtil; import com.jetbrains.python.psi.LanguageLevel; import com.jetbrains.python.sdk.PySdkUtil; @@ -208,12 +209,10 @@ public abstract class PythonSdkFlavor { } @SuppressWarnings({"MethodMayBeStatic"}) - public void addPredefinedEnvironmentVariables(Map envs) { - Charset defaultCharset = EncodingManager.getInstance().getDefaultCharset(); - if (defaultCharset != null) { - final String encoding = defaultCharset.name(); - PythonEnvUtil.setPythonIOEncoding(envs, encoding); - } + public void addPredefinedEnvironmentVariables(Map envs, @NotNull Project project) { + Charset defaultCharset = EncodingProjectManager.getInstance(project).getDefaultCharset(); + final String encoding = defaultCharset.name(); + PythonEnvUtil.setPythonIOEncoding(envs, encoding); } @NotNull diff --git a/xml/relaxng/src/org/intellij/plugins/relaxNG/convert/ConvertSchemaSettingsImpl.java b/xml/relaxng/src/org/intellij/plugins/relaxNG/convert/ConvertSchemaSettingsImpl.java index f91ecfb8882e..16956e5ff22f 100644 --- a/xml/relaxng/src/org/intellij/plugins/relaxNG/convert/ConvertSchemaSettingsImpl.java +++ b/xml/relaxng/src/org/intellij/plugins/relaxNG/convert/ConvertSchemaSettingsImpl.java @@ -28,7 +28,7 @@ import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.encoding.EncodingManager; +import com.intellij.openapi.vfs.encoding.EncodingProjectManager; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.ui.DocumentAdapter; @@ -120,12 +120,8 @@ public class ConvertSchemaSettingsImpl implements ConvertSchemaSettings { } myEncoding.setModel(new DefaultComboBoxModel(suggestions.toArray())); - final Charset charset = EncodingManager.getInstance().getDefaultCharset(); - if (charset == null) { - myEncoding.setSelectedItem(System.getProperty("file.encoding", "UTF-8")); - } else { - myEncoding.setSelectedItem(charset.name()); - } + final Charset charset = EncodingProjectManager.getInstance(project).getDefaultCharset(); + myEncoding.setSelectedItem(charset.name()); final CodeStyleSettings styleSettings = CodeStyleSettingsManager.getSettings(project); final int indent = styleSettings.getIndentSize(type); diff --git a/xml/relaxng/src/org/intellij/plugins/relaxNG/convert/IdeaDriver.java b/xml/relaxng/src/org/intellij/plugins/relaxNG/convert/IdeaDriver.java index a0b8cad3d94f..723ee4bf9302 100644 --- a/xml/relaxng/src/org/intellij/plugins/relaxNG/convert/IdeaDriver.java +++ b/xml/relaxng/src/org/intellij/plugins/relaxNG/convert/IdeaDriver.java @@ -83,9 +83,7 @@ public class IdeaDriver { if (inputType != SchemaType.DTD) { final Charset charset = inputFile.getCharset(); - if (charset != null) { - inputParams.add("encoding=" + charset.name()); - } + inputParams.add("encoding=" + charset.name()); } final ArrayList outputParams = new ArrayList(); From e0cb4c01db0e77aae2f80a55b38c8c25c4ebe2d1 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Thu, 27 Nov 2014 14:23:35 +0300 Subject: [PATCH 10/27] compress with encoding which is known to be able to unambiguously decode, not the user specified one --- .../command/impl/EditorChangeAction.java | 38 +++++++++---------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/command/impl/EditorChangeAction.java b/platform/platform-impl/src/com/intellij/openapi/command/impl/EditorChangeAction.java index d1e485529cad..159447d3601d 100644 --- a/platform/platform-impl/src/com/intellij/openapi/command/impl/EditorChangeAction.java +++ b/platform/platform-impl/src/com/intellij/openapi/command/impl/EditorChangeAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,29 +18,26 @@ package com.intellij.openapi.command.impl; import com.intellij.openapi.command.undo.BasicUndoableAction; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.ex.DocumentEx; -import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.vcs.FileStatusManager; import com.intellij.openapi.vcs.impl.FileStatusManagerImpl; +import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.encoding.EncodingManager; import com.intellij.testFramework.LightVirtualFile; +import com.intellij.util.CompressionUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.nio.charset.Charset; -import static com.intellij.util.CompressionUtil.compressCharSequence; -import static com.intellij.util.CompressionUtil.uncompressCharSequence; - public class EditorChangeAction extends BasicUndoableAction { private final int myOffset; private final Object myOldString; private final Object myNewString; private final long myOldTimeStamp; private final long myNewTimeStamp; - @NotNull private final Charset myCharset; + @NotNull private static final Charset myCharset= CharsetToolkit.UTF8_CHARSET; public EditorChangeAction(DocumentEvent e) { this((DocumentEx)e.getDocument(), e.getOffset(), e.getOldFragment(), e.getNewFragment(), e.getOldTimeStamp()); @@ -48,23 +45,18 @@ public class EditorChangeAction extends BasicUndoableAction { public EditorChangeAction(@NotNull DocumentEx document, int offset, - CharSequence oldString, - CharSequence newString, + @NotNull CharSequence oldString, + @NotNull CharSequence newString, long oldTimeStamp) { super(document); - - Charset charset = EncodingManager.getInstance().getEncoding(FileDocumentManager.getInstance().getFile(document), true); - if (charset == null) charset = EncodingManager.getInstance().getDefaultCharset(); - if (charset == null) charset = Charset.defaultCharset(); - myCharset = charset; - myOffset = offset; - myOldString = oldString == null ? "" : compressCharSequence(oldString, myCharset); - myNewString = newString == null ? "" : compressCharSequence(newString, myCharset); + myOldString = CompressionUtil.compressCharSequence(oldString, myCharset); + myNewString = CompressionUtil.compressCharSequence(newString, myCharset); myOldTimeStamp = oldTimeStamp; myNewTimeStamp = document.getModificationStamp(); } + @Override public void undo() { DocumentUndoProvider.startDocumentUndo(getDocument()); try { @@ -79,13 +71,18 @@ public class EditorChangeAction extends BasicUndoableAction { } public void performUndo() { - exchangeStrings(uncompressCharSequence(myNewString, myCharset), uncompressCharSequence(myOldString, myCharset)); + CharSequence oldString = CompressionUtil.uncompressCharSequence(myOldString, myCharset); + CharSequence newString = CompressionUtil.uncompressCharSequence(myNewString, myCharset); + exchangeStrings(newString, oldString); } + @Override public void redo() { DocumentUndoProvider.startDocumentUndo(getDocument()); try { - exchangeStrings(uncompressCharSequence(myOldString, myCharset), uncompressCharSequence(myNewString, myCharset)); + CharSequence oldString = CompressionUtil.uncompressCharSequence(myOldString, myCharset); + CharSequence newString = CompressionUtil.uncompressCharSequence(myNewString, myCharset); + exchangeStrings(oldString, newString); } finally { DocumentUndoProvider.finishDocumentUndo(getDocument()); @@ -94,7 +91,7 @@ public class EditorChangeAction extends BasicUndoableAction { refreshFileStatus(); } - private void exchangeStrings(CharSequence newString, CharSequence oldString) { + private void exchangeStrings(@NotNull CharSequence newString, @NotNull CharSequence oldString) { DocumentEx d = getDocument(); if (newString.length() > 0 && oldString.length() == 0) { @@ -123,6 +120,7 @@ public class EditorChangeAction extends BasicUndoableAction { return (DocumentEx)getAffectedDocuments()[0].getDocument(); } + @Override @NonNls public String toString() { return "editor change: '" + myOldString + "' to '" + myNewString + "'" + " at: " + myOffset; From f40ae968cd83dbd7fa1a28f1f63b313219a07162 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Thu, 27 Nov 2014 14:25:40 +0300 Subject: [PATCH 11/27] moved to core --- .../intellij/lang/impl/PsiBuilderImpl.java | 3 +- .../util/StandardProgressIndicatorBase.java | 30 +++++++++++++++++++ .../psi/impl/DocumentCommitThread.java | 26 +++++----------- .../impl/source/text/BlockSupportImpl.java | 8 ++--- .../psi/impl/source/tree/TreeUtil.java | 6 ++-- 5 files changed, 45 insertions(+), 28 deletions(-) create mode 100644 platform/core-impl/src/com/intellij/openapi/progress/util/StandardProgressIndicatorBase.java rename platform/{lang-impl => core-impl}/src/com/intellij/psi/impl/DocumentCommitThread.java (95%) diff --git a/platform/core-impl/src/com/intellij/lang/impl/PsiBuilderImpl.java b/platform/core-impl/src/com/intellij/lang/impl/PsiBuilderImpl.java index f76ba37df0eb..573dad432194 100644 --- a/platform/core-impl/src/com/intellij/lang/impl/PsiBuilderImpl.java +++ b/platform/core-impl/src/com/intellij/lang/impl/PsiBuilderImpl.java @@ -19,6 +19,7 @@ package com.intellij.lang.impl; import com.intellij.lang.*; import com.intellij.lexer.Lexer; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.progress.EmptyProgressIndicator; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressIndicatorProvider; import com.intellij.openapi.project.Project; @@ -1111,7 +1112,7 @@ public class PsiBuilderImpl extends UserDataHolderBase implements PsiBuilder { final MyComparator comparator = new MyComparator(getUserDataUnprotected(CUSTOM_COMPARATOR), treeStructure); final ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator(); - BlockSupportImpl.diffTrees(oldRoot, builder, comparator, treeStructure, indicator); + BlockSupportImpl.diffTrees(oldRoot, builder, comparator, treeStructure, indicator == null ? new EmptyProgressIndicator() : indicator); return diffLog; } diff --git a/platform/core-impl/src/com/intellij/openapi/progress/util/StandardProgressIndicatorBase.java b/platform/core-impl/src/com/intellij/openapi/progress/util/StandardProgressIndicatorBase.java new file mode 100644 index 000000000000..698015040f8f --- /dev/null +++ b/platform/core-impl/src/com/intellij/openapi/progress/util/StandardProgressIndicatorBase.java @@ -0,0 +1,30 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.openapi.progress.util; + +import com.intellij.openapi.progress.StandardProgressIndicator; + +public class StandardProgressIndicatorBase extends AbstractProgressIndicatorBase implements StandardProgressIndicator { + @Override + public final void cancel() { + super.cancel(); + } + + @Override + public final boolean isCanceled() { + return super.isCanceled(); + } +} diff --git a/platform/lang-impl/src/com/intellij/psi/impl/DocumentCommitThread.java b/platform/core-impl/src/com/intellij/psi/impl/DocumentCommitThread.java similarity index 95% rename from platform/lang-impl/src/com/intellij/psi/impl/DocumentCommitThread.java rename to platform/core-impl/src/com/intellij/psi/impl/DocumentCommitThread.java index fd9c69710189..c0e6117cf510 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/DocumentCommitThread.java +++ b/platform/core-impl/src/com/intellij/psi/impl/DocumentCommitThread.java @@ -15,9 +15,7 @@ */ package com.intellij.psi.impl; -import com.intellij.codeInsight.daemon.impl.DaemonProgressIndicator; import com.intellij.diagnostic.ThreadDumper; -import com.intellij.ide.startup.impl.StartupManagerImpl; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationAdapter; import com.intellij.openapi.application.ex.ApplicationEx; @@ -27,9 +25,8 @@ import com.intellij.openapi.editor.Document; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; -import com.intellij.openapi.progress.util.ProgressIndicatorBase; +import com.intellij.openapi.progress.util.StandardProgressIndicatorBase; import com.intellij.openapi.project.Project; -import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.FileViewProvider; @@ -175,7 +172,7 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run private void doQueue(@NotNull Project project, @NotNull Document document, @NotNull Object reason) { synchronized (documentsToCommit) { - ProgressIndicator indicator = new DaemonProgressIndicator(); + ProgressIndicator indicator = createProgressIndicator(); CommitTask newTask = new CommitTask(document, project, indicator, reason); markRemovedFromDocsToCommit(newTask); @@ -211,7 +208,7 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run } if (task != null) { boolean stillUncommitted = !task.project.isDisposed() && - ((PsiDocumentManagerImpl)PsiDocumentManager.getInstance(task.project)).isInUncommittedSet(task.document); + ((PsiDocumentManagerBase)PsiDocumentManager.getInstance(task.project)).isInUncommittedSet(task.document); if (stillUncommitted) { s += "; Uncommitted: " + task.document; } @@ -325,7 +322,7 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run log("Pulled", task, false, indicator); - if (project.isDisposed() || !((PsiDocumentManagerImpl)PsiDocumentManager.getInstance(project)).isInUncommittedSet(document)) { + if (project.isDisposed() || !((PsiDocumentManagerBase)PsiDocumentManager.getInstance(project)).isInUncommittedSet(document)) { log("Abandon and proceed to next",task, false); return; } @@ -394,13 +391,6 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run if (!project.isInitialized() && !project.isDefault()) { @NonNls String s = project + "; Disposed: "+project.isDisposed()+"; Open: "+project.isOpen(); - s += "; SA Passed: "; - try { - s += ((StartupManagerImpl)StartupManager.getInstance(project)).startupActivityPassed(); - } - catch (Exception e) { - s += e; - } try { Disposer.dispose(project); } @@ -433,7 +423,7 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run @NotNull @Override protected ProgressIndicator createProgressIndicator() { - return new ProgressIndicatorBase(); + return new StandardProgressIndicatorBase(); } private void startNewTask(@Nullable CommitTask task, @NotNull Object reason) { @@ -459,7 +449,7 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run myApplication.assertReadAccessAllowed(); if (project.isDisposed()) return; - final PsiDocumentManagerImpl documentManager = (PsiDocumentManagerImpl)PsiDocumentManager.getInstance(project); + final PsiDocumentManagerBase documentManager = (PsiDocumentManagerBase)PsiDocumentManager.getInstance(project); if (documentManager.isCommitted(document)) return; FileViewProvider viewProvider = documentManager.getCachedViewProvider(document); @@ -525,7 +515,7 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run } } - PsiDocumentManagerImpl documentManager = (PsiDocumentManagerImpl)PsiDocumentManager.getInstance(project); + PsiDocumentManagerBase documentManager = (PsiDocumentManagerBase)PsiDocumentManager.getInstance(project); log("Executing later finishCommit", task, false); boolean success = documentManager.finishCommit(document, finishProcessors, synchronously, task.reason); @@ -546,7 +536,7 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run } @NotNull - private Processor handleCommitWithoutPsi(@NotNull final PsiDocumentManagerImpl documentManager, + private Processor handleCommitWithoutPsi(@NotNull final PsiDocumentManagerBase documentManager, @NotNull Document document, @NotNull final CommitTask task, final boolean synchronously) { diff --git a/platform/core-impl/src/com/intellij/psi/impl/source/text/BlockSupportImpl.java b/platform/core-impl/src/com/intellij/psi/impl/source/text/BlockSupportImpl.java index 768a75def04b..0ef1af849fd1 100644 --- a/platform/core-impl/src/com/intellij/psi/impl/source/text/BlockSupportImpl.java +++ b/platform/core-impl/src/com/intellij/psi/impl/source/text/BlockSupportImpl.java @@ -285,18 +285,16 @@ public class BlockSupportImpl extends BlockSupport { @NotNull final DiffTreeChangeBuilder builder, @NotNull final ShallowNodeComparator comparator, @NotNull final FlyweightCapableTreeStructure newTreeStructure, - final ProgressIndicator indicator) { + @NotNull ProgressIndicator indicator) { TreeUtil.ensureParsedRecursivelyCheckingProgress(oldRoot, indicator); DiffTree.diff(createInterruptibleASTStructure(oldRoot, indicator), newTreeStructure, comparator, builder); } - private static ASTStructure createInterruptibleASTStructure(@NotNull final ASTNode oldRoot, @Nullable final ProgressIndicator indicator) { + private static ASTStructure createInterruptibleASTStructure(@NotNull final ASTNode oldRoot, @NotNull final ProgressIndicator indicator) { return new ASTStructure(oldRoot) { @Override public int getChildren(@NotNull ASTNode astNode, @NotNull Ref into) { - if (indicator != null) { - indicator.checkCanceled(); - } + indicator.checkCanceled(); return super.getChildren(astNode, into); } }; diff --git a/platform/core-impl/src/com/intellij/psi/impl/source/tree/TreeUtil.java b/platform/core-impl/src/com/intellij/psi/impl/source/tree/TreeUtil.java index f390511f8d08..99960ec65d66 100644 --- a/platform/core-impl/src/com/intellij/psi/impl/source/tree/TreeUtil.java +++ b/platform/core-impl/src/com/intellij/psi/impl/source/tree/TreeUtil.java @@ -57,13 +57,11 @@ public class TreeUtil { public static void ensureParsedRecursively(@NotNull ASTNode node) { ((TreeElement)node).acceptTree(new RecursiveTreeElementWalkingVisitor() { }); } - public static void ensureParsedRecursivelyCheckingProgress(@NotNull ASTNode node, final ProgressIndicator indicator) { + public static void ensureParsedRecursivelyCheckingProgress(@NotNull ASTNode node, @NotNull final ProgressIndicator indicator) { ((TreeElement)node).acceptTree(new RecursiveTreeElementWalkingVisitor() { @Override public void visitLeaf(LeafElement leaf) { - if (indicator != null) { - indicator.checkCanceled(); - } + indicator.checkCanceled(); } }); } From 2982ecf7c03452a5d0257b6b0ea8e178586293cb Mon Sep 17 00:00:00 2001 From: Alexander Zolotov Date: Wed, 19 Nov 2014 16:10:32 +0300 Subject: [PATCH 12/27] Yet another @TestDataFile annotation --- .../intellij/testFramework/fixtures/CodeInsightTestFixture.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/testFramework/src/com/intellij/testFramework/fixtures/CodeInsightTestFixture.java b/platform/testFramework/src/com/intellij/testFramework/fixtures/CodeInsightTestFixture.java index 41f0fb7d9e06..6be1c2ae4a9d 100644 --- a/platform/testFramework/src/com/intellij/testFramework/fixtures/CodeInsightTestFixture.java +++ b/platform/testFramework/src/com/intellij/testFramework/fixtures/CodeInsightTestFixture.java @@ -120,7 +120,7 @@ public interface CodeInsightTestFixture extends IdeaProjectTestFixture { * @return the VirtualFile for the copied directory in the test project directory. */ @NotNull - VirtualFile copyDirectoryToProject(@NonNls @NotNull String sourceFilePath, @NonNls @NotNull String targetPath); + VirtualFile copyDirectoryToProject(@TestDataFile @NonNls @NotNull String sourceFilePath, @NonNls @NotNull String targetPath); /** * Copies a file from the testdata directory to the same relative path in the test project directory. From 54408f18528082ccce6a31a65a3e1e8feece28a7 Mon Sep 17 00:00:00 2001 From: Dmitry Avdeev Date: Thu, 27 Nov 2014 14:50:08 +0300 Subject: [PATCH 13/27] IDEA-133345 Idea inserts wrong closing tag --- .../editorActions/XmlSlashTypedHandler.java | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/xml/impl/src/com/intellij/codeInsight/editorActions/XmlSlashTypedHandler.java b/xml/impl/src/com/intellij/codeInsight/editorActions/XmlSlashTypedHandler.java index 52851edc1e33..09994ffec9e5 100644 --- a/xml/impl/src/com/intellij/codeInsight/editorActions/XmlSlashTypedHandler.java +++ b/xml/impl/src/com/intellij/codeInsight/editorActions/XmlSlashTypedHandler.java @@ -144,8 +144,21 @@ public class XmlSlashTypedHandler extends TypedHandlerDelegate { return Result.CONTINUE; } - public boolean shouldReplace(XmlTag tag, XmlTag tag1) { + private static boolean shouldReplace(XmlTag tag, XmlTag tag1) { return tag1 != null && tag1 != tag && tag1.getTextOffset() > tag.getTextOffset() && - XmlUtil.getTokenOfType(tag1, XmlTokenType.XML_EMPTY_ELEMENT_END) == null && XmlTagUtil.getEndTagNameElement(tag1) == null; + hasUnclosedParent(tag1); + } + + private static boolean hasUnclosedParent(XmlTag tag) { + String name = tag.getName(); + while (tag != null) { + if (XmlUtil.getTokenOfType(tag, XmlTokenType.XML_EMPTY_ELEMENT_END) == null && + XmlTagUtil.getEndTagNameElement(tag) == null && + name.equals(tag.getName())) { + return true; + } + tag = tag.getParentTag(); + } + return false; } } \ No newline at end of file From 6fbd8697725f37359222e3d70e26fcb135f744ef Mon Sep 17 00:00:00 2001 From: "Ilya.Kazakevich" Date: Thu, 27 Nov 2014 15:03:17 +0300 Subject: [PATCH 14/27] PY-12564 Django: Template directories auto-configuration is missing on opening existing project PY-12876 Jinja2 Unresolved template reference --- .../PythonTemplateLanguage.java | 41 +++++++++++++++++++ .../templateLanguages/TemplatesService.java | 40 ++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 python/openapi/src/com/jetbrains/python/templateLanguages/PythonTemplateLanguage.java diff --git a/python/openapi/src/com/jetbrains/python/templateLanguages/PythonTemplateLanguage.java b/python/openapi/src/com/jetbrains/python/templateLanguages/PythonTemplateLanguage.java new file mode 100644 index 000000000000..28a7e082ec65 --- /dev/null +++ b/python/openapi/src/com/jetbrains/python/templateLanguages/PythonTemplateLanguage.java @@ -0,0 +1,41 @@ +package com.jetbrains.python.templateLanguages; + +import com.intellij.lang.Language; +import com.intellij.openapi.module.Module; +import com.intellij.psi.templateLanguages.TemplateLanguage; +import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Python template language + * @author Ilya.Kazakevich + */ +public abstract class PythonTemplateLanguage extends Language implements TemplateLanguage { + + + protected PythonTemplateLanguage(@Nullable final Language baseLanguage, + @NotNull @NonNls final String ID, + @NotNull @NonNls final String... mimeTypes) { + super(baseLanguage, ID, mimeTypes); + } + + protected PythonTemplateLanguage(@NotNull @NonNls final String id) { + super(id); + } + + /** + * @return template language readable name + */ + @NotNull + public abstract String getTemplateLanguageName(); + + /** + * Checks if text contains some chars that make us think this text uses appropriate template language and we should set + * this language as our project language + * + * @param text text with chars to check + * @return text contains some chars that make us think this text uses appropriate template language and we should set this language as our project language + */ + public abstract boolean isFileLeadsToLanguageSelection(@NotNull String text); +} diff --git a/python/openapi/src/com/jetbrains/python/templateLanguages/TemplatesService.java b/python/openapi/src/com/jetbrains/python/templateLanguages/TemplatesService.java index 03d82e338144..e7873d1bb7e3 100644 --- a/python/openapi/src/com/jetbrains/python/templateLanguages/TemplatesService.java +++ b/python/openapi/src/com/jetbrains/python/templateLanguages/TemplatesService.java @@ -23,7 +23,9 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.containers.ContainerUtil; import com.jetbrains.python.packaging.PyPackageManager; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import java.util.ArrayList; import java.util.List; /** @@ -31,12 +33,42 @@ import java.util.List; */ public abstract class TemplatesService { public static final String NONE = "None"; + /** + * @deprecated Use {@link #getKnownTemplateLanguages()} + * or {@link com.jetbrains.python.templateLanguages.PythonTemplateLanguage#getTemplateLanguageName()} + */ + @Deprecated public static final String DJANGO = "Django"; + /** + * @deprecated Use {@link #getKnownTemplateLanguages()} + * or {@link com.jetbrains.python.templateLanguages.PythonTemplateLanguage#getTemplateLanguageName()} + */ + @Deprecated public static final String MAKO = "Mako"; + /** + * @deprecated Use {@link #getKnownTemplateLanguages()} + * or {@link com.jetbrains.python.templateLanguages.PythonTemplateLanguage#getTemplateLanguageName()} + */ + @Deprecated public static final String JINJA2 = "Jinja2"; + /** + * @deprecated Use {@link #getKnownTemplateLanguages()} + * or {@link com.jetbrains.python.templateLanguages.PythonTemplateLanguage#getTemplateLanguageName()} + */ + @Deprecated public static final String WEB2PY = "Web2Py"; + /** + * @deprecated Use {@link #getKnownTemplateLanguages()} + * or {@link com.jetbrains.python.templateLanguages.PythonTemplateLanguage#getTemplateLanguageName()} + */ + @Deprecated public static final String CHAMELEON = "Chameleon"; + /** + * @deprecated Use {@link #getKnownTemplateLanguages()} + * or {@link com.jetbrains.python.templateLanguages.PythonTemplateLanguage#getTemplateLanguageName()} + */ + @Deprecated private static List ALL_TEMPLATE_LANGUAGES = ContainerUtil.immutableList(NONE, DJANGO, MAKO, @@ -47,16 +79,24 @@ public abstract class TemplatesService { public static List ALL_TEMPLATE_BINDINGS = ContainerUtil.immutableList("django-mako", "django-jinja", "django-chameleon", "flask-mako", "pyramid_jinja2"); + @Nullable public abstract Language getSelectedTemplateLanguage(); public static TemplatesService getInstance(Module module) { return ModuleServiceManager.getService(module, TemplatesService.class); } + /** + * @deprecated Use {@link #getKnownTemplateLanguages()} + * or {@link com.jetbrains.python.templateLanguages.PythonTemplateLanguage#getTemplateLanguageName()} + */ + @Deprecated public static List getAllTemplateLanguages() { return ALL_TEMPLATE_LANGUAGES; } + public abstract List getKnownTemplateLanguages(); + public abstract void setTemplateLanguage(String templateLanguage); @NotNull From 98dff6563604d7529fcd92ee2a918f78c0567680 Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Thu, 27 Nov 2014 11:29:20 +0100 Subject: [PATCH 15/27] tests startup: ensure v4 protocols on both sides of connection (IDEA-125656) --- .../src/com/intellij/rt/execution/junit/JUnitStarter.java | 3 ++- plugins/testng_rt/src/org/testng/RemoteTestNGStarter.java | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/plugins/junit_rt/src/com/intellij/rt/execution/junit/JUnitStarter.java b/plugins/junit_rt/src/com/intellij/rt/execution/junit/JUnitStarter.java index 5c0edbb9ded8..02287c929dcb 100644 --- a/plugins/junit_rt/src/com/intellij/rt/execution/junit/JUnitStarter.java +++ b/plugins/junit_rt/src/com/intellij/rt/execution/junit/JUnitStarter.java @@ -18,6 +18,7 @@ package com.intellij.rt.execution.junit; import com.intellij.rt.execution.junit.segments.SegmentedOutputStream; import java.io.*; +import java.net.Inet4Address; import java.net.InetAddress; import java.net.Socket; import java.util.ArrayList; @@ -108,7 +109,7 @@ public class JUnitStarter { } else if (arg.startsWith(SOCKET)) { final int port = Integer.parseInt(arg.substring(SOCKET.length())); try { - final Socket socket = new Socket(InetAddress.getByName(null), port); //start collecting tests + final Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), port); //start collecting tests final DataInputStream os = new DataInputStream(socket.getInputStream()); try { os.readBoolean();//wait for ready flag diff --git a/plugins/testng_rt/src/org/testng/RemoteTestNGStarter.java b/plugins/testng_rt/src/org/testng/RemoteTestNGStarter.java index 6c343dcf3512..3aa287ec66a1 100644 --- a/plugins/testng_rt/src/org/testng/RemoteTestNGStarter.java +++ b/plugins/testng_rt/src/org/testng/RemoteTestNGStarter.java @@ -44,7 +44,7 @@ public class RemoteTestNGStarter { if (arg.startsWith(SOCKET)) { final int port = Integer.parseInt(arg.substring(SOCKET.length())); try { - final Socket socket = new Socket(InetAddress.getByName(null), port); //start collecting tests + final Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), port); //start collecting tests final DataInputStream os = new DataInputStream(socket.getInputStream()); try { os.readBoolean();//wait for ready flag From 7b244b9669375c947579a1666f5e72084e85b226 Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Thu, 27 Nov 2014 11:48:51 +0100 Subject: [PATCH 16/27] make use of PsiFunctionalExpression --- .../impl/source/resolve/graphInference/InferenceSession.java | 3 +-- .../source/resolve/graphInference/PsiPolyExpressionUtil.java | 5 ++--- .../constraints/InputOutputConstraintFormula.java | 2 +- .../scope/conflictResolvers/JavaMethodsConflictResolver.java | 2 +- 4 files changed, 5 insertions(+), 7 deletions(-) diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java index 008216b63e06..fb12dd3bb658 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java @@ -311,8 +311,7 @@ public class InferenceSession { expression = PsiUtil.skipParenthesizedExprDown(expression); if (expression instanceof PsiConditionalExpression || expression instanceof PsiCallExpression || - expression instanceof PsiLambdaExpression || - expression instanceof PsiMethodReferenceExpression) { + expression instanceof PsiFunctionalExpression) { found = true; break; } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/PsiPolyExpressionUtil.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/PsiPolyExpressionUtil.java index cc7a64dc7d96..7c53f1d6097c 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/PsiPolyExpressionUtil.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/PsiPolyExpressionUtil.java @@ -30,8 +30,7 @@ import java.util.Set; */ public class PsiPolyExpressionUtil { public static boolean hasStandaloneForm(PsiExpression expression) { - if (expression instanceof PsiLambdaExpression || - expression instanceof PsiMethodReferenceExpression || + if (expression instanceof PsiFunctionalExpression || expression instanceof PsiParenthesizedExpression || expression instanceof PsiConditionalExpression || expression instanceof PsiCallExpression) { @@ -41,7 +40,7 @@ public class PsiPolyExpressionUtil { } public static boolean isPolyExpression(final PsiExpression expression) { - if (expression instanceof PsiLambdaExpression || expression instanceof PsiMethodReferenceExpression) { + if (expression instanceof PsiFunctionalExpression) { return true; } else if (expression instanceof PsiParenthesizedExpression) { diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/InputOutputConstraintFormula.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/InputOutputConstraintFormula.java index 8edb864a2391..827d7f64bea6 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/InputOutputConstraintFormula.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/InputOutputConstraintFormula.java @@ -42,7 +42,7 @@ public abstract class InputOutputConstraintFormula implements ConstraintFormula public Set getInputVariables(InferenceSession session) { final PsiExpression psiExpression = getExpression(); final PsiType type = getT(); - if (psiExpression instanceof PsiLambdaExpression || psiExpression instanceof PsiMethodReferenceExpression) { + if (psiExpression instanceof PsiFunctionalExpression) { final InferenceVariable inferenceVariable = session.getInferenceVariable(type); if (inferenceVariable != null) { return Collections.singleton(inferenceVariable); diff --git a/java/java-psi-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java b/java/java-psi-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java index 99e577b8506c..7e29a1bd448d 100644 --- a/java/java-psi-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java +++ b/java/java-psi-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java @@ -761,7 +761,7 @@ public class JavaMethodsConflictResolver implements PsiConflictResolver{ return thenSpecifics == elseSpecifics ? thenSpecifics : Specifics.NEITHER; } - if (expr instanceof PsiLambdaExpression || expr instanceof PsiMethodReferenceExpression) { + if (expr instanceof PsiFunctionalExpression) { if (expr instanceof PsiLambdaExpression && !((PsiLambdaExpression)expr).hasFormalParameterTypes()) { return Specifics.NEITHER; From 1dcf60a5187e25bc177978282989180309af1d92 Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Thu, 27 Nov 2014 12:34:19 +0100 Subject: [PATCH 17/27] do not mark methods as always inverted when they are used as method references (IDEA-133555) --- ...oleanMethodIsAlwaysInvertedInspectionBase.java | 8 ++++++++ .../methodReferenceIgnored/expected.xml | 3 +++ .../methodReferenceIgnored/src/Test.java | 14 ++++++++++++++ .../codeInspection/BooleanMethodInvertedTest.java | 15 +++++++++++++++ 4 files changed, 40 insertions(+) create mode 100644 plugins/InspectionGadgets/test/invertedBoolean/methodReferenceIgnored/expected.xml create mode 100644 plugins/InspectionGadgets/test/invertedBoolean/methodReferenceIgnored/src/Test.java diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/intellij/codeInspection/booleanIsAlwaysInverted/BooleanMethodIsAlwaysInvertedInspectionBase.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/intellij/codeInspection/booleanIsAlwaysInverted/BooleanMethodIsAlwaysInvertedInspectionBase.java index cf9cbb0be624..da6c519bb3b6 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/intellij/codeInspection/booleanIsAlwaysInverted/BooleanMethodIsAlwaysInvertedInspectionBase.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/intellij/codeInspection/booleanIsAlwaysInverted/BooleanMethodIsAlwaysInvertedInspectionBase.java @@ -77,6 +77,14 @@ public class BooleanMethodIsAlwaysInvertedInspectionBase extends GlobalJavaBatch refMethod.putUserData(ALWAYS_INVERTED, Boolean.FALSE); } } + + @Override + public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) { + super.visitMethodReferenceExpression(expression); + if (expression.isReferenceTo(psiElement)) { + refMethod.putUserData(ALWAYS_INVERTED, Boolean.FALSE); + } + } }); } diff --git a/plugins/InspectionGadgets/test/invertedBoolean/methodReferenceIgnored/expected.xml b/plugins/InspectionGadgets/test/invertedBoolean/methodReferenceIgnored/expected.xml new file mode 100644 index 000000000000..5e933496b9cf --- /dev/null +++ b/plugins/InspectionGadgets/test/invertedBoolean/methodReferenceIgnored/expected.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/plugins/InspectionGadgets/test/invertedBoolean/methodReferenceIgnored/src/Test.java b/plugins/InspectionGadgets/test/invertedBoolean/methodReferenceIgnored/src/Test.java new file mode 100644 index 000000000000..40a1948dcfb4 --- /dev/null +++ b/plugins/InspectionGadgets/test/invertedBoolean/methodReferenceIgnored/src/Test.java @@ -0,0 +1,14 @@ +class Test { + { + I ii = this::isFoo; + if (!isFoo()); + } + + boolean isFoo() { + return true; + } + + interface I { + boolean i(); + } +} \ No newline at end of file diff --git a/plugins/InspectionGadgets/testsrc/com/intellij/codeInspection/BooleanMethodInvertedTest.java b/plugins/InspectionGadgets/testsrc/com/intellij/codeInspection/BooleanMethodInvertedTest.java index 0fa73d215602..9051a173773a 100644 --- a/plugins/InspectionGadgets/testsrc/com/intellij/codeInspection/BooleanMethodInvertedTest.java +++ b/plugins/InspectionGadgets/testsrc/com/intellij/codeInspection/BooleanMethodInvertedTest.java @@ -1,5 +1,8 @@ package com.intellij.codeInspection; +import com.intellij.codeInspection.ex.GlobalInspectionToolWrapper; +import com.intellij.openapi.roots.LanguageLevelProjectExtension; +import com.intellij.pom.java.LanguageLevel; import com.siyeh.ig.IGInspectionTestCase; import com.intellij.codeInspection.booleanIsAlwaysInverted.BooleanMethodIsAlwaysInvertedInspection; @@ -61,6 +64,18 @@ public class BooleanMethodInvertedTest extends IGInspectionTestCase { doTest(); } + public void testMethodReferenceIgnored() throws Exception { + final LanguageLevelProjectExtension projectExtension = LanguageLevelProjectExtension.getInstance(getJavaFacade().getProject()); + final LanguageLevel oldLevel = projectExtension.getLanguageLevel(); + try { + projectExtension.setLanguageLevel(LanguageLevel.JDK_1_8); + doTest(); + } + finally { + projectExtension.setLanguageLevel(oldLevel); + } + } + private void doTest() throws Exception { doTest(false); } From cbb26891ca4bbdde53f87ca64e8c4e772a4c52c5 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Thu, 27 Nov 2014 15:06:00 +0300 Subject: [PATCH 18/27] Add utility method: com.intellij.util.ui.UIUtil.getWindow --- .../src/com/intellij/ide/IdeEventQueue.java | 9 ++------- .../ui/laf/darcula/ui/DarculaRootPaneUI.java | 17 ++++------------- .../application/impl/ApplicationImpl.java | 2 +- .../keymap/impl/IdeKeyEventDispatcher.java | 7 +------ .../wm/ex/LayoutFocusTraversalPolicyExt.java | 8 ++------ .../openapi/wm/impl/IdeGlassPaneImpl.java | 5 ++--- .../src/com/intellij/ui/FocusTrackback.java | 6 +++--- .../com/intellij/ui/popup/AbstractPopup.java | 10 ++-------- .../com/intellij/ui/popup/PopupComponent.java | 2 +- .../util/src/com/intellij/util/ui/UIUtil.java | 12 ++++++++++++ 10 files changed, 30 insertions(+), 48 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java b/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java index 435e230b6a47..2bbca4d274fc 100644 --- a/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java +++ b/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java @@ -656,12 +656,7 @@ public class IdeEventQueue extends EventQueue { try { Object owner = getNativeFocusOwner.invoke(mgr); if (owner instanceof Component) { - Component nativeFocusOwner = (Component)owner; - if (nativeFocusOwner instanceof Window) { - showingWindow = (Window)nativeFocusOwner; - } else { - showingWindow = SwingUtilities.getWindowAncestor(nativeFocusOwner); - } + showingWindow = UIUtil.getWindow((Component)owner); } } catch (Exception e1) { @@ -996,7 +991,7 @@ public class IdeEventQueue extends EventQueue { @Override public void run() { try { - final Window window = component instanceof Window ? (Window)component : SwingUtilities.windowForComponent(component); + final Window window = UIUtil.getWindow(component); if (window == null || !window.isActive()) { return; } diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaRootPaneUI.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaRootPaneUI.java index 8b2be4cca78c..114422f579e8 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaRootPaneUI.java +++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaRootPaneUI.java @@ -15,6 +15,8 @@ */ package com.intellij.ide.ui.laf.darcula.ui; +import com.intellij.util.ui.UIUtil; + import javax.swing.*; import javax.swing.event.MouseInputAdapter; import javax.swing.event.MouseInputListener; @@ -109,12 +111,7 @@ public class DarculaRootPaneUI extends BasicRootPaneUI { private void installWindowListeners(JRootPane root, Component parent) { - if (parent instanceof Window) { - myWindow = (Window)parent; - } - else { - myWindow = SwingUtilities.getWindowAncestor(parent); - } + myWindow = UIUtil.getWindow(parent); if (myWindow != null) { if (myMouseInputListener == null) { @@ -177,13 +174,7 @@ public class DarculaRootPaneUI extends BasicRootPaneUI { }); } - Window currWindow; - if (parent instanceof Window) { - currWindow = (Window)parent; - } - else { - currWindow = SwingUtilities.getWindowAncestor(parent); - } + Window currWindow = UIUtil.getWindow(parent); if (myWindowListener != null) { myCurrentWindow .removeWindowListener(myWindowListener); diff --git a/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java b/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java index 512ee8729dca..90bd90d474d1 100644 --- a/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java @@ -672,7 +672,7 @@ public class ApplicationImpl extends PlatformComponentManagerImpl implements App @Override @NotNull public ModalityState getModalityStateForComponent(@NotNull Component c) { - Window window = c instanceof Window ? (Window)c : SwingUtilities.windowForComponent(c); + Window window = UIUtil.getWindow(c); if (window == null) return getNoneModalityState(); //? return LaterInvocator.modalityStateForWindow(window); } diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/IdeKeyEventDispatcher.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/IdeKeyEventDispatcher.java index 852cc7f2e5ff..ff2820a5cc90 100644 --- a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/IdeKeyEventDispatcher.java +++ b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/IdeKeyEventDispatcher.java @@ -249,12 +249,7 @@ public final class IdeKeyEventDispatcher implements Disposable { * @throws IllegalArgumentException if component is null. */ public static boolean isModalContext(@NotNull Component component) { - Window window; - if (component instanceof Window) { - window = (Window)component; - } else { - window = SwingUtilities.getWindowAncestor(component); - } + Window window = UIUtil.getWindow(component); if (window instanceof IdeFrameImpl) { final Component pane = ((IdeFrameImpl) window).getGlassPane(); diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/ex/LayoutFocusTraversalPolicyExt.java b/platform/platform-impl/src/com/intellij/openapi/wm/ex/LayoutFocusTraversalPolicyExt.java index 5a64a1cd8bd6..b427b94dc2bf 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/ex/LayoutFocusTraversalPolicyExt.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/ex/LayoutFocusTraversalPolicyExt.java @@ -17,6 +17,7 @@ package com.intellij.openapi.wm.ex; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.registry.Registry; +import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; @@ -56,12 +57,7 @@ public class LayoutFocusTraversalPolicyExt extends LayoutFocusTraversalPolicy{ @Nullable public static LayoutFocusTraversalPolicyExt findWindowPolicy(Component c) { - Window wnd; - if (c instanceof Window) { - wnd = (Window)c; - } else { - wnd = SwingUtilities.getWindowAncestor(c); - } + Window wnd = UIUtil.getWindow(c); final FocusTraversalPolicy policy = wnd.getFocusTraversalPolicy(); if (policy instanceof LayoutFocusTraversalPolicyExt) { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeGlassPaneImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeGlassPaneImpl.java index 1613953287b6..ecee36ecf18a 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeGlassPaneImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeGlassPaneImpl.java @@ -109,8 +109,7 @@ public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEvent if (e instanceof MouseEvent) { MouseEvent me = (MouseEvent)e; - Window eventWindow = - me.getComponent() instanceof Window ? (Window)me.getComponent() : SwingUtilities.getWindowAncestor(me.getComponent()); + Window eventWindow = UIUtil.getWindow(me.getComponent()); if (isContextMenu(eventWindow)) return false; @@ -155,7 +154,7 @@ public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEvent MouseEvent me = (MouseEvent)e; final Component meComponent = me.getComponent(); if (!dispatched && meComponent != null) { - final Window eventWindow = meComponent instanceof Window ? (Window)meComponent : SwingUtilities.getWindowAncestor(meComponent); + final Window eventWindow = UIUtil.getWindow(meComponent); if (eventWindow != SwingUtilities.getWindowAncestor(myRootPane)) { return false; } diff --git a/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java b/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java index 5c531a7b6ae8..fee094a77ba6 100644 --- a/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java +++ b/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java @@ -69,7 +69,7 @@ public class FocusTrackback { private boolean myForcedRestore; public FocusTrackback(@NotNull Object requestor, Component parent, boolean mustBeShown) { - this(requestor, parent == null || parent instanceof Window ? (Window)parent : SwingUtilities.getWindowAncestor(parent), mustBeShown); + this(requestor, parent == null ? null : UIUtil.getWindow(parent), mustBeShown); } public FocusTrackback(@NotNull Object requestor, Window parent, boolean mustBeShown) { @@ -263,7 +263,7 @@ public class FocusTrackback { } if (myParentWindow != null) { - final Window to = toFocus instanceof Window ? (Window) toFocus : SwingUtilities.getWindowAncestor(toFocus); + final Window to = UIUtil.getWindow(toFocus); if (to != null && UIUtil.findUltimateParent(to) == UIUtil.findUltimateParent(myParentWindow)) { // IDEADEV-34537 toFocus.requestFocus(); result.setDone(); @@ -490,7 +490,7 @@ public class FocusTrackback { public static List getChildPopups(@NotNull final Component component) { List result = new ArrayList(); - final Window window = component instanceof Window ? (Window)component: SwingUtilities.windowForComponent(component); + final Window window = UIUtil.getWindow(component); if (window == null) return result; final List stack = getCleanStackForRoot(findUtlimateParent(window)); diff --git a/platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java b/platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java index 2f87b866e68a..02f0785971b7 100644 --- a/platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java +++ b/platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java @@ -1674,17 +1674,11 @@ public class AbstractPopup implements JBPopup { if (owner == null) return false; - Window wnd; - if (owner instanceof Window) { - wnd = (Window)owner; - } - else { - wnd = SwingUtilities.getWindowAncestor(owner); - } + Window wnd = UIUtil.getWindow(owner); for (Component each : components) { if (each != null && SwingUtilities.isDescendingFrom(owner, each)) { - Window eachWindow = each instanceof Window ? (Window)each : SwingUtilities.getWindowAncestor(each); + Window eachWindow = UIUtil.getWindow(each); if (eachWindow == wnd) { return true; } diff --git a/platform/platform-impl/src/com/intellij/ui/popup/PopupComponent.java b/platform/platform-impl/src/com/intellij/ui/popup/PopupComponent.java index 3b78e44b3f89..91aa6fc8d2b4 100644 --- a/platform/platform-impl/src/com/intellij/ui/popup/PopupComponent.java +++ b/platform/platform-impl/src/com/intellij/ui/popup/PopupComponent.java @@ -106,7 +106,7 @@ public interface PopupComponent { throw new IllegalArgumentException("Popup owner must be showing"); } - final Window wnd = owner instanceof Window ? (Window)owner: SwingUtilities.getWindowAncestor(owner); + final Window wnd = UIUtil.getWindow(owner); if (wnd instanceof Frame) { myDialog = new JDialog((Frame)wnd); } else if (wnd instanceof Dialog) { diff --git a/platform/util/src/com/intellij/util/ui/UIUtil.java b/platform/util/src/com/intellij/util/ui/UIUtil.java index ad8d3eeb36c3..5e3402802df6 100644 --- a/platform/util/src/com/intellij/util/ui/UIUtil.java +++ b/platform/util/src/com/intellij/util/ui/UIUtil.java @@ -3217,4 +3217,16 @@ public class UIUtil { textField.setColumns(4); } + + /** + * Returns the first window ancestor of the component. + * Note that this method returns the component itself if it is a window. + * + * @param component the component used to find corresponding window + * @return the first window ancestor of the component; or {@code null} + * if the component is not a window and is not contained inside a window + */ + public static Window getWindow(Component component) { + return component instanceof Window ? (Window)component : SwingUtilities.getWindowAncestor(component); + } } From 028f01a8acf022a77f4c263dc85efbdeb1a48228 Mon Sep 17 00:00:00 2001 From: Dmitry Batrak Date: Thu, 27 Nov 2014 15:15:06 +0300 Subject: [PATCH 19/27] IDEA-133443 concurrency issue during TraverseUI application execution --- .../src/com/intellij/idea/IdeaApplication.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/idea/IdeaApplication.java b/platform/platform-impl/src/com/intellij/idea/IdeaApplication.java index ba338533ca8a..d2094ddb6494 100644 --- a/platform/platform-impl/src/com/intellij/idea/IdeaApplication.java +++ b/platform/platform-impl/src/com/intellij/idea/IdeaApplication.java @@ -90,9 +90,7 @@ public class IdeaApplication { boolean isUnitTest = Boolean.getBoolean(IDEA_IS_UNIT_TEST); boolean headless = Main.isHeadless(); - if (!headless) { - patchSystem(); - } + patchSystem(headless); if (Main.isCommandLine()) { if (CommandLineApplication.ourInstance == null) { @@ -126,10 +124,12 @@ public class IdeaApplication { myStarter.premain(args); } - private static void patchSystem() { + private static void patchSystem(boolean headless) { System.setProperty("sun.awt.noerasebackground", "true"); IdeEventQueue.getInstance(); // replace system event queue + + if (headless) return; if (Patches.SUN_BUG_ID_6209673) { RepaintManager.setCurrentManager(new IdeRepaintManager()); From 3b6a2a67b4074fba62f88b2f06257a0397827ef8 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Thu, 27 Nov 2014 15:15:16 +0300 Subject: [PATCH 20/27] Check for modification after choosing value in a popup --- .../options/newEditor/ConfigurableEditor.java | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/ConfigurableEditor.java b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/ConfigurableEditor.java index 78f3a604e46c..a4b6cf60c1a2 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/ConfigurableEditor.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/ConfigurableEditor.java @@ -33,6 +33,7 @@ import com.intellij.openapi.util.ActionCallback; import com.intellij.ui.JBColor; import com.intellij.ui.RelativeFont; import com.intellij.ui.components.labels.LinkLabel; +import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.update.MergingUpdateQueue; import com.intellij.util.ui.update.Update; @@ -149,7 +150,7 @@ class ConfigurableEditor extends AbstractEditor implements AnActionListener, AWT case MouseEvent.MOUSE_RELEASED: case MouseEvent.MOUSE_DRAGGED: MouseEvent me = (MouseEvent)event; - if (isDescendingFrom(me.getComponent(), this)) { + if (isDescendingFrom(me.getComponent(), this) || isPopupOverEditor(me.getComponent())) { requestUpdate(); } break; @@ -178,6 +179,21 @@ class ConfigurableEditor extends AbstractEditor implements AnActionListener, AWT }); } + private boolean isPopupOverEditor(Component component) { + Window editor = UIUtil.getWindow(this); + if (editor != null) { + Window popup = UIUtil.getWindow(component); + if (popup != null && editor == popup.getParent()) { + if (popup instanceof JDialog) { + JDialog dialog = (JDialog)popup; + return Dialog.ModalityType.MODELESS == dialog.getModalityType(); + } + return popup instanceof JWindow; + } + } + return false; + } + void updateCurrent(Configurable configurable, boolean reset) { boolean modified = configurable != null && configurable.isModified(); myApplyAction.setEnabled(modified); From 536caece39ac4adcf1bfcfc5ae40d4772a95f011 Mon Sep 17 00:00:00 2001 From: Mikhail Golubev Date: Wed, 26 Nov 2014 21:01:40 +0300 Subject: [PATCH 21/27] PY-14432 Update relative import inside moved module/package --- .../refactoring/move/PyMoveFileHandler.java | 63 ++++++++++++++++--- .../after/src/pkg1/__init__.py | 0 .../after/src/pkg1/subpkg2/__init__.py | 0 .../after/src/pkg1/subpkg2/mod2.py | 0 .../after/src/subpkg1/__init__.py | 0 .../after/src/subpkg1/mod1.py | 14 +++++ .../after/src/subpkg1/mod3.py | 0 .../before/src/pkg1/__init__.py | 0 .../before/src/pkg1/subpkg1/__init__.py | 0 .../before/src/pkg1/subpkg1/mod1.py | 14 +++++ .../before/src/pkg1/subpkg1/mod3.py | 0 .../before/src/pkg1/subpkg2/__init__.py | 0 .../before/src/pkg1/subpkg2/mod2.py | 0 .../python/refactoring/PyMoveTest.java | 5 ++ 14 files changed, 89 insertions(+), 7 deletions(-) create mode 100644 python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/pkg1/__init__.py create mode 100644 python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/pkg1/subpkg2/__init__.py create mode 100644 python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/pkg1/subpkg2/mod2.py create mode 100644 python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/subpkg1/__init__.py create mode 100644 python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/subpkg1/mod1.py create mode 100644 python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/subpkg1/mod3.py create mode 100644 python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/__init__.py create mode 100644 python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg1/__init__.py create mode 100644 python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg1/mod1.py create mode 100644 python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg1/mod3.py create mode 100644 python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg2/__init__.py create mode 100644 python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg2/mod2.py diff --git a/python/src/com/jetbrains/python/refactoring/move/PyMoveFileHandler.java b/python/src/com/jetbrains/python/refactoring/move/PyMoveFileHandler.java index bf4d2623b070..efe00ad4a715 100644 --- a/python/src/com/jetbrains/python/refactoring/move/PyMoveFileHandler.java +++ b/python/src/com/jetbrains/python/refactoring/move/PyMoveFileHandler.java @@ -18,16 +18,14 @@ package com.jetbrains.python.refactoring.move; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.PsiDirectory; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; -import com.intellij.psi.PsiNamedElement; +import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.QualifiedName; import com.intellij.refactoring.RefactoringSettings; import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFileHandler; import com.intellij.usageView.UsageInfo; import com.intellij.util.IncorrectOperationException; +import com.intellij.util.PathUtil; import com.jetbrains.python.PyNames; import com.jetbrains.python.PyTokenTypes; import com.jetbrains.python.PythonFileType; @@ -42,11 +40,14 @@ import org.jetbrains.annotations.Nullable; import java.util.*; +import static com.intellij.openapi.vfs.VirtualFileManager.*; + /** * @author vlan */ public class PyMoveFileHandler extends MoveFileHandler { private static final Key REFERENCED_ELEMENT = Key.create("PY_REFERENCED_ELEMENT"); + private static final Key ORIGINAL_FILE_LOCATION = Key.create("PY_ORIGINAL_FILE_LOCATION"); @Override public boolean canProcessElement(PsiFile element) { @@ -69,8 +70,52 @@ public class PyMoveFileHandler extends MoveFileHandler { if (moveDestination != root && root != null && searchForReferences && !probablyNamespacePackage(file, moveDestination, root)) { CreatePackageAction.createInitPyInHierarchy(moveDestination, root); } + if (file instanceof PyFile) { + final PyFile module = (PyFile)file; + final String originalLocation = file.getUserData(ORIGINAL_FILE_LOCATION); + file.putUserData(ORIGINAL_FILE_LOCATION, null); + for (PyFromImportStatement statement : module.getFromImports()) { + if (statement.getRelativeLevel() == 0) { + continue; + } + if (originalLocation == null) { + continue; + } + String relativeImportBasePath = extractPath(originalLocation); + for (int level = 0; level < statement.getRelativeLevel(); level++) { + relativeImportBasePath = PathUtil.getParentPath(relativeImportBasePath); + } + if (!relativeImportBasePath.isEmpty()) { + //noinspection ConstantConditions + final String relativeImportBaseUrl = constructUrl(extractProtocol(originalLocation), relativeImportBasePath); + VirtualFile sourceFile = getInstance().findFileByUrl(relativeImportBaseUrl); + if (sourceFile != null && sourceFile.exists() && statement.getImportSource() != null) { + sourceFile = sourceFile.findFileByRelativePath(statement.getImportSource().getText().replace('.', '/')); + } + if (sourceFile != null) { + final PsiManager psiManager = file.getManager(); + final PsiFileSystemItem sourceElement; + if (sourceFile.isDirectory()) { + sourceElement = psiManager.findDirectory(sourceFile); + } + else { + sourceElement = psiManager.findFile(sourceFile); + } + final QualifiedName newName = QualifiedNameFinder.findShortestImportableQName(sourceElement); + final PsiElement fromKeyword = statement.getFirstChild(); + final PsiElement firstDot = fromKeyword.getNextSibling().getNextSibling(); + assert firstDot.getNode().getElementType() == PyTokenTypes.DOT; + final PsiWhiteSpace nextWhitespace = PsiTreeUtil.getNextSiblingOfType(firstDot, PsiWhiteSpace.class); + final PsiElement replacementEnd = nextWhitespace == null ? statement.getLastChild() : nextWhitespace.getPrevSibling(); + if (replacementEnd != firstDot) { + statement.deleteChildRange(firstDot.getNextSibling(), replacementEnd); + } + replaceWithQualifiedExpression(firstDot, newName); + } + } + } + } } - // TODO: Update relative imports } private static boolean probablyNamespacePackage(@NotNull PsiFile anchor, @NotNull PsiDirectory destination, @NotNull PsiDirectory root) { @@ -81,6 +126,7 @@ public class PyMoveFileHandler extends MoveFileHandler { if (destination.findFile(PyNames.INIT_DOT_PY) != null) { return false; } + //noinspection ConstantConditions destination = destination.getParent(); } return true; @@ -89,6 +135,7 @@ public class PyMoveFileHandler extends MoveFileHandler { @Override public List findUsages(PsiFile file, PsiDirectory newParent, boolean searchInComments, boolean searchInNonJavaFiles) { if (file != null) { + file.putUserData(ORIGINAL_FILE_LOCATION, file.getVirtualFile().getUrl()); final List usages = PyRefactoringUtil.findUsages(file, false); for (UsageInfo usage : usages) { final PsiElement element = usage.getElement(); @@ -128,7 +175,8 @@ public class PyMoveFileHandler extends MoveFileHandler { if (((PyReferenceExpression)element).isQualified()) { final QualifiedName newQualifiedName = QualifiedNameFinder.findCanonicalImportPath(newElement, element); replaceWithQualifiedExpression(element, newQualifiedName); - } else { + } + else { final QualifiedName newName = QualifiedName.fromComponents(PyClassRefactoringUtil.getOriginalName(newElement)); final PsiElement replaced = replaceWithQualifiedExpression(element, newName); PyClassRefactoringUtil.insertImport(replaced, newElement, null); @@ -141,8 +189,9 @@ public class PyMoveFileHandler extends MoveFileHandler { final PyImportOptimizer optimizer = new PyImportOptimizer(); for (PsiFile file : updatedFiles) { final boolean injectedFragment = InjectedLanguageManager.getInstance(file.getProject()).isInjectedFragment(file); - if (!injectedFragment) + if (!injectedFragment) { optimizer.processFile(file).run(); + } } } } diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/pkg1/__init__.py b/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/pkg1/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/pkg1/subpkg2/__init__.py b/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/pkg1/subpkg2/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/pkg1/subpkg2/mod2.py b/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/pkg1/subpkg2/mod2.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/subpkg1/__init__.py b/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/subpkg1/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/subpkg1/mod1.py b/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/subpkg1/mod1.py new file mode 100644 index 000000000000..43bd9de9b91e --- /dev/null +++ b/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/subpkg1/mod1.py @@ -0,0 +1,14 @@ +from pkg1 import subpkg2 +from pkg1.subpkg2 import mod2 + +# malformed imports +from +from import +from pkg1.subpkg2 import + +# absolute imports +import pkg1.subpkg2 as foo +from pkg1 import subpkg2 as bar +from subpkg1 import mod3 + +print(subpkg2, mod3, mod2, foo, bar) diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/subpkg1/mod3.py b/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/subpkg1/mod3.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/__init__.py b/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg1/__init__.py b/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg1/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg1/mod1.py b/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg1/mod1.py new file mode 100644 index 000000000000..974095a51398 --- /dev/null +++ b/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg1/mod1.py @@ -0,0 +1,14 @@ +from .. import subpkg2 +from ..subpkg2 import mod2 +from . import mod3 + +# malformed imports +from +from import +from ..subpkg2 import + +# absolute imports +import pkg1.subpkg2 as foo +from pkg1 import subpkg2 as bar + +print(subpkg2, mod3, mod2, foo, bar) diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg1/mod3.py b/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg1/mod3.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg2/__init__.py b/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg2/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg2/mod2.py b/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg2/mod2.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/python/testSrc/com/jetbrains/python/refactoring/PyMoveTest.java b/python/testSrc/com/jetbrains/python/refactoring/PyMoveTest.java index 6ac6a9ff54b3..7537582aa6e8 100644 --- a/python/testSrc/com/jetbrains/python/refactoring/PyMoveTest.java +++ b/python/testSrc/com/jetbrains/python/refactoring/PyMoveTest.java @@ -194,6 +194,11 @@ public class PyMoveTest extends PyTestCase { doMoveFileTest("nspkg/nssubpkg", ""); } + // PY-14432 + public void testRelativeImportInsideMovedModule() { + doMoveFileTest("pkg1/subpkg1", ""); + } + public void testRelativeImportOfNameFromInitPy() { doMoveFileTest("pkg/subpkg2", ""); } From db6410e9fc47558836f5422a2053e7641ccff6f2 Mon Sep 17 00:00:00 2001 From: Mikhail Golubev Date: Wed, 26 Nov 2014 21:06:01 +0300 Subject: [PATCH 22/27] Fix AIOOBE in PyImportOptimizer in case of incomplete import statement --- .../python/codeInsight/imports/PyImportOptimizer.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/python/src/com/jetbrains/python/codeInsight/imports/PyImportOptimizer.java b/python/src/com/jetbrains/python/codeInsight/imports/PyImportOptimizer.java index 2a0b09ef42fd..63ce0c00e5cd 100644 --- a/python/src/com/jetbrains/python/codeInsight/imports/PyImportOptimizer.java +++ b/python/src/com/jetbrains/python/codeInsight/imports/PyImportOptimizer.java @@ -20,6 +20,7 @@ import com.intellij.lang.ImportOptimizer; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileSystemItem; +import com.intellij.util.ArrayUtil; import com.jetbrains.python.formatter.PyBlock; import com.jetbrains.python.inspections.unresolvedReference.PyUnresolvedReferencesInspection; import com.jetbrains.python.psi.*; @@ -102,7 +103,8 @@ public class PyImportOptimizer implements ImportOptimizer { toImport = ((PyFromImportStatement)importStatement).resolveImportSource(); } else { - toImport = importStatement.getImportElements()[0].resolve(); + final PyImportElement firstImportElement = ArrayUtil.getFirstElement(importStatement.getImportElements()); + toImport = firstImportElement != null? firstImportElement.resolve() : null; } prioritize(importStatement, toImport); } From e3fc0ee66ac0e1b3cff41e6cf7cf90b5c16318f5 Mon Sep 17 00:00:00 2001 From: Mikhail Golubev Date: Wed, 26 Nov 2014 21:31:38 +0300 Subject: [PATCH 23/27] PY-13114 Inlining of method call does not add extra parenthesis Fix prioritization problem: reference expressions should have the same priority as indexing, slicing and function calls. --- .../python/refactoring/PyReplaceExpressionUtil.java | 5 ++++- .../inlinelocal/methodCallInlinedAsQualifier.after.py | 1 + .../inlinelocal/methodCallInlinedAsQualifier.before.py | 2 ++ .../com/jetbrains/python/refactoring/PyInlineLocalTest.java | 5 +++++ 4 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 python/testData/refactoring/inlinelocal/methodCallInlinedAsQualifier.after.py create mode 100644 python/testData/refactoring/inlinelocal/methodCallInlinedAsQualifier.before.py diff --git a/python/src/com/jetbrains/python/refactoring/PyReplaceExpressionUtil.java b/python/src/com/jetbrains/python/refactoring/PyReplaceExpressionUtil.java index 90689fc405f9..9b4c95f7d2b2 100644 --- a/python/src/com/jetbrains/python/refactoring/PyReplaceExpressionUtil.java +++ b/python/src/com/jetbrains/python/refactoring/PyReplaceExpressionUtil.java @@ -441,7 +441,10 @@ public class PyReplaceExpressionUtil implements PyElementTypes { private static int getExpressionPriority(PyElement expr) { int priority = 0; - if (expr instanceof PySubscriptionExpression || expr instanceof PySliceExpression || expr instanceof PyCallExpression) priority = 1; + if (expr instanceof PyReferenceExpression || + expr instanceof PySubscriptionExpression || + expr instanceof PySliceExpression || + expr instanceof PyCallExpression) priority = 1; else if (expr instanceof PyPrefixExpression) { final IElementType opType = getOperationType(expr); if (opType == PLUS || opType == MINUS || opType == TILDE) priority = 2; diff --git a/python/testData/refactoring/inlinelocal/methodCallInlinedAsQualifier.after.py b/python/testData/refactoring/inlinelocal/methodCallInlinedAsQualifier.after.py new file mode 100644 index 000000000000..1a3f524e748a --- /dev/null +++ b/python/testData/refactoring/inlinelocal/methodCallInlinedAsQualifier.after.py @@ -0,0 +1 @@ +a.method().strip() \ No newline at end of file diff --git a/python/testData/refactoring/inlinelocal/methodCallInlinedAsQualifier.before.py b/python/testData/refactoring/inlinelocal/methodCallInlinedAsQualifier.before.py new file mode 100644 index 000000000000..4bf5d50d679c --- /dev/null +++ b/python/testData/refactoring/inlinelocal/methodCallInlinedAsQualifier.before.py @@ -0,0 +1,2 @@ +res = a.method() +res.strip() \ No newline at end of file diff --git a/python/testSrc/com/jetbrains/python/refactoring/PyInlineLocalTest.java b/python/testSrc/com/jetbrains/python/refactoring/PyInlineLocalTest.java index a8b29f98daba..993c0fd794b2 100644 --- a/python/testSrc/com/jetbrains/python/refactoring/PyInlineLocalTest.java +++ b/python/testSrc/com/jetbrains/python/refactoring/PyInlineLocalTest.java @@ -104,6 +104,11 @@ public class PyInlineLocalTest extends PyTestCase { doTest(); } + // PY-13114 + public void testMethodCallInlinedAsQualifier() { + doTest(); + } + // PY-12409 public void testResultExceedsRightMargin() { final CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(myFixture.getProject()); From 38ee0bd960105e6d78cd63dd618774737c731899 Mon Sep 17 00:00:00 2001 From: Mikhail Golubev Date: Thu, 27 Nov 2014 14:32:53 +0300 Subject: [PATCH 24/27] PY-14432 Handle relative imports of modules, not only packages --- .../python/refactoring/move/PyMoveFileHandler.java | 11 ++++++++--- .../after/src/pkg1/__init__.py | 0 .../after/src/pkg1/subpkg2/__init__.py | 0 .../after/src/pkg1/subpkg2/mod2.py | 0 .../after/src/subpkg1/__init__.py | 0 .../after/src/subpkg1/mod1.py | 3 ++- .../after/src/subpkg1/mod3.py | 0 .../before/src/pkg1/__init__.py | 0 .../before/src/pkg1/subpkg1/__init__.py | 0 .../before/src/pkg1/subpkg1/mod1.py | 3 ++- .../before/src/pkg1/subpkg1/mod3.py | 0 .../before/src/pkg1/subpkg2/__init__.py | 0 .../before/src/pkg1/subpkg2/mod2.py | 0 .../com/jetbrains/python/refactoring/PyMoveTest.java | 2 +- 14 files changed, 13 insertions(+), 6 deletions(-) rename python/testData/refactoring/move/{relativeImportInsideMovedModule => relativeImportsInsideMovedModule}/after/src/pkg1/__init__.py (100%) rename python/testData/refactoring/move/{relativeImportInsideMovedModule => relativeImportsInsideMovedModule}/after/src/pkg1/subpkg2/__init__.py (100%) rename python/testData/refactoring/move/{relativeImportInsideMovedModule => relativeImportsInsideMovedModule}/after/src/pkg1/subpkg2/mod2.py (100%) rename python/testData/refactoring/move/{relativeImportInsideMovedModule => relativeImportsInsideMovedModule}/after/src/subpkg1/__init__.py (100%) rename python/testData/refactoring/move/{relativeImportInsideMovedModule => relativeImportsInsideMovedModule}/after/src/subpkg1/mod1.py (74%) rename python/testData/refactoring/move/{relativeImportInsideMovedModule => relativeImportsInsideMovedModule}/after/src/subpkg1/mod3.py (100%) rename python/testData/refactoring/move/{relativeImportInsideMovedModule => relativeImportsInsideMovedModule}/before/src/pkg1/__init__.py (100%) rename python/testData/refactoring/move/{relativeImportInsideMovedModule => relativeImportsInsideMovedModule}/before/src/pkg1/subpkg1/__init__.py (100%) rename python/testData/refactoring/move/{relativeImportInsideMovedModule => relativeImportsInsideMovedModule}/before/src/pkg1/subpkg1/mod1.py (74%) rename python/testData/refactoring/move/{relativeImportInsideMovedModule => relativeImportsInsideMovedModule}/before/src/pkg1/subpkg1/mod3.py (100%) rename python/testData/refactoring/move/{relativeImportInsideMovedModule => relativeImportsInsideMovedModule}/before/src/pkg1/subpkg2/__init__.py (100%) rename python/testData/refactoring/move/{relativeImportInsideMovedModule => relativeImportsInsideMovedModule}/before/src/pkg1/subpkg2/mod2.py (100%) diff --git a/python/src/com/jetbrains/python/refactoring/move/PyMoveFileHandler.java b/python/src/com/jetbrains/python/refactoring/move/PyMoveFileHandler.java index efe00ad4a715..e6f386f0d4e0 100644 --- a/python/src/com/jetbrains/python/refactoring/move/PyMoveFileHandler.java +++ b/python/src/com/jetbrains/python/refactoring/move/PyMoveFileHandler.java @@ -88,9 +88,14 @@ public class PyMoveFileHandler extends MoveFileHandler { if (!relativeImportBasePath.isEmpty()) { //noinspection ConstantConditions final String relativeImportBaseUrl = constructUrl(extractProtocol(originalLocation), relativeImportBasePath); - VirtualFile sourceFile = getInstance().findFileByUrl(relativeImportBaseUrl); - if (sourceFile != null && sourceFile.exists() && statement.getImportSource() != null) { - sourceFile = sourceFile.findFileByRelativePath(statement.getImportSource().getText().replace('.', '/')); + final VirtualFile relativeImportBaseDir = getInstance().findFileByUrl(relativeImportBaseUrl); + VirtualFile sourceFile = relativeImportBaseDir; + if (relativeImportBaseDir != null && relativeImportBaseDir.exists() && statement.getImportSource() != null) { + final String relativePath = statement.getImportSource().getText().replace('.', '/'); + sourceFile = relativeImportBaseDir.findFileByRelativePath(relativePath); + if (sourceFile == null) { + sourceFile = relativeImportBaseDir.findFileByRelativePath(relativePath + PyNames.DOT_PY); + } } if (sourceFile != null) { final PsiManager psiManager = file.getManager(); diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/pkg1/__init__.py b/python/testData/refactoring/move/relativeImportsInsideMovedModule/after/src/pkg1/__init__.py similarity index 100% rename from python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/pkg1/__init__.py rename to python/testData/refactoring/move/relativeImportsInsideMovedModule/after/src/pkg1/__init__.py diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/pkg1/subpkg2/__init__.py b/python/testData/refactoring/move/relativeImportsInsideMovedModule/after/src/pkg1/subpkg2/__init__.py similarity index 100% rename from python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/pkg1/subpkg2/__init__.py rename to python/testData/refactoring/move/relativeImportsInsideMovedModule/after/src/pkg1/subpkg2/__init__.py diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/pkg1/subpkg2/mod2.py b/python/testData/refactoring/move/relativeImportsInsideMovedModule/after/src/pkg1/subpkg2/mod2.py similarity index 100% rename from python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/pkg1/subpkg2/mod2.py rename to python/testData/refactoring/move/relativeImportsInsideMovedModule/after/src/pkg1/subpkg2/mod2.py diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/subpkg1/__init__.py b/python/testData/refactoring/move/relativeImportsInsideMovedModule/after/src/subpkg1/__init__.py similarity index 100% rename from python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/subpkg1/__init__.py rename to python/testData/refactoring/move/relativeImportsInsideMovedModule/after/src/subpkg1/__init__.py diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/subpkg1/mod1.py b/python/testData/refactoring/move/relativeImportsInsideMovedModule/after/src/subpkg1/mod1.py similarity index 74% rename from python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/subpkg1/mod1.py rename to python/testData/refactoring/move/relativeImportsInsideMovedModule/after/src/subpkg1/mod1.py index 43bd9de9b91e..67b279f7f9f7 100644 --- a/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/subpkg1/mod1.py +++ b/python/testData/refactoring/move/relativeImportsInsideMovedModule/after/src/subpkg1/mod1.py @@ -1,5 +1,6 @@ from pkg1 import subpkg2 from pkg1.subpkg2 import mod2 +from pkg1.subpkg2.mod2 import VAR # malformed imports from @@ -11,4 +12,4 @@ import pkg1.subpkg2 as foo from pkg1 import subpkg2 as bar from subpkg1 import mod3 -print(subpkg2, mod3, mod2, foo, bar) +print(subpkg2, mod3, mod2, foo, bar, VAR) diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/subpkg1/mod3.py b/python/testData/refactoring/move/relativeImportsInsideMovedModule/after/src/subpkg1/mod3.py similarity index 100% rename from python/testData/refactoring/move/relativeImportInsideMovedModule/after/src/subpkg1/mod3.py rename to python/testData/refactoring/move/relativeImportsInsideMovedModule/after/src/subpkg1/mod3.py diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/__init__.py b/python/testData/refactoring/move/relativeImportsInsideMovedModule/before/src/pkg1/__init__.py similarity index 100% rename from python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/__init__.py rename to python/testData/refactoring/move/relativeImportsInsideMovedModule/before/src/pkg1/__init__.py diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg1/__init__.py b/python/testData/refactoring/move/relativeImportsInsideMovedModule/before/src/pkg1/subpkg1/__init__.py similarity index 100% rename from python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg1/__init__.py rename to python/testData/refactoring/move/relativeImportsInsideMovedModule/before/src/pkg1/subpkg1/__init__.py diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg1/mod1.py b/python/testData/refactoring/move/relativeImportsInsideMovedModule/before/src/pkg1/subpkg1/mod1.py similarity index 74% rename from python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg1/mod1.py rename to python/testData/refactoring/move/relativeImportsInsideMovedModule/before/src/pkg1/subpkg1/mod1.py index 974095a51398..d6ab1c6f2d91 100644 --- a/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg1/mod1.py +++ b/python/testData/refactoring/move/relativeImportsInsideMovedModule/before/src/pkg1/subpkg1/mod1.py @@ -1,5 +1,6 @@ from .. import subpkg2 from ..subpkg2 import mod2 +from ..subpkg2.mod2 import VAR from . import mod3 # malformed imports @@ -11,4 +12,4 @@ from ..subpkg2 import import pkg1.subpkg2 as foo from pkg1 import subpkg2 as bar -print(subpkg2, mod3, mod2, foo, bar) +print(subpkg2, mod3, mod2, foo, bar, VAR) diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg1/mod3.py b/python/testData/refactoring/move/relativeImportsInsideMovedModule/before/src/pkg1/subpkg1/mod3.py similarity index 100% rename from python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg1/mod3.py rename to python/testData/refactoring/move/relativeImportsInsideMovedModule/before/src/pkg1/subpkg1/mod3.py diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg2/__init__.py b/python/testData/refactoring/move/relativeImportsInsideMovedModule/before/src/pkg1/subpkg2/__init__.py similarity index 100% rename from python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg2/__init__.py rename to python/testData/refactoring/move/relativeImportsInsideMovedModule/before/src/pkg1/subpkg2/__init__.py diff --git a/python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg2/mod2.py b/python/testData/refactoring/move/relativeImportsInsideMovedModule/before/src/pkg1/subpkg2/mod2.py similarity index 100% rename from python/testData/refactoring/move/relativeImportInsideMovedModule/before/src/pkg1/subpkg2/mod2.py rename to python/testData/refactoring/move/relativeImportsInsideMovedModule/before/src/pkg1/subpkg2/mod2.py diff --git a/python/testSrc/com/jetbrains/python/refactoring/PyMoveTest.java b/python/testSrc/com/jetbrains/python/refactoring/PyMoveTest.java index 7537582aa6e8..b96d827c3342 100644 --- a/python/testSrc/com/jetbrains/python/refactoring/PyMoveTest.java +++ b/python/testSrc/com/jetbrains/python/refactoring/PyMoveTest.java @@ -195,7 +195,7 @@ public class PyMoveTest extends PyTestCase { } // PY-14432 - public void testRelativeImportInsideMovedModule() { + public void testRelativeImportsInsideMovedModule() { doMoveFileTest("pkg1/subpkg1", ""); } From 38397c63f66a4dc3786257c71c76364b63067759 Mon Sep 17 00:00:00 2001 From: Mikhail Golubev Date: Thu, 27 Nov 2014 16:02:22 +0300 Subject: [PATCH 25/27] Make several improvements in AddImportHelper * Added missing javadoc and @Nullable/@NotNull annotations to several methods * Renamed addImportFromStatement to addFromImportStatement to be consistent with PSI * Renamed addImportFrom to addOrUpdateImportFrom to emphasise its intended behavior --- .../codeInsight/imports/AddImportHelper.java | 64 ++++++++++++++----- .../imports/ImportFromExistingAction.java | 2 +- .../testIntegration/PyTestCreator.java | 3 +- .../classes/PyClassRefactoringUtil.java | 2 +- .../membersManager/MethodsManager.java | 2 +- .../com/jetbrains/python/PyAddImportTest.java | 2 +- 6 files changed, 54 insertions(+), 21 deletions(-) diff --git a/python/src/com/jetbrains/python/codeInsight/imports/AddImportHelper.java b/python/src/com/jetbrains/python/codeInsight/imports/AddImportHelper.java index 916f58c65654..2710b0535652 100644 --- a/python/src/com/jetbrains/python/codeInsight/imports/AddImportHelper.java +++ b/python/src/com/jetbrains/python/codeInsight/imports/AddImportHelper.java @@ -175,7 +175,7 @@ public class AddImportHelper { } /** - * Adds an import statement, presumably below all other initial imports in the file. + * Adds an import statement, if it doesn't exist yet, presumably below all other initial imports in the file. * * @param file where to operate * @param name which to import (qualified is OK) @@ -183,7 +183,10 @@ public class AddImportHelper { * @param anchor place where the imported name was used * @return whether import statement was actually added */ - public static boolean addImportStatement(PsiFile file, String name, @Nullable String asName, ImportPriority priority, + public static boolean addImportStatement(@NotNull PsiFile file, + @NotNull String name, + @Nullable String asName, + @Nullable ImportPriority priority, @Nullable PsiElement anchor) { if (!(file instanceof PyFile)) { return false; @@ -214,15 +217,20 @@ public class AddImportHelper { } /** - * Adds an "import ... from ..." statement below other top-level imports. + * Adds a new {@link com.jetbrains.python.psi.PyFromImportStatement} statement below other top-level imports. * * @param file where to operate - * @param from name of the module - * @param name imported name - * @param asName optional name for 'as' clause - * @param anchor place where the imported name was used + * @param from import source (reference after {@code from} keyword) + * @param name imported name (identifier after {@code import} keyword) + * @param asName optional alias (identifier after {@code as} keyword) + * @param anchor place where the imported name was used. It's used to determine proper block where new import should be inserted, + * e.g. inside conditional block or try/except statement. */ - public static void addImportFromStatement(PsiFile file, String from, String name, @Nullable String asName, ImportPriority priority, + public static void addFromImportStatement(@NotNull PsiFile file, + @NotNull String from, + @NotNull String name, + @Nullable String asName, + @Nullable ImportPriority priority, @Nullable PsiElement anchor) { final PyElementGenerator generator = PyElementGenerator.getInstance(file.getProject()); final LanguageLevel languageLevel = LanguageLevel.forElement(file); @@ -253,18 +261,32 @@ public class AddImportHelper { } } - public static boolean addImportFrom(PsiFile file, @Nullable PsiElement target, String path, final String name, - @Nullable String asName, ImportPriority priority, @Nullable PsiElement anchor) { + /** + * Adds new {@link com.jetbrains.python.psi.PyFromImportStatement} in file or append {@link com.jetbrains.python.psi.PyImportElement} to + * existing from import statement. + * + * @param file module where import will be added + * @param from import source (reference after {@code from} keyword) + * @param name imported name (identifier after {@code import} keyword) + * @param asName optional alias (identifier after {@code as} keyword) + * @param priority optional import priority used to sort imports + * @param anchor used to determine insert position for new import statement + * @return whether import was actually added + * @see #addFromImportStatement + */ + public static boolean addOrUpdateFromImportStatement(@NotNull PsiFile file, + @NotNull String from, + @NotNull String name, + @Nullable String asName, + @Nullable ImportPriority priority, + @Nullable PsiElement anchor) { final List existingImports = ((PyFile)file).getFromImports(); for (PyFromImportStatement existingImport : existingImports) { - if (target != null && existingImport.getTextRange().getStartOffset() > target.getTextRange().getStartOffset()) { - continue; - } if (existingImport.isStarImport()) { continue; } final QualifiedName qName = existingImport.getImportSourceQName(); - if (qName != null && qName.toString().equals(path) && existingImport.getRelativeLevel() == 0) { + if (qName != null && qName.toString().equals(from) && existingImport.getRelativeLevel() == 0) { for (PyImportElement el : existingImport.getImportElements()) { final QualifiedName importedQName = el.getImportedQName(); if (importedQName != null && StringUtil.equals(name, importedQName.toString()) && StringUtil.equals(asName, el.getAsName())) { @@ -277,10 +299,20 @@ public class AddImportHelper { return false; } } - addImportFromStatement(file, path, name, asName, priority, anchor); + addFromImportStatement(file, from, name, asName, priority, anchor); return true; } + /** + * Adds either {@link com.jetbrains.python.psi.PyFromImportStatement} or {@link com.jetbrains.python.psi.PyImportStatement} + * to specified target depending on user preferences and whether it's possible to import element via "from" form of import + * (e.g. consider top level module). + * + * @param target element import is pointing to + * @param file file where import will be inserted + * @param element used to determine where to insert import + * @see com.jetbrains.python.codeInsight.PyCodeInsightSettings#PREFER_FROM_IMPORT + */ public static void addImport(final PsiNamedElement target, final PsiFile file, final PyElement element) { final boolean useQualified = !PyCodeInsightSettings.getInstance().PREFER_FROM_IMPORT; final PsiFileSystemItem toImport = @@ -301,7 +333,7 @@ public class AddImportHelper { element.replace(elementGenerator.createExpressionFromText(LanguageLevel.forElement(target), toImportQName + "." + targetName)); } else { - addImportFrom(file, null, toImportQName.toString(), target.getName(), null, priority, element); + addOrUpdateFromImportStatement(file, toImportQName.toString(), target.getName(), null, priority, element); } } } diff --git a/python/src/com/jetbrains/python/codeInsight/imports/ImportFromExistingAction.java b/python/src/com/jetbrains/python/codeInsight/imports/ImportFromExistingAction.java index 86c97a11eb67..a9ef7a03441f 100644 --- a/python/src/com/jetbrains/python/codeInsight/imports/ImportFromExistingAction.java +++ b/python/src/com/jetbrains/python/codeInsight/imports/ImportFromExistingAction.java @@ -183,7 +183,7 @@ public class ImportFromExistingAction implements QuestionAction { AddImportHelper.addLocalFromImportStatement(myTarget, qualifiedName, myName); } else { - AddImportHelper.addImportFromStatement(file, qualifiedName, myName, null, priority, null); + AddImportHelper.addFromImportStatement(file, qualifiedName, myName, null, priority, null); } } } diff --git a/python/src/com/jetbrains/python/codeInsight/testIntegration/PyTestCreator.java b/python/src/com/jetbrains/python/codeInsight/testIntegration/PyTestCreator.java index 4c13089f40ed..c9d8fea9826e 100644 --- a/python/src/com/jetbrains/python/codeInsight/testIntegration/PyTestCreator.java +++ b/python/src/com/jetbrains/python/codeInsight/testIntegration/PyTestCreator.java @@ -85,7 +85,8 @@ public class PyTestCreator implements TestCreator { PsiFile psiFile = PyUtil.getOrCreateFile( dialog.getTargetDir() + "/" + fileName, project); - AddImportHelper.addImportFrom(psiFile, null, "unittest", "TestCase", null, AddImportHelper.ImportPriority.BUILTIN, null); + AddImportHelper.addOrUpdateFromImportStatement(psiFile, "unittest", "TestCase", null, AddImportHelper.ImportPriority.BUILTIN, + null); PyElement createdClass = PyElementGenerator.getInstance(project).createFromText( LanguageLevel.forElement(psiFile), PyClass.class, diff --git a/python/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java b/python/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java index 8f0dfea18252..458fc127b29e 100644 --- a/python/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java +++ b/python/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java @@ -321,7 +321,7 @@ public final class PyClassRefactoringUtil { } final AddImportHelper.ImportPriority priority = AddImportHelper.getImportPriority(anchor, newFile); if (preferFromImport && !containingQName.getComponents().isEmpty()) { - return AddImportHelper.addImportFrom(file, null, containingQName.toString(), importedName, asName, priority, anchor); + return AddImportHelper.addOrUpdateFromImportStatement(file, containingQName.toString(), importedName, asName, priority, anchor); } else { return AddImportHelper.addImportStatement(file, containingQName.append(importedName).toString(), asName, priority, anchor); diff --git a/python/src/com/jetbrains/python/refactoring/classes/membersManager/MethodsManager.java b/python/src/com/jetbrains/python/refactoring/classes/membersManager/MethodsManager.java index 24b8ec0e3873..3c99ee8a0b9c 100644 --- a/python/src/com/jetbrains/python/refactoring/classes/membersManager/MethodsManager.java +++ b/python/src/com/jetbrains/python/refactoring/classes/membersManager/MethodsManager.java @@ -162,7 +162,7 @@ class MethodsManager extends MembersManager { * @param nameToImport what to import */ private static void addImportFromAbc(@NotNull final PsiFile file, @NotNull final String nameToImport) { - AddImportHelper.addImportFromStatement(file, ABC_META_PACKAGE, nameToImport, null, + AddImportHelper.addFromImportStatement(file, ABC_META_PACKAGE, nameToImport, null, AddImportHelper.ImportPriority.BUILTIN, null); } diff --git a/python/testSrc/com/jetbrains/python/PyAddImportTest.java b/python/testSrc/com/jetbrains/python/PyAddImportTest.java index 5cedd4af2045..c0b2ee5bb214 100644 --- a/python/testSrc/com/jetbrains/python/PyAddImportTest.java +++ b/python/testSrc/com/jetbrains/python/PyAddImportTest.java @@ -53,7 +53,7 @@ public class PyAddImportTest extends PyTestCase { new WriteCommandAction(myFixture.getProject(), myFixture.getFile()) { @Override protected void run(Result result) throws Throwable { - AddImportHelper.addImportFrom(myFixture.getFile(), null, path, name, null, AddImportHelper.ImportPriority.BUILTIN, null); + AddImportHelper.addOrUpdateFromImportStatement(myFixture.getFile(), path, name, null, AddImportHelper.ImportPriority.BUILTIN, null); } }.execute(); myFixture.checkResultByFile("addImport/" + getTestName(true) + ".after.py"); From 10d0a1dfb77234aa354535d3e245845f832f5018 Mon Sep 17 00:00:00 2001 From: Julia Beliaeva Date: Thu, 27 Nov 2014 16:12:51 +0300 Subject: [PATCH 26/27] [vcs-log] fix newlines in getSelectedText in details panel IDEA-131488 --- .../vcs/log/ui/frame/DetailsPanel.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/DetailsPanel.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/DetailsPanel.java index abc2348e32d7..69be8a31c89b 100644 --- a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/DetailsPanel.java +++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/DetailsPanel.java @@ -50,8 +50,17 @@ import javax.swing.border.CompoundBorder; import javax.swing.border.MatteBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; +import javax.swing.text.BadLocationException; import javax.swing.text.DefaultCaret; +import javax.swing.text.Document; +import javax.swing.text.Position; +import javax.swing.text.html.HTMLEditorKit; +import javax.swing.text.html.parser.ParserDelegator; import java.awt.*; +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -315,6 +324,47 @@ class DetailsPanel extends JPanel implements ListSelectionListener { return authorText; } + @Override + public String getSelectedText() { + Document doc = getDocument(); + int start = getSelectionStart(); + int end = getSelectionEnd(); + + try { + Position p0 = doc.createPosition(start); + Position p1 = doc.createPosition(end); + StringWriter sw = new StringWriter(p1.getOffset() - p0.getOffset()); + getEditorKit().write(sw, doc, p0.getOffset(), p1.getOffset() - p0.getOffset()); + + MyHtml2Text parser = new MyHtml2Text(); + parser.parse(new StringReader(sw.toString())); + return parser.getText(); + } + catch (BadLocationException e) { + } + catch (IOException e) { + } + return super.getSelectedText(); + } + + private static class MyHtml2Text extends HTMLEditorKit.ParserCallback { + @NotNull private StringBuffer myBuffer; + + public void parse(Reader in) throws IOException { + myBuffer = new StringBuffer(); + new ParserDelegator().parse(in, this, Boolean.TRUE); + } + + public void handleText(char[] text, int pos) { + myBuffer.append(text); + myBuffer.append("\n"); + } + + public String getText() { + return myBuffer.toString(); + } + } + @Override public Color getBackground() { return getDetailsBackground(); From 76fc272667fb3ada3e213fc24b975f94b0f997ff Mon Sep 17 00:00:00 2001 From: Sergey Ignatov Date: Thu, 27 Nov 2014 16:20:29 +0300 Subject: [PATCH 27/27] always set opaque false for editor vertical scrollbar --- .../src/com/intellij/openapi/editor/impl/EditorImpl.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java index e4d03477e47d..232f959cfee2 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java @@ -489,6 +489,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi myEditorComponent = new EditorComponentImpl(this); myScrollPane = new MyScrollPane(); myVerticalScrollBar = (MyScrollBar)myScrollPane.getVerticalScrollBar(); + myVerticalScrollBar.setOpaque(false); myPanel = new JPanel(); UIUtil.putClientProperty( @@ -4852,6 +4853,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi public void setUI(ScrollBarUI ui) { if (myPersistentUI == null) myPersistentUI = ui; super.setUI(myPersistentUI); + setOpaque(false); } @Override