Merge remote-tracking branch 'origin/master'

This commit is contained in:
Konstantin Bulenkov
2012-10-26 00:49:43 +02:00
88 changed files with 1525 additions and 836 deletions
@@ -287,6 +287,7 @@ public class ChangeContextUtil {
try{
PsiExpression qualifier = refExpr.getQualifierExpression();
if (!(qualifier instanceof PsiReferenceExpression)) return false;
if (refExpr.getTypeParameters().length > 0) return false;
PsiElement qualifierRefElement = ((PsiReferenceExpression)qualifier).resolve();
if (!(qualifierRefElement instanceof PsiClass)) return false;
PsiElement refElement = refExpr.resolve();
@@ -64,9 +64,6 @@ public class JavaCompletionSorting {
else {
afterPriority.add(new PreferDefaultTypeWeigher(expectedTypes, parameters));
}
if (!JavaCompletionData.START_FOR.accepts(position)) {
afterPriority.add(new PreferByKindWeigher(type, position));
}
ContainerUtil.addIfNotNull(afterPriority, recursion(parameters, expectedTypes));
if (!smart && !afterNew) {
afterPriority.add(new PreferExpected(false, expectedTypes));
@@ -117,7 +114,8 @@ public class JavaCompletionSorting {
});
}
sorter = sorter.weighAfter("priority", afterPriority.toArray(new LookupElementWeigher[afterPriority.size()]));
sorter = sorter.weighAfter("prefix", new PreferNonGeneric(), new PreferAccessible(position), new PreferSimple(), new PreferEnumConstants(parameters));
sorter = sorter.weighAfter("prefix", new PreferByKindWeigher(type, position));
sorter = sorter.weighAfter("stats", new PreferNonGeneric(), new PreferAccessible(position), new PreferSimple(), new PreferEnumConstants(parameters));
sorter = sorter.weighAfter("proximity", afterProximity.toArray(new LookupElementWeigher[afterProximity.size()]));
return result.withRelevanceSorter(sorter);
}
@@ -93,7 +93,13 @@ public class PreferByKindWeigher extends LookupElementWeigher {
assert annotation != null;
PsiAnnotationOwner owner = annotation.getOwner();
if (owner instanceof PsiModifierList || owner instanceof PsiTypeElement || owner instanceof PsiTypeParameter) {
PsiElement member = owner instanceof PsiModifierList ? ((PsiElement)owner).getParent() : (PsiElement)owner;
PsiElement member = (PsiElement)owner;
if (member instanceof PsiModifierList) {
member = member.getParent();
}
if (member instanceof PsiTypeElement && member.getParent() instanceof PsiMethod) {
member = member.getParent();
}
final String[] elementTypeFields = PsiAnnotationImpl.getApplicableElementTypeFields(member);
return new Condition<PsiClass>() {
@Override
@@ -23,8 +23,6 @@ import com.intellij.openapi.util.Comparing;
import com.intellij.patterns.PsiJavaPatterns;
import com.intellij.patterns.StandardPatterns;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.filters.AndFilter;
import com.intellij.psi.filters.ClassFilter;
import com.intellij.psi.filters.ElementFilter;
@@ -53,7 +51,7 @@ class RecursionWeigher extends LookupElementWeigher {
public RecursionWeigher(PsiElement position,
@NotNull PsiReferenceExpression reference,
PsiMethodCallExpression expression,
@Nullable PsiMethodCallExpression expression,
ExpectedTypeInfo[] expectedInfos) {
super("recursion");
myFilter = recursionFilter(position);
@@ -70,7 +68,7 @@ class RecursionWeigher extends LookupElementWeigher {
}
@Nullable
private static PsiExpression normalizeQualifier(PsiElement qualifier) {
private static PsiExpression normalizeQualifier(@Nullable PsiElement qualifier) {
return qualifier instanceof PsiThisExpression || !(qualifier instanceof PsiExpression) ? null : (PsiExpression)qualifier;
}
@@ -127,21 +125,23 @@ class RecursionWeigher extends LookupElementWeigher {
return Result.passingObjectToItself;
}
if (myExpression != null) {
if (myExpectedInfos != null) {
final PsiType itemType = JavaCompletionUtil.getLookupElementType(element);
for (final ExpectedTypeInfo expectedInfo : myExpectedInfos) {
PsiMethod calledMethod = expectedInfo.getCalledMethod();
if (calledMethod != null && itemType != null) {
if (calledMethod.equals(myPositionMethod) && expectedInfo.getType().isAssignableFrom(itemType)) {
return myDelegate ? Result.delegation : Result.recursive;
}
if (isGetterSetterAssignment(object, calledMethod)) {
return myDelegate ? Result.delegation : Result.recursive;
}
}
if (myExpectedInfos != null) {
final PsiType itemType = JavaCompletionUtil.getLookupElementType(element);
for (final ExpectedTypeInfo expectedInfo : myExpectedInfos) {
PsiMethod calledMethod = expectedInfo.getCalledMethod();
if (itemType != null &&
calledMethod != null &&
calledMethod.equals(myPositionMethod) &&
expectedInfo.getType().isAssignableFrom(itemType)) {
return myDelegate ? Result.delegation : Result.recursive;
}
String propertyName = getSetterPropertyName(calledMethod);
if (propertyName != null && isGetterSetterAssignment(object, propertyName)) {
return myDelegate ? Result.delegation : Result.recursive;
}
}
}
if (myExpression != null) {
return Result.normal;
}
@@ -159,16 +159,25 @@ class RecursionWeigher extends LookupElementWeigher {
return Result.normal;
}
private static boolean isGetterSetterAssignment(Object lookupObject, PsiMethod calledMethod) {
if (!PropertyUtil.isSimplePropertySetter(calledMethod)) {
return false;
@Nullable
private String getSetterPropertyName(@Nullable PsiMethod calledMethod) {
if (PropertyUtil.isSimplePropertySetter(calledMethod)) {
assert calledMethod != null;
return PropertyUtil.getPropertyName(calledMethod);
}
PsiReferenceExpression reference = ExcludeSillyAssignment.getAssignedReference(myPosition);
if (reference != null) {
PsiElement target = reference.resolve();
if (target instanceof PsiField) {
return PropertyUtil.suggestPropertyName((PsiField)target);
}
}
return null;
}
String prop = PropertyUtil.getPropertyName(calledMethod);
assert prop != null;
private static boolean isGetterSetterAssignment(Object lookupObject, String prop) {
if (lookupObject instanceof PsiField &&
prop.equals(JavaCodeStyleManager.getInstance(calledMethod.getProject())
.variableNameToPropertyName(((PsiField)lookupObject).getName(), VariableKind.FIELD))) {
prop.equals(PropertyUtil.suggestPropertyName((PsiField)lookupObject))) {
return true;
}
if (lookupObject instanceof PsiMethod &&
@@ -181,7 +190,7 @@ class RecursionWeigher extends LookupElementWeigher {
private boolean isPassingObjectToItself(Object object) {
if (object instanceof PsiThisExpression) {
return !myDelegate || myCallQualifier instanceof PsiSuperExpression;
return myCallQualifier != null && !myDelegate || myCallQualifier instanceof PsiSuperExpression;
}
return myCallQualifier instanceof PsiReferenceExpression &&
object.equals(((PsiReferenceExpression)myCallQualifier).advancedResolve(true).getElement());
@@ -18,11 +18,13 @@ package com.intellij.codeInspection;
import com.intellij.codeInsight.daemon.GroupNames;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.ArrayUtilRt;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -115,6 +117,7 @@ public class LambdaCanBeMethReferenceInspection extends BaseJavaLocalInspectionT
if (psiMethod == null) {
isConstructor = true;
if (!(methodCall instanceof PsiNewExpression)) return null;
if (((PsiNewExpression)methodCall).getAnonymousClass() != null) return null;
final PsiJavaCodeReferenceElement classReference = ((PsiNewExpression)methodCall).getClassOrAnonymousClassReference();
if (classReference == null) return null;
containingClass = (PsiClass)classReference.resolve();
@@ -145,22 +148,37 @@ public class LambdaCanBeMethReferenceInspection extends BaseJavaLocalInspectionT
if (parameters[i + offset] != resolve) return null;
}
final PsiExpression qualifierExpression;
if (methodCall instanceof PsiMethodCallExpression) {
qualifierExpression = ((PsiMethodCallExpression)methodCall).getMethodExpression().getQualifierExpression();
}
else if (methodCall instanceof PsiNewExpression) {
qualifierExpression = ((PsiNewExpression)methodCall).getQualifier();
}
else {
qualifierExpression = null;
}
if (offset > 0) {
final PsiExpression qualifierExpression;
if (methodCall instanceof PsiMethodCallExpression) {
qualifierExpression = ((PsiMethodCallExpression)methodCall).getMethodExpression().getQualifierExpression();
}
else if (methodCall instanceof PsiNewExpression) {
qualifierExpression = ((PsiNewExpression)methodCall).getQualifier();
}
else {
qualifierExpression = null;
}
if (!(qualifierExpression instanceof PsiReferenceExpression) ||
((PsiReferenceExpression)qualifierExpression).resolve() != parameters[0]) {
return null;
}
}
else if (qualifierExpression != null) {
final Ref<Boolean> usedInQualifier = new Ref<Boolean>(false);
qualifierExpression.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitReferenceExpression(PsiReferenceExpression expression) {
final PsiElement resolve = expression.resolve();
if (resolve instanceof PsiParameter && ArrayUtilRt.find(parameters, resolve) > -1) {
usedInQualifier.set(true);
return;
}
super.visitReferenceExpression(expression);
}
});
if (usedInQualifier.get()) return null;
}
return methodCall;
}
}
@@ -181,7 +199,7 @@ public class LambdaCanBeMethReferenceInspection extends BaseJavaLocalInspectionT
final String methodReferenceName = methodExpression.getReferenceName();
if (qualifierExpression != null) {
boolean isReceiverType = LambdaUtil.isReceiverType(functionalInterfaceType, containingClass, psiMethod);
methodRefText = (isReceiverType ? containingClass.getQualifiedName() : qualifierExpression.getText()) + "::" + methodReferenceName;
methodRefText = (isReceiverType ? containingClass.getQualifiedName() : qualifierExpression.getText()) + "::" + ((PsiMethodCallExpression)element).getTypeArgumentList().getText() + methodReferenceName;
}
else {
methodRefText =
@@ -17,6 +17,7 @@ package com.intellij.psi.filters.element;
import com.intellij.psi.*;
import com.intellij.psi.filters.ElementFilter;
import org.jetbrains.annotations.Nullable;
/**
* Created by IntelliJ IDEA.
@@ -26,14 +27,13 @@ import com.intellij.psi.filters.ElementFilter;
* To change this template use Options | File Templates.
*/
public class ExcludeSillyAssignment implements ElementFilter {
@Override
public boolean isAcceptable(Object element, PsiElement context) {
if(!(element instanceof PsiElement)) return true;
PsiElement each = context;
@Nullable
public static PsiReferenceExpression getAssignedReference(PsiElement position) {
PsiElement each = position;
while (each != null && !(each instanceof PsiFile)) {
if (each instanceof PsiExpressionList || each instanceof PsiPrefixExpression || each instanceof PsiPolyadicExpression) {
return true;
return null;
}
if (each instanceof PsiAssignmentExpression) {
@@ -43,18 +43,29 @@ public class ExcludeSillyAssignment implements ElementFilter {
final PsiElement qualifier = referenceExpression.getQualifier();
if (qualifier != null) {
if (!(qualifier instanceof PsiThisExpression) || ((PsiThisExpression)qualifier).getQualifier() != null) {
return true;
return null;
}
}
return !referenceExpression.isReferenceTo((PsiElement)element);
return referenceExpression;
}
return true;
return null;
}
each = each.getContext();
}
return null;
}
@Override
public boolean isAcceptable(Object element, PsiElement context) {
if(!(element instanceof PsiElement)) return true;
PsiReferenceExpression referenceExpression = getAssignedReference(context);
if (referenceExpression != null && referenceExpression.isReferenceTo((PsiElement)element)) {
return false;
}
return true;
}
@@ -17,8 +17,10 @@ package com.intellij.refactoring.move.moveMembers;
import com.intellij.codeInsight.ChangeContextUtil;
import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.JavaResolveUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.*;
@@ -171,7 +173,17 @@ public class MoveJavaMemberHandler implements MoveMemberHandler {
changeQualifier(refExpr, usage.qualifierClass, usage.member);
}
else {
refExpr.setQualifierExpression(null);
final PsiReferenceParameterList parameterList = refExpr.getParameterList();
if (parameterList != null && parameterList.getTypeArguments().length == 0){
refExpr.setQualifierExpression(null);
} else {
final Project project = element.getProject();
final PsiClass targetClass =
JavaPsiFacade.getInstance(project).findClass(options.getTargetClassName(), GlobalSearchScope.projectScope(project));
if (targetClass != null) {
changeQualifier(refExpr, targetClass, usage.member);
}
}
}
}
else { // no qualifier
@@ -506,6 +506,9 @@ public class PropertyUtil {
modifierList.addAfter(factory.createAnnotationFromText("@" + annotationQName, listOwner), null);
}
public static String suggestPropertyName(PsiField field) {
return suggestPropertyName(field.getProject(), field);
}
public static String suggestPropertyName(Project project, PsiField field) {
JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
VariableKind kind = codeStyleManager.getVariableKind(field);
@@ -0,0 +1,10 @@
class PsiElement {}
public class Foo {
Object psiElement() {}
void foo() {
Psi<caret>
}
}
@@ -0,0 +1,6 @@
class Foo {
@T<caret>
public static void main(String[] args) {
}
}
@@ -1,22 +1,14 @@
class T {
I myLastI;
I getLastI() { return myLastI; }
I lastI;
I getLastI() { return lastI; }
void setLastI(I a) {
myLastI = <caret>
lastI = <caret>
}
}
class I {
static final I _1 = new I();
static final I _2a = new I();
static final I _3a = new I();
static final I _4a = new I();
static final I _5a = new I();
static final I _6a = new I();
static final I _7a = new I();
static final I _8a = new I();
static final I _9a = new I();
static I valueOf(String sth) {
return null;
@@ -0,0 +1,12 @@
// "Replace with method reference" "true"
interface Foo<A, B> {
B f(A a);
}
interface DeeBee<A> {
A run(Void c) throws SQLException;
<B> DeeBee<B> bind(final Foo<A, DeeBee<B>> f) default {
return f.f(null)::run;
}
}
@@ -0,0 +1,16 @@
// "Replace with method reference" "true"
interface Foo<A, B> {
B f(A a);
}
interface DeeBee<A> {
A run(Void c) throws SQLException;
<B> DeeBee<B> bind(final Foo<A, DeeBee<B>> f) default {
return new Dee<caret>Bee<B> () {
public B run(final Void c) throws SQLException {
return f.f(null).run(c);
}
};
}
}
@@ -0,0 +1,16 @@
// "Replace with method reference" "false"
interface Foo<A, B> {
B f(A a);
}
interface DeeBee<A> {
A run(Void c) throws SQLException;
<B> DeeBee<B> bind(final Foo<A, DeeBee<B>> f) default {
return new Dee<caret>Bee<B> () {
public B run(final Void c) throws SQLException {
return f.f(DeeBee.this.run(c)).run(c);
}
};
}
}
@@ -0,0 +1,13 @@
// "Replace lambda with method reference" "false"
class NonStaticInner3 {
class Foo {
}
interface I1<X> {
X m();
}
{
I1<Foo> b2 = () -> <caret>new Foo(){};
}
}
@@ -0,0 +1,16 @@
package pack1;
interface Eff<A, B> {
B f(A a);
}
abstract class POne<A> {
abstract A _1();
}
final class Hooray<A> {
public <B> Hooray<B> map(final Eff<A, B> f) {
return null;
}
}
@@ -0,0 +1,15 @@
package pack1;
public class C {
static <A> POne<Hooray<A>> sequence(final Hooray<POne<A>> as) {
return new POne<Hooray<A>>() {
public Hooray<A> _1() {
return as.map(C.<A>__1());
}
};
}
static <A> Eff<POne<A>, A> __1() {
return POne::_1;
}
}
@@ -0,0 +1,28 @@
package pack1;
interface Eff<A, B> {
B f(A a);
}
abstract class POne<A> {
abstract A _1();
static <A> POne<Hooray<A>> sequence(final Hooray<POne<A>> as) {
return new POne<Hooray<A>>() {
public Hooray<A> _1() {
return as.map(POne.<A>__1());
}
};
}
static <A> Eff<POne<A>, A> __1() {
return POne::_1;
}
}
final class Hooray<A> {
public <B> Hooray<B> map(final Eff<A, B> f) {
return null;
}
}
@@ -0,0 +1,4 @@
package pack1;
public class C {
}
@@ -1,4 +1,4 @@
package com.intellij.codeInsight;
package com.intellij.codeInsight
import com.intellij.JavaTestUtil;
import com.intellij.ide.actions.CopyReferenceAction;
@@ -7,7 +7,6 @@ import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.psi.PsiFile;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import org.jetbrains.annotations.NonNls
import com.intellij.openapi.util.io.FileUtil;
public class CopyReferenceTest extends LightCodeInsightFixtureTestCase {
@NonNls private static final String BASE_PATH = "/codeInsight/copyReference";
@@ -53,11 +52,10 @@ public class CopyReferenceTest extends LightCodeInsightFixtureTestCase {
myFixture.configureByText 'a.java', '''
<caret>class Foo {
}'''
def path = FileUtil.toSystemDependentName(myFixture.file.virtualFile.path)
performCopy()
myFixture.configureByText 'a.txt', ''
performPaste()
myFixture.checkResult "$path:2"
myFixture.checkResult "/a.java:2"
}
private void doTest() throws Exception {
@@ -864,7 +864,11 @@ class Foo {
}
public void testNonFinishedParameterComma() {
myFixture.configureByText("a.java", """ class Foo { void foo(int aaa, int aaaaa) { foo(<caret>) } } """)
myFixture.configureByText("a.java", """
class Foo {
void foo(int aaa, int aaaaa) { }
void bar(int aaa, int aaaaa) { foo(<caret>) }
} """)
type 'a,'
assert myFixture.editor.document.text.contains('foo(aaa, )')
}
@@ -200,7 +200,7 @@ public class NormalCompletionOrderingTest extends CompletionSortingTestCase {
}
public void testLocalVarsOverMethods() {
checkPreferredItems(0, "value", "validate", "validateTree", "valueOf");
checkPreferredItems(1, "value", "valueOf");
}
public void testCurrentClassBest() {
@@ -281,12 +281,12 @@ public class NormalCompletionOrderingTest extends CompletionSortingTestCase {
public void testPreselectMostRelevantInTheMiddleAlpha() {
UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = true;
myFixture.addClass("package foo; public class Elxaaaaaaaaaaaaaaaaaaaa {}");
myFixture.addClass("package foo; public class ELXaaaaaaaaaaaaaaaaaaaa {}");
invokeCompletion(getTestName(false) + ".java");
myFixture.completeBasic();
LookupImpl lookup = getLookup();
assertPreferredItems(lookup.getList().getSelectedIndex());
assertEquals("Elxaaaaaaaaaaaaaaaaaaaa", lookup.getItems().get(0).getLookupString());
assertEquals("ELXaaaaaaaaaaaaaaaaaaaa", lookup.getItems().get(0).getLookupString());
assertEquals("ELXEMENT_A", lookup.getCurrentItem().getLookupString());
}
@@ -356,6 +356,19 @@ import java.lang.annotation.Target;
checkPreferredItems 0, 'TMetaAnno', 'Target', 'TreeSelectionMode', 'TLocalAnno'
}
public void testPreferApplicableAnnotationsMethod() throws Throwable {
myFixture.addClass '''
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target({ElementType.TYPE})
@interface TClassAnno {}
@Target({ElementType.METHOD})
@interface TMethodAnno {}'''
checkPreferredItems 0, 'TMethodAnno', 'TClassAnno'
}
public void testJComponentAddNewWithStats() throws Throwable {
final LookupImpl lookup = invokeCompletion("/../smartTypeSorting/JComponentAddNew.java");
assertPreferredItems(0, "FooBean3", "JComponent", "Component");
@@ -382,7 +395,7 @@ import java.lang.annotation.Target;
myFixture.addClass('public class fooAClass {}')
configureNoCompletion(getTestName(false) + ".java");
myFixture.complete(CompletionType.BASIC, 2);
assertPreferredItems(0, 'fooy', 'foox', 'fooAClass', 'fooBar');
assertPreferredItems(0, 'fooy', 'fooAClass', 'fooBar', 'foox');
}
public void testChangePreselectionOnSecondInvocation() {
@@ -486,4 +499,9 @@ import java.lang.annotation.Target;
assertPreferredItems 0, 'contains', 'containsAll'
}
public void testCommonPrefixMoreImportantThanKind() {
CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = CodeInsightSettings.NONE;
checkPreferredItems(0, 'PsiElement', 'psiElement')
}
}
@@ -21,7 +21,7 @@ public class SmartTypeCompletionOrderingTest extends CompletionSortingTestCase {
}
public void testJComponentAdd() throws Throwable {
checkPreferredItems(0, "name", "b", "foo", "fooBean239", "this", "getName");
checkPreferredItems(0, "name", "getName", "b", "foo", "fooBean239", "this");
}
public void testJComponentAddNew() throws Throwable {
@@ -161,7 +161,7 @@ public class SmartTypeCompletionOrderingTest extends CompletionSortingTestCase {
}
public void testPreferParametersToGetters() throws Throwable {
checkPreferredItems(0, "a", "getLastI");
checkPreferredItems(0, "a", "I._1", "valueOf", "getLastI");
}
public void testExpectedInterfaceShouldGoFirst() throws Throwable {
@@ -178,7 +178,7 @@ public class SmartTypeCompletionOrderingTest extends CompletionSortingTestCase {
}
public void testPreferNonRecursiveMethodParams() throws Throwable {
checkPreferredItems(0, "b", "s", "a", "hashCode");
checkPreferredItems(0, "b", "hashCode", "s", "a");
}
public void testPreferDelegatingMethodParams() throws Throwable {
@@ -222,7 +222,7 @@ public class SmartTypeCompletionOrderingTest extends CompletionSortingTestCase {
}
public void testFactoryMethodForDefaultType() throws Throwable {
checkPreferredItems(0, "create", "this", "map", "getClass");
checkPreferredItems(0, "create", "this", "getClass");
}
public void testLocalVarsBeforeClassLiterals() throws Throwable {
@@ -57,6 +57,10 @@ public class MoveMembersTest extends MultiFileTestCase {
doTest("pack1.A", "pack1.C", 0, 1, 2);
}
public void testParameterizedRefOn() throws Exception {
doTest("pack1.POne", "pack1.C", 1, 2);
}
public void testIDEADEV12448() throws Exception {
doTest("B", "A", false, 0);
}
@@ -55,10 +55,17 @@ public abstract class InjectedLanguageManager {
public abstract TextRange injectedToHost(@NotNull PsiElement injectedContext, @NotNull TextRange injectedTextRange);
public abstract int injectedToHost(@NotNull PsiElement injectedContext, int injectedOffset);
/** @see com.intellij.lang.injection.MultiHostInjector#MULTIHOST_INJECTOR_EP_NAME */
/**
* Test-only method.
* @see com.intellij.lang.injection.MultiHostInjector#MULTIHOST_INJECTOR_EP_NAME
*/
@Deprecated
public abstract void registerMultiHostInjector(@NotNull MultiHostInjector injector);
/** @see com.intellij.lang.injection.MultiHostInjector#MULTIHOST_INJECTOR_EP_NAME */
/**
* Test-only method.
* @see com.intellij.lang.injection.MultiHostInjector#MULTIHOST_INJECTOR_EP_NAME
*/
@Deprecated
public abstract boolean unregisterMultiHostInjector(@NotNull MultiHostInjector injector);
@@ -29,8 +29,15 @@ public class DocumentUtil {
private DocumentUtil() {
}
// TODO den add doc
/**
* Ensures that given task is executed when given document is at the given 'in bulk' mode.
*
* @param document target document
* @param executeInBulk <code>true</code> to force given document to be in bulk mode when given task is executed;
* <code>false</code> to force given document to be <b>not</b> in bulk mode when given task is executed
* @param task task to execute
*/
public static void executeInBulk(@NotNull Document document, final boolean executeInBulk, @NotNull Runnable task) {
if (!(document instanceof DocumentEx)) {
task.run();
@@ -15,13 +15,27 @@
*/
package com.intellij.psi.codeStyle.arrangement.settings;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.psi.codeStyle.arrangement.model.ArrangementSettingType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
/**
* Strategy which hints on what colors should be used at arrangement setting UI.
* Callback which allows to customize colors used at the arrangement UI on the basis of existing coloring scheme.
*
* @author Denis Zhdanov
* @since 10/23/12 11:53 PM
*/
public interface ArrangementColorsAware {
// TODO den implement
@Nullable
TextAttributesKey getTextKey(@NotNull ArrangementSettingType type, boolean selected);
@Nullable
TextAttributesKey getTextBackgroundKey(@NotNull ArrangementSettingType type, boolean selected);
@Nullable
Color getBorderColor(boolean selected);
}
@@ -1,46 +0,0 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.application.options.codeStyle.arrangement;
import com.intellij.ui.GroupedElementsRenderer;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
/**
* @author Denis Zhdanov
* @since 10/23/12 11:47 PM
*/
public abstract class AbstractArrangementColorsProvider implements ArrangementColorsProvider {
@NotNull private Color myNormalBorderColor;
@NotNull private Color mySelectedBorderColor;
@NotNull
public Color getBorderColor(boolean selected) {
return selected ? mySelectedBorderColor : myNormalBorderColor;
}
public void updateColors() {
myNormalBorderColor = UIUtil.getBorderColor();
Color selectionBorderColor = UIUtil.getTreeSelectionBorderColor();
if (selectionBorderColor == null) {
selectionBorderColor = GroupedElementsRenderer.SELECTED_FRAME_FOREGROUND;
}
mySelectedBorderColor = selectionBorderColor;
}
}
@@ -25,18 +25,13 @@ import java.awt.*;
* @since 10/23/12 11:46 PM
*/
public interface ArrangementColorsProvider {
@NotNull
Color getBorderColor(boolean selected);
@NotNull
Color getTextColor(@NotNull ArrangementSettingType type);
Color getTextColor(@NotNull ArrangementSettingType type, boolean selected);
@NotNull
Color getTextBackgroundColor(@NotNull ArrangementSettingType type);
@NotNull
Color getSelectedTextColor(@NotNull ArrangementSettingType type);
@NotNull
Color getSelectedTextBackgroundColor(@NotNull ArrangementSettingType type);
Color getTextBackgroundColor(@NotNull ArrangementSettingType type, boolean selected);
}
@@ -0,0 +1,155 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.application.options.codeStyle.arrangement;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.psi.codeStyle.arrangement.model.ArrangementSettingType;
import com.intellij.psi.codeStyle.arrangement.settings.ArrangementColorsAware;
import com.intellij.ui.GroupedElementsRenderer;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.util.EnumMap;
import java.util.Map;
/**
* @author Denis Zhdanov
* @since 10/24/12 4:25 PM
*/
public class ArrangementColorsProviderImpl implements ArrangementColorsProvider {
@Nullable private final ArrangementColorsAware myColorsAware;
@NotNull private final Map<ArrangementSettingType, Color> myTextColors
= new EnumMap<ArrangementSettingType, Color>(ArrangementSettingType.class);
@NotNull private final Map<ArrangementSettingType, Color> myBackgroundColors
= new EnumMap<ArrangementSettingType, Color>(ArrangementSettingType.class);
@NotNull private final Map<ArrangementSettingType, Color> mySelectedTextColors
= new EnumMap<ArrangementSettingType, Color>(ArrangementSettingType.class);
@NotNull private final Map<ArrangementSettingType, Color> mySelectedBackgroundColors
= new EnumMap<ArrangementSettingType, Color>(ArrangementSettingType.class);
@NotNull private Color myBorderColor;
@NotNull private Color mySelectedBorderColor;
public ArrangementColorsProviderImpl(@Nullable ArrangementColorsAware colorsAware) {
myColorsAware = colorsAware;
applyDefaultColors();
if (colorsAware != null) {
applyCustomColors(colorsAware);
}
}
@NotNull
@Override
public Color getBorderColor(boolean selected) {
return selected ? myBorderColor : mySelectedBorderColor;
}
@NotNull
@Override
public Color getTextColor(@NotNull ArrangementSettingType type, boolean selected) {
return selected ? mySelectedTextColors.get(type) : myTextColors.get(type);
}
@NotNull
@Override
public Color getTextBackgroundColor(@NotNull ArrangementSettingType type, boolean selected) {
return selected ? mySelectedBackgroundColors.get(type) : myBackgroundColors.get(type);
}
/**
* Asks the implementation to ensure that it uses the most up-to-date colors.
* <p/>
* I.e. this method is assumed to be called when color settings has been changed and gives a chance to reflect the changes
* accordingly.
*/
public void refresh() {
if (myColorsAware == null) {
return;
}
myTextColors.clear();
myBackgroundColors.clear();
mySelectedTextColors.clear();
mySelectedBackgroundColors.clear();
applyDefaultColors();
applyCustomColors(myColorsAware);
}
private void applyDefaultColors() {
Color textColor = UIUtil.getTreeTextForeground();
Color selectedTextColor = UIUtil.getTreeSelectionForeground();
Color backgroundColor = UIUtil.getPanelBackground();
Color selectedBackgroundColor = UIUtil.getTreeSelectionBackground();
for (ArrangementSettingType type : ArrangementSettingType.values()) {
myTextColors.put(type, textColor);
mySelectedTextColors.put(type, selectedTextColor);
myBackgroundColors.put(type, backgroundColor);
mySelectedBackgroundColors.put(type, selectedBackgroundColor);
}
myBorderColor = UIUtil.getBorderColor();
Color selectionBorderColor = UIUtil.getTreeSelectionBorderColor();
if (selectionBorderColor == null) {
selectionBorderColor = GroupedElementsRenderer.SELECTED_FRAME_FOREGROUND;
}
mySelectedBorderColor = selectionBorderColor;
}
private void applyCustomColors(@NotNull ArrangementColorsAware colorsAware) {
EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
for (ArrangementSettingType type : ArrangementSettingType.values()) {
applyColorIfPossible(scheme, colorsAware.getTextKey(type, false), type, myTextColors);
applyColorIfPossible(scheme, colorsAware.getTextKey(type, true), type, mySelectedTextColors);
applyColorIfPossible(scheme, colorsAware.getTextBackgroundKey(type, false), type, myBackgroundColors);
applyColorIfPossible(scheme, colorsAware.getTextBackgroundKey(type, true), type, mySelectedBackgroundColors);
}
Color borderColor = colorsAware.getBorderColor(false);
if (borderColor != null) {
myBorderColor = borderColor;
}
Color selectedBorderColor = colorsAware.getBorderColor(true);
if (selectedBorderColor != null) {
mySelectedBorderColor = selectedBorderColor;
}
}
private static void applyColorIfPossible(@NotNull EditorColorsScheme scheme,
@Nullable TextAttributesKey key,
@NotNull ArrangementSettingType type,
@NotNull Map<ArrangementSettingType, Color> holder)
{
if (key == null) {
return;
}
TextAttributes attributes = scheme.getAttributes(key);
if (attributes == null) {
return;
}
Color color = attributes.getForegroundColor();
if (color != null) {
holder.put(type, color);
}
}
}
@@ -1,76 +0,0 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.application.options.codeStyle.arrangement;
import com.intellij.ide.ui.LafManager;
import com.intellij.ide.ui.LafManagerListener;
import com.intellij.ui.GroupedElementsRenderer;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
/**
* @author Denis Zhdanov
* @since 9/6/12 2:30 PM
*/
public class ArrangementColorsService {
@NotNull private Color myNormalTextColor;
@NotNull private Color mySelectedTextColor;
@NotNull private Color myNormalBackgroundColor;
@NotNull private Color mySelectedBackgroundColor;
@NotNull private Color myNormalBorderColor;
@NotNull private Color mySelectedBorderColor;
public ArrangementColorsService(@NotNull LafManager lafManager) {
lafManager.addLafManagerListener(new LafManagerListener() {
@Override
public void lookAndFeelChanged(LafManager source) {
updateColors();
}
});
updateColors();
}
@NotNull
public Color getTextColor(boolean selected) {
return selected ? mySelectedTextColor : myNormalTextColor;
}
@NotNull
public Color getBackgroundColor(boolean selected) {
return selected ? mySelectedBackgroundColor : myNormalBackgroundColor;
}
@NotNull
public Color getBorderColor(boolean selected) {
return selected ? mySelectedBorderColor : myNormalBorderColor;
}
private void updateColors() {
myNormalTextColor = UIUtil.getTreeTextForeground();
mySelectedTextColor = UIUtil.getTreeSelectionForeground();
myNormalBackgroundColor = UIUtil.getPanelBackground();
mySelectedBackgroundColor = UIUtil.getTreeSelectionBackground();
myNormalBorderColor = UIUtil.getBorderColor();
Color selectionBorderColor = UIUtil.getTreeSelectionBorderColor();
if (selectionBorderColor == null) {
selectionBorderColor = GroupedElementsRenderer.SELECTED_FRAME_FOREGROUND;
}
mySelectedBorderColor = selectionBorderColor;
}
}
@@ -49,10 +49,14 @@ public class ArrangementRuleEditor extends JPanel {
new HashMap<Object, ArrangementAtomMatchNodeComponent>();
@NotNull private final ArrangementStandardSettingsAware myFilter;
@NotNull private final ArrangementColorsProvider myColorsProvider;
@Nullable private ArrangementRuleEditingModel myModel;
public ArrangementRuleEditor(@NotNull ArrangementStandardSettingsAware filter, @NotNull ArrangementNodeDisplayManager displayManager) {
public ArrangementRuleEditor(@NotNull ArrangementStandardSettingsAware filter,
@NotNull ArrangementColorsProvider provider,
@NotNull ArrangementNodeDisplayManager displayManager) {
myFilter = filter;
myColorsProvider = provider;
init(displayManager);
addMouseListener(new MouseAdapter() {
@Override
@@ -82,7 +86,7 @@ public class ArrangementRuleEditor extends JPanel {
JPanel valuesPanel = new MultiRowFlowPanel(FlowLayout.LEFT, 8, 5);
for (Object value : manager.sort(values)) {
ArrangementAtomMatchNodeComponent component =
new ArrangementAtomMatchNodeComponent(manager, new ArrangementAtomMatchCondition(key, value), null);
new ArrangementAtomMatchNodeComponent(manager, myColorsProvider, new ArrangementAtomMatchCondition(key, value), null);
myComponents.put(value, component);
valuesPanel.add(component.getUiComponent());
}
@@ -42,7 +42,6 @@ import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.plaf.TreeUI;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.ActionEvent;
@@ -92,10 +91,11 @@ public class ArrangementRuleTree {
public ArrangementRuleTree(@Nullable StdArrangementSettings settings,
@NotNull List<Set<ArrangementMatchCondition>> uiGroupingRules,
@NotNull ArrangementNodeDisplayManager displayManager,
@NotNull ArrangementColorsProvider colorsProvider,
@NotNull ArrangementStandardSettingsAware settingsFilter)
{
myUiGroupingRules = uiGroupingRules;
myFactory = new ArrangementMatchNodeComponentFactory(displayManager, new Runnable() {
myFactory = new ArrangementMatchNodeComponentFactory(displayManager, colorsProvider, new Runnable() {
@Override
public void run() {
notifySelectionListeners();
@@ -32,10 +32,7 @@ import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.arrangement.Rearranger;
import com.intellij.psi.codeStyle.arrangement.StdArrangementSettings;
import com.intellij.psi.codeStyle.arrangement.model.ArrangementMatchCondition;
import com.intellij.psi.codeStyle.arrangement.settings.ArrangementConditionsGrouper;
import com.intellij.psi.codeStyle.arrangement.settings.ArrangementStandardSettingsAware;
import com.intellij.psi.codeStyle.arrangement.settings.ArrangementStandardSettingsRepresentationAware;
import com.intellij.psi.codeStyle.arrangement.settings.DefaultArrangementSettingsRepresentationManager;
import com.intellij.psi.codeStyle.arrangement.settings.*;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.SideBorder;
import com.intellij.ui.components.JBScrollPane;
@@ -94,6 +91,13 @@ public abstract class ArrangementSettingsPanel extends CodeStyleAbstractPanel {
final ArrangementNodeDisplayManager displayManager = new ArrangementNodeDisplayManager(
mySettingsAware, representationManager, groupingRules
);
final ArrangementColorsProvider colorsProvider;
if (rearranger instanceof ArrangementColorsAware) {
colorsProvider = new ArrangementColorsProviderImpl((ArrangementColorsAware)rearranger);
}
else {
colorsProvider = new ArrangementColorsProviderImpl(null);
}
final ActionManager actionManager = ActionManager.getInstance();
final ActionGroup actionGroup = (ActionGroup)actionManager.getAction(ArrangementConstants.ACTION_GROUP_RULE_EDITOR_TOOL_WINDOW);
@@ -103,7 +107,7 @@ public abstract class ArrangementSettingsPanel extends CodeStyleAbstractPanel {
toolbarControl.setBorder(IdeBorderFactory.createBorder(SideBorder.LEFT | SideBorder.TOP | SideBorder.RIGHT));
myContent.add(toolbarControl, new GridBag().weightx(1).fillCellHorizontally().coverLine());
myRuleTree = new ArrangementRuleTree(getSettings(settings), groupingRules, displayManager, mySettingsAware);
myRuleTree = new ArrangementRuleTree(getSettings(settings), groupingRules, displayManager, colorsProvider, mySettingsAware);
final Tree treeComponent = myRuleTree.getTreeComponent();
actionToolbar.setTargetComponent(treeComponent);
JBScrollPane scrollPane = new JBScrollPane(treeComponent);
@@ -113,7 +117,7 @@ public abstract class ArrangementSettingsPanel extends CodeStyleAbstractPanel {
);
final JXTaskPane editorPane = new JXTaskPane(ApplicationBundle.message("arrangement.title.editor"));
final ArrangementRuleEditor ruleEditor = new ArrangementRuleEditor(mySettingsAware, displayManager);
final ArrangementRuleEditor ruleEditor = new ArrangementRuleEditor(mySettingsAware, colorsProvider, displayManager);
ruleEditor.applyBackground(treeComponent.getBackground());
editorPane.getContentPane().setBackground(treeComponent.getBackground());
editorPane.add(ruleEditor);
@@ -1,67 +0,0 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.application.options.codeStyle.arrangement;
import com.intellij.psi.codeStyle.arrangement.model.ArrangementSettingType;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
/**
* @author Denis Zhdanov
* @since 10/23/12 11:50 PM
*/
public class DefaultArrangementColorsProvider extends AbstractArrangementColorsProvider {
@NotNull private Color myNormalTextColor;
@NotNull private Color mySelectedTextColor;
@NotNull private Color myNormalBackgroundColor;
@NotNull private Color mySelectedBackgroundColor;
@NotNull
@Override
public Color getTextColor(@NotNull ArrangementSettingType type) {
return myNormalTextColor;
}
@NotNull
@Override
public Color getTextBackgroundColor(@NotNull ArrangementSettingType type) {
return myNormalBackgroundColor;
}
@NotNull
@Override
public Color getSelectedTextColor(@NotNull ArrangementSettingType type) {
return mySelectedTextColor;
}
@NotNull
@Override
public Color getSelectedTextBackgroundColor(@NotNull ArrangementSettingType type) {
return mySelectedBackgroundColor;
}
@Override
public void updateColors() {
super.updateColors();
myNormalTextColor = UIUtil.getTreeTextForeground();
mySelectedTextColor = UIUtil.getTreeSelectionForeground();
myNormalBackgroundColor = UIUtil.getPanelBackground();
mySelectedBackgroundColor = UIUtil.getTreeSelectionBackground();
}
}
@@ -43,8 +43,6 @@ public class ArrangementAtomMatchNodeComponent implements ArrangementMatchNodeCo
public static final int VERTICAL_PADDING = 2;
public static final int HORIZONTAL_PADDING = 8;
@NotNull private final ArrangementColorsService myColorsService = ServiceManager.getService(ArrangementColorsService.class);
@NotNull private final JPanel myRenderer = new JPanel(new GridBagLayout()) {
@Override
public void paint(Graphics g) {
@@ -77,11 +75,13 @@ public class ArrangementAtomMatchNodeComponent implements ArrangementMatchNodeCo
return myLabelSize == null ? super.getPreferredSize() : myLabelSize;
}
};
@NotNull private final RoundedLineBorder myBorder;
@NotNull private final ArrangementAtomMatchCondition myCondition;
@Nullable private final ActionButton myCloseButton;
@Nullable private final Runnable myCloseCallback;
@NotNull private final ArrangementColorsProvider myColorsProvider;
@NotNull private final RoundedLineBorder myBorder;
@NotNull private final ArrangementAtomMatchCondition myCondition;
@Nullable private final ActionButton myCloseButton;
@Nullable private final Runnable myCloseCallback;
@NotNull private Color myBackgroundColor;
@@ -93,9 +93,11 @@ public class ArrangementAtomMatchNodeComponent implements ArrangementMatchNodeCo
private boolean myCloseButtonHovered;
public ArrangementAtomMatchNodeComponent(@NotNull ArrangementNodeDisplayManager manager,
@NotNull ArrangementColorsProvider colorsProvider,
@NotNull ArrangementAtomMatchCondition condition,
@Nullable Runnable closeCallback)
{
myColorsProvider = colorsProvider;
myCondition = condition;
myCloseCallback = closeCallback;
myLabel.setHorizontalAlignment(SwingConstants.CENTER);
@@ -186,9 +188,9 @@ public class ArrangementAtomMatchNodeComponent implements ArrangementMatchNodeCo
* @param selected flag that indicates if current component should be drawn as 'selected'
*/
public void setSelected(boolean selected) {
myLabel.setForeground(myColorsService.getTextColor(selected));
myBorder.setColor(myColorsService.getBorderColor(selected));
myBackgroundColor = myColorsService.getBackgroundColor(selected);
myLabel.setForeground(myColorsProvider.getTextColor(myCondition.getType(), selected));
myBorder.setColor(myColorsProvider.getBorderColor(selected));
myBackgroundColor = myColorsProvider.getTextBackgroundColor(myCondition.getType(), selected);
}
public boolean isEnabled() {
@@ -15,10 +15,8 @@
*/
package com.intellij.application.options.codeStyle.arrangement.node.match;
import com.intellij.application.options.codeStyle.arrangement.ArrangementColorsService;
import com.intellij.application.options.codeStyle.arrangement.ArrangementConfigUtil;
import com.intellij.application.options.codeStyle.arrangement.ArrangementNodeDisplayManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.codeStyle.arrangement.model.ArrangementAtomMatchCondition;
import com.intellij.psi.codeStyle.arrangement.model.ArrangementMatchCondition;
@@ -40,12 +38,10 @@ public class ArrangementGroupingMatchNodeComponent extends JPanel implements Arr
private static final int TOP_INSET = 3;
@NotNull private final ArrangementColorsService myColorsService = ServiceManager.getService(ArrangementColorsService.class);
@NotNull private final ArrangementAtomMatchCondition myCondition;
@Nullable private Rectangle myScreenBounds;
@NotNull private Dimension myPreferredSize;
private boolean mySelected;
public ArrangementGroupingMatchNodeComponent(@NotNull ArrangementNodeDisplayManager manager,
@NotNull ArrangementAtomMatchCondition condition)
@@ -104,7 +100,6 @@ public class ArrangementGroupingMatchNodeComponent extends JPanel implements Arr
@Override
public void setSelected(boolean selected) {
mySelected = selected;
}
@Nullable
@@ -126,10 +121,6 @@ public class ArrangementGroupingMatchNodeComponent extends JPanel implements Arr
int y = TOP_INSET;
g.drawLine(cornerX, y, bounds.width, y);
g.drawLine(cornerX, y, cornerX, y + bounds.height);
if (mySelected) {
g.setColor(myColorsService.getBackgroundColor(true));
g.fillRect(cornerX + 1, y + 1, bounds.width - 1, bounds.height - 1);
}
Point point = ArrangementConfigUtil.getLocationOnScreen(this);
if (point != null) {
@@ -15,6 +15,7 @@
*/
package com.intellij.application.options.codeStyle.arrangement.node.match;
import com.intellij.application.options.codeStyle.arrangement.ArrangementColorsProvider;
import com.intellij.application.options.codeStyle.arrangement.ArrangementNodeDisplayManager;
import com.intellij.application.options.codeStyle.arrangement.ArrangementRuleEditingModel;
import com.intellij.openapi.util.Ref;
@@ -37,13 +38,15 @@ public class ArrangementMatchNodeComponentFactory {
@NotNull private final Set<ArrangementMatchCondition> myGroupingConditions = ContainerUtilRt.newHashSet();
@NotNull private final ArrangementNodeDisplayManager myDisplayManager;
@NotNull private final ArrangementColorsProvider myColorsProvider;
@NotNull private final Runnable myRemoveConditionCallback;
public ArrangementMatchNodeComponentFactory(@NotNull ArrangementNodeDisplayManager manager,
@NotNull Runnable removeConditionCallback,
@NotNull ArrangementColorsProvider provider, @NotNull Runnable removeConditionCallback,
@NotNull List<Set<ArrangementMatchCondition>> groupingRules)
{
myDisplayManager = manager;
myColorsProvider = provider;
myRemoveConditionCallback = removeConditionCallback;
for (Set<ArrangementMatchCondition> rules : groupingRules) {
myGroupingConditions.addAll(rules);
@@ -63,7 +66,9 @@ public class ArrangementMatchNodeComponentFactory {
component = new ArrangementGroupingMatchNodeComponent(myDisplayManager, condition);
}
else {
component = new ArrangementAtomMatchNodeComponent(myDisplayManager, condition, prepareRemoveCallback(condition, model));
component = new ArrangementAtomMatchNodeComponent(
myDisplayManager, myColorsProvider, condition, prepareRemoveCallback(condition, model)
);
}
ref.set(component);
}
@@ -236,7 +236,7 @@ public class CompletionLookupArranger extends LookupArranger {
private static void ensureEverythingVisibleAdded(LookupImpl lookup, final LinkedHashSet<LookupElement> model, Iterator<LookupElement> byRelevance) {
JList list = lookup.getList();
final boolean testMode = ApplicationManager.getApplication().isUnitTestMode();
final int limit = Math.max(list.getLastVisibleIndex(), model.size()) + list.getVisibleRowCount() * 3;
final int limit = Math.max(list.getLastVisibleIndex(), model.size()) + ourUISettings.MAX_LOOKUP_LIST_HEIGHT * 3;
addSomeItems(model, byRelevance, new Condition<LookupElement>() {
@Override
public boolean value(LookupElement lastAdded) {
@@ -243,7 +243,7 @@ public class CompletionServiceImpl extends CompletionService{
for (final Weigher weigher : WeighingService.getWeighers(CompletionService.RELEVANCE_KEY)) {
final String id = weigher.toString();
if ("prefix".equals(id)) {
sorter = sorter.withClassifier(CompletionSorterImpl.weighingFactory(new PrefixMatchingClassifier(location)));
sorter = sorter.withClassifier(CompletionSorterImpl.weighingFactory(new RealPrefixMatchingWeigher(location)));
}
else if ("stats".equals(id)) {
sorter = sorter.withClassifier(CompletionSorterImpl.weighingFactory(new StatisticsWeigher.LookupStatisticsWeigher(location)));
@@ -276,25 +276,11 @@ public class CompletionServiceImpl extends CompletionService{
return new CompletionSorterImpl(new ArrayList<ClassifierFactory<LookupElement>>());
}
private static class PreferStartMatching extends LookupElementWeigher {
private final CompletionLocation myLocation;
public PreferStartMatching(CompletionLocation location) {
super("middleMatching", false, true);
myLocation = location;
}
@Override
public Comparable weigh(@NotNull LookupElement element) {
return !isStartMatch(element, myLocation.getCompletionParameters().getLookup());
}
}
public static boolean isStartMatch(LookupElement element, Lookup lookup) {
return getItemMatcher(element, lookup).isStartMatch(element);
}
private static PrefixMatcher getItemMatcher(LookupElement element, Lookup lookup) {
static PrefixMatcher getItemMatcher(LookupElement element, Lookup lookup) {
PrefixMatcher itemMatcher = lookup.itemMatcher(element);
String pattern = lookup.itemPattern(element);
if (!pattern.equals(itemMatcher.getPrefix())) {
@@ -302,25 +288,4 @@ public class CompletionServiceImpl extends CompletionService{
}
return itemMatcher;
}
private static class PrefixMatchingClassifier extends LookupElementWeigher {
private final CompletionLocation myLocation;
public PrefixMatchingClassifier(CompletionLocation location) {
super("prefix", false, true);
myLocation = location;
}
@Override
public Comparable weigh(@NotNull LookupElement element) {
final PrefixMatcher matcher = getItemMatcher(element, myLocation.getCompletionParameters().getLookup());
int max = Integer.MIN_VALUE;
for (String lookupString : element.getAllLookupStrings()) {
max = Math.max(max, matcher.matchingDegree(lookupString));
}
return -max;
}
}
}
@@ -0,0 +1,23 @@
package com.intellij.codeInsight.completion.impl;
import com.intellij.codeInsight.completion.CompletionLocation;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementWeigher;
import org.jetbrains.annotations.NotNull;
/**
* @author Peter
*/
public class PreferStartMatching extends LookupElementWeigher {
private final CompletionLocation myLocation;
public PreferStartMatching(CompletionLocation location) {
super("middleMatching", false, true);
myLocation = location;
}
@Override
public Comparable weigh(@NotNull LookupElement element) {
return !CompletionServiceImpl.isStartMatch(element, myLocation.getCompletionParameters().getLookup());
}
}
@@ -0,0 +1,31 @@
package com.intellij.codeInsight.completion.impl;
import com.intellij.codeInsight.completion.CompletionLocation;
import com.intellij.codeInsight.completion.PrefixMatcher;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementWeigher;
import org.jetbrains.annotations.NotNull;
/**
* @author Peter
*/
public class RealPrefixMatchingWeigher extends LookupElementWeigher {
private final CompletionLocation myLocation;
public RealPrefixMatchingWeigher(CompletionLocation location) {
super("prefix", false, true);
myLocation = location;
}
@Override
public Comparable weigh(@NotNull LookupElement element) {
final PrefixMatcher matcher = CompletionServiceImpl.getItemMatcher(element, myLocation.getCompletionParameters().getLookup());
int max = Integer.MIN_VALUE;
for (String lookupString : element.getAllLookupStrings()) {
max = Math.max(max, matcher.matchingDegree(lookupString));
}
return -max;
}
}
@@ -28,6 +28,7 @@ import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.intellij.openapi.editor.actionSystem.EditorActionManager;
import com.intellij.openapi.editor.actionSystem.EditorTextInsertHandler;
import com.intellij.openapi.editor.ex.DocumentEx;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.Extensions;
@@ -39,6 +40,7 @@ import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.util.DocumentUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Producer;
import com.intellij.util.containers.HashMap;
@@ -365,15 +367,23 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
}
}
private static void reformatBlock(Project project, Editor editor, int startOffset, int endOffset) {
private static void reformatBlock(final Project project, final Editor editor, final int startOffset, final int endOffset) {
PsiDocumentManager.getInstance(project).commitAllDocuments();
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
Runnable task = new Runnable() {
@Override
public void run() {
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
try {
CodeStyleManager.getInstance(project).reformatRange(file, startOffset, endOffset, true);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
};
try {
CodeStyleManager.getInstance(project).reformatRange(file, startOffset, endOffset, true);
}
catch (IncorrectOperationException e) {
LOG.error(e);
if (endOffset - startOffset > 1000) {
DocumentUtil.executeInBulk(editor.getDocument(), true, task);
}
}
@@ -321,8 +321,9 @@ class FormatProcessor {
* <code>false</code> otherwise
*/
@SuppressWarnings({"deprecation"})
private boolean applyChangesAtBulkMode(final List<LeafBlockWrapper> blocksToModify, final FormattingModel model,
@NotNull CommonCodeStyleSettings.IndentOptions indentOption)
private boolean applyChangesAtRewriteMode(@NotNull final List<LeafBlockWrapper> blocksToModify,
@NotNull final FormattingModel model,
@NotNull CommonCodeStyleSettings.IndentOptions indentOption)
{
FormattingDocumentModel documentModel = model.getDocumentModel();
Document document = documentModel.getDocument();
@@ -366,14 +367,13 @@ class FormatProcessor {
@Nullable
private static DocumentEx getAffectedDocument(final FormattingModel model) {
if (model instanceof DocumentBasedFormattingModel) {
final Document document = ((DocumentBasedFormattingModel)model).getDocument();
if (document instanceof DocumentEx) return (DocumentEx)document;
}/* else if (false) { // till issue with persistent range markers dropped fixed
Document document = model.getDocumentModel().getDocument();
if (document instanceof DocumentEx) return (DocumentEx)document;
}*/
return null;
final Document document = model.getDocumentModel().getDocument();
if (document instanceof DocumentEx) {
return (DocumentEx)document;
}
else {
return null;
}
}
private static int replaceWhiteSpace(final FormattingModel model,
@@ -1397,7 +1397,7 @@ class FormatProcessor {
myResetBulkUpdateState = true;
}
if (blocksToModifyCount > BULK_REPLACE_OPTIMIZATION_CRITERIA
&& applyChangesAtBulkMode(myBlocksToModify, myModel, myDefaultIndentOption))
&& applyChangesAtRewriteMode(myBlocksToModify, myModel, myDefaultIndentOption))
{
setDone(true);
}
@@ -29,6 +29,7 @@ import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.io.FileUtil;
@@ -36,9 +37,7 @@ import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.ex.StatusBarEx;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import com.intellij.psi.*;
import com.intellij.util.ArrayUtil;
import com.intellij.util.LogicalRoot;
import com.intellij.util.LogicalRootsManager;
@@ -58,7 +57,7 @@ import java.util.zip.ZipEntry;
/**
* @author Alexey
*/
public class CopyReferenceAction extends AnAction {
public class CopyReferenceAction extends DumbAwareAction {
public static final DataFlavor ourFlavor;
static {
try {
@@ -141,9 +140,9 @@ public class CopyReferenceAction extends AnAction {
if (!doCopy(element, project, editor) && editor != null) {
Document document = editor.getDocument();
VirtualFile file = FileDocumentManager.getInstance().getFile(document);
PsiFile file = PsiDocumentManager.getInstance(project).getCachedPsiFile(document);
if (file != null) {
String toCopy = FileUtil.toSystemDependentName(file.getPath()) + ":" + (editor.getCaretModel().getLogicalPosition().line + 1);
String toCopy = getFileFqn(file) + ":" + (editor.getCaretModel().getLogicalPosition().line + 1);
CopyPasteManager.getInstance().setContents(new StringSelection(toCopy));
setStatusBarText(project, toCopy + " has been copied");
}
@@ -181,6 +180,13 @@ public class CopyReferenceAction extends AnAction {
if (element == null) {
element = LangDataKeys.PSI_ELEMENT.getData(dataContext);
}
if (element == null && editor == null) {
VirtualFile virtualFile = PlatformDataKeys.VIRTUAL_FILE.getData(dataContext);
Project project = PlatformDataKeys.PROJECT.getData(dataContext);
if (virtualFile != null && project != null) {
element = PsiManager.getInstance(project).findFile(virtualFile);
}
}
if (element instanceof PsiFile && !((PsiFile)element).getViewProvider().isPhysical()) {
return null;
}
@@ -65,6 +65,7 @@ import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
@@ -288,7 +289,7 @@ public abstract class AbstractTreeClassChooserDialog<T extends PsiNamedElement>
}
private Set<Object> doFilter(Set<Object> elements) {
Set<Object> result = new HashSet<Object>();
Set<Object> result = new LinkedHashSet<Object>();
for (Object o : elements) {
if (myElementClass.isInstance(o) && getFilter().isAccepted((T)o)) {
result.add(o);
@@ -70,8 +70,8 @@ public class ANSIColoredConsoleColorsPage implements ColorSettingsPage, DisplayP
ADDITIONAL_HIGHLIGHT_DESCRIPTORS.put("stdout", ConsoleViewContentType.NORMAL_OUTPUT_KEY);
ADDITIONAL_HIGHLIGHT_DESCRIPTORS.put("stdin", ConsoleViewContentType.USER_INPUT_KEY);
ADDITIONAL_HIGHLIGHT_DESCRIPTORS.put("stderr", ConsoleViewContentType.ERROR_OUTPUT_KEY);
ADDITIONAL_HIGHLIGHT_DESCRIPTORS.put("logError", ConsoleViewContentType.LOG_WARNING_OUTPUT_KEY);
ADDITIONAL_HIGHLIGHT_DESCRIPTORS.put("logWarning", ConsoleViewContentType.LOG_ERROR_OUTPUT_KEY);
ADDITIONAL_HIGHLIGHT_DESCRIPTORS.put("logError", ConsoleViewContentType.LOG_ERROR_OUTPUT_KEY);
ADDITIONAL_HIGHLIGHT_DESCRIPTORS.put("logWarning", ConsoleViewContentType.LOG_WARNING_OUTPUT_KEY);
ADDITIONAL_HIGHLIGHT_DESCRIPTORS.put("logExpired", ConsoleViewContentType.LOG_EXPIRED_ENTRY);
ADDITIONAL_HIGHLIGHT_DESCRIPTORS.put("red", ConsoleHighlighter.RED);
@@ -56,24 +56,49 @@ public abstract class InjectedLanguageBlockBuilder {
final Ref<TextRange> injectedRangeInsideHost = new Ref<TextRange>();
final Ref<Integer> prefixLength = new Ref<Integer>();
final Ref<Integer> suffixLength = new Ref<Integer>();
final Ref<ASTNode> injectionHostToUse = new Ref<ASTNode>(injectionHost);
final PsiLanguageInjectionHost.InjectedPsiVisitor injectedPsiVisitor = new PsiLanguageInjectionHost.InjectedPsiVisitor() {
@Override
public void visit(@NotNull final PsiFile injectedPsi, @NotNull final List<PsiLanguageInjectionHost.Shred> places) {
if (places.size() == 1) {
final PsiLanguageInjectionHost.Shred shred = places.get(0);
final TextRange textRange = shred.getRangeInsideHost();
String childText;
if (places.size() != 1) {
return;
}
final PsiLanguageInjectionHost.Shred shred = places.get(0);
TextRange textRange = shred.getRangeInsideHost();
PsiLanguageInjectionHost shredHost = shred.getHost();
if (shredHost == null) {
return;
}
ASTNode node = shredHost.getNode();
if (node == null) {
return;
}
if (node != injectionHost) {
int shift = 0;
boolean canProcess = false;
for (ASTNode n = injectionHost.getTreeParent(), prev = injectionHost; n != null; prev = n, n = n.getTreeParent()) {
shift += n.getStartOffset() - prev.getStartOffset();
if (n == node) {
textRange = textRange.shiftRight(shift);
canProcess = true;
break;
}
}
if (!canProcess) {
return;
}
}
String childText;
if ((injectionHost.getTextLength() == textRange.getEndOffset() && textRange.getStartOffset() == 0) ||
(canProcessFragment((childText = injectionHost.getText()).substring(0, textRange.getStartOffset()), injectionHost) &&
canProcessFragment(childText.substring(textRange.getEndOffset()), injectionHost))) {
injectedFile[0] = injectedPsi;
injectedRangeInsideHost.set(textRange);
prefixLength.set(shred.getPrefix() != null ? shred.getPrefix().length() : 0);
suffixLength.set(shred.getSuffix() != null ? shred.getSuffix().length() : 0);
prefixLength.set(shred.getPrefix().length());
suffixLength.set(shred.getSuffix().length());
}
}
}
};
InjectedLanguageUtil.enumerate(injectionHost.getPsi(), injectedPsiVisitor);
@@ -85,19 +110,19 @@ public abstract class InjectedLanguageBlockBuilder {
if (builder != null) {
final int startOffset = injectedRangeInsideHost.get().getStartOffset();
final int endOffset = injectedRangeInsideHost.get().getEndOffset();
TextRange range = injectionHost.getTextRange();
TextRange range = injectionHostToUse.get().getTextRange();
int childOffset = range.getStartOffset();
if (startOffset != 0) {
final ASTNode leaf = injectionHost.findLeafElementAt(startOffset - 1);
final ASTNode leaf = injectionHostToUse.get().findLeafElementAt(startOffset - 1);
result.add(createBlockBeforeInjection(leaf, wrap, alignment, indent, new TextRange(childOffset, childOffset + startOffset)));
}
addInjectedLanguageBlockWrapper(result, injectedFile[0].getNode(), indent, childOffset + startOffset,
new TextRange(prefixLength.get(), injectedFile[0].getTextLength() - suffixLength.get()));
if (endOffset != injectionHost.getTextLength()) {
final ASTNode leaf = injectionHost.findLeafElementAt(endOffset);
if (endOffset != injectionHostToUse.get().getTextLength()) {
final ASTNode leaf = injectionHostToUse.get().findLeafElementAt(endOffset);
result.add(createBlockAfterInjection(leaf, wrap, alignment, indent, new TextRange(childOffset + endOffset, range.getEndOffset())));
}
return true;
@@ -88,6 +88,9 @@ public class JBLabel extends JLabel implements AnchorableComponent {
@Override
public Color getForeground() {
if (!isEnabled()) {
return UIUtil.getLabelDisabledForeground();
}
if (myFontColor != null) {
return UIUtil.getLabelFontColor(myFontColor);
}
@@ -73,7 +73,7 @@ import java.util.Set;
public class ActionMacroManager implements ExportableApplicationComponent, NamedJDOMExternalizable {
private static final Logger LOG = Logger.getInstance("#com.intellij.ide.actionMacro.ActionMacroManager");
private static final String TYPING_SAMPLE = "WWWWWWWWWWWWWWWWWWWWWWWW";
private static final String TYPING_SAMPLE = "WWWWWWWWWWWWWWWWWWWW";
private static final String RECORDED = "Recorded: ";
private boolean myIsRecording;
@@ -91,7 +91,6 @@ public class ActionMacroManager implements ExportableApplicationComponent, Named
private ActionMacroManager.Widget myWidget;
private String myLastTyping = new String();
private boolean myLastWasTyping;
public ActionMacroManager(ActionManagerEx actionManagerEx) {
myActionManager = actionManagerEx;
@@ -231,7 +230,7 @@ public class ActionMacroManager implements ExportableApplicationComponent, Named
final NonOpaquePanel top = new NonOpaquePanel(new BorderLayout());
top.add(tb.getComponent(), BorderLayout.WEST);
myText = new JLabel(TYPING_SAMPLE, SwingConstants.LEFT);
myText = new JLabel(RECORDED + "..." + TYPING_SAMPLE, SwingConstants.LEFT);
final Dimension preferredSize = myText.getPreferredSize();
myText.setPreferredSize(preferredSize);
myText.setText("Macro recording started...");
@@ -587,23 +586,19 @@ public class ActionMacroManager implements ExportableApplicationComponent, Named
private void notifyUser(String text, boolean typing) {
String actualText = text;
if (typing && myLastWasTyping) {
int maxLength = TYPING_SAMPLE.length() + RECORDED.length();
if (typing) {
int maxLength = TYPING_SAMPLE.length();
myLastTyping += text;
if (myLastTyping.length() > maxLength) {
myLastTyping = myLastTyping.substring(myLastTyping.length() - maxLength);
myLastTyping = "..." + myLastTyping.substring(myLastTyping.length() - maxLength);
}
actualText = myLastTyping;
} else {
myLastTyping = "";
}
if (myWidget != null) {
myWidget.notifyUser(RECORDED + actualText);
}
myLastWasTyping = typing;
if (!typing) {
myLastTyping = "";
}
}
}
@@ -0,0 +1,72 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.internal;
import com.intellij.ide.caches.CacheUpdater;
import com.intellij.ide.caches.FileContent;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbServiceImpl;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.util.Alarm;
import com.intellij.util.TimeoutUtil;
import java.util.Arrays;
/**
* @author peter
*/
public class ToggleLaggingModeAction extends AnAction implements DumbAware {
private volatile boolean myLagging = false;
private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
public void actionPerformed(final AnActionEvent e) {
if (myLagging) {
myLagging = false;
myAlarm.cancelAllRequests();
}
else {
myLagging = true;
for (int i = 0; i < 100; i++) {
new Runnable() {
@Override
public void run() {
myAlarm.addRequest(this, 1);
}
}.run();
}
}
}
@Override
public void update(final AnActionEvent e) {
final Presentation presentation = e.getPresentation();
final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext());
presentation.setEnabled(project != null && myLagging == DumbServiceImpl.getInstance(project).isDumb());
if (myLagging) {
presentation.setText("Exit dumb mode");
}
else {
presentation.setText("Enter dumb mode");
}
}
}
@@ -252,7 +252,7 @@ public class NotificationsManagerImpl extends NotificationsManager {
text.setCaretPosition(0);
JScrollPane pane = ScrollPaneFactory.createScrollPane(text,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane.setBorder(null);
pane.setOpaque(false);
pane.getViewport().setOpaque(false);
@@ -266,10 +266,14 @@ public class NotificationsManagerImpl extends NotificationsManager {
Dimension preferredSize = text.getPreferredSize();
text.setSize(preferredSize);
preferredSize = text.getPreferredSize();
Dimension paneSize = new Dimension(text.getPreferredSize());
int maxHeight = Math.min(400, window.getComponent().getHeight() - 20);
if (preferredSize.height > maxHeight) {
pane.setPreferredSize(new Dimension(preferredSize.width, maxHeight));
int maxWidth = Math.min(600, window.getComponent().getWidth() - 20);
if (paneSize.height > maxHeight) {
pane.setPreferredSize(new Dimension(Math.min(maxWidth, paneSize.width + UIUtil.getScrollBarWidth()), maxHeight));
} else if (paneSize.width > maxWidth) {
pane.setPreferredSize(new Dimension(maxWidth, paneSize.height + UIUtil.getScrollBarWidth()));
}
final BalloonBuilder builder = JBPopupFactory.getInstance().createBalloonBuilder(content);
@@ -63,7 +63,8 @@ public class NotificationTestAction extends AnAction implements DumbAware {
final Notification notification = new Notification(TEST_GROUP_ID, "This is a test notification", //"a",
"You can<br> close this very<p> very very very long notification by clicking <a href=\"close\">this link</a>. Long long long long. It should be long. Very long. Too long." +
StringUtil.repeat("<br>line", 100) +
//StringUtil.repeat("line", 100) +
//StringUtil.repeat("<br>line", 100) +
" And even longer.",
type, listener);
@@ -715,6 +715,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi
myMousePressedEvent = null;
myMouseMovedEvent = null;
Disposer.dispose(myCaretModel);
Disposer.dispose(mySoftWrapModel);
clearCaretThread();
myFocusListeners.clear();
@@ -16,6 +16,7 @@
package com.intellij.openapi.editor.impl;
import com.intellij.diagnostic.Dumpable;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
@@ -52,7 +53,9 @@ import java.util.List;
* @author Denis Zhdanov
* @since Jun 8, 2010 12:47:32 PM
*/
public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentListener, FoldingListener, PropertyChangeListener, Dumpable {
public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentListener, DocumentBulkUpdateListener, FoldingListener,
PropertyChangeListener, Dumpable, Disposable
{
/**
* Holds name of JVM property which presence should trigger debug-aware soft wraps processing.
@@ -109,6 +112,8 @@ public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentLi
* Current field serves as a flag that indicates if all preliminary actions necessary for successful soft wraps processing is done.
*/
private boolean myUpdateInProgress;
private boolean myBulkUpdateInProgress;
/**
* There is a possible case that target document is changed while its editor is inactive (e.g. user opens two editors for classes
@@ -169,6 +174,8 @@ public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentLi
myUseSoftWraps = settings.isUseSoftWraps();
editor.addPropertyChangeListener(this);
ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(DocumentBulkUpdateListener.TOPIC, this);
}
/**
@@ -370,7 +377,7 @@ public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentLi
@NotNull
@Override
public LogicalPosition visualToLogicalPosition(@NotNull VisualPosition visual) {
if (myUpdateInProgress || !prepareToMapping()) {
if (myBulkUpdateInProgress || myUpdateInProgress || !prepareToMapping()) {
return myEditor.visualToLogicalPosition(visual, false);
}
myActive++;
@@ -386,7 +393,7 @@ public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentLi
@NotNull
@Override
public LogicalPosition offsetToLogicalPosition(int offset) {
if (myUpdateInProgress || !prepareToMapping()) {
if (myBulkUpdateInProgress || myUpdateInProgress || !prepareToMapping()) {
return myEditor.offsetToLogicalPosition(offset, false);
}
myActive++;
@@ -401,7 +408,7 @@ public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentLi
@NotNull
public LogicalPosition adjustLogicalPosition(LogicalPosition defaultLogical, int offset) {
if (myUpdateInProgress || !prepareToMapping()) {
if (myBulkUpdateInProgress || myUpdateInProgress || !prepareToMapping()) {
return defaultLogical;
}
@@ -418,7 +425,7 @@ public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentLi
@Override
@NotNull
public VisualPosition adjustVisualPosition(@NotNull LogicalPosition logical, @NotNull VisualPosition defaultVisual) {
if (myUpdateInProgress || !prepareToMapping()) {
if (myBulkUpdateInProgress || myUpdateInProgress || !prepareToMapping()) {
return defaultVisual;
}
@@ -566,6 +573,9 @@ public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentLi
@Override
public void beforeDocumentChange(DocumentEvent event) {
if (myBulkUpdateInProgress) {
return;
}
myUpdateInProgress = true;
if (!isSoftWrappingEnabled()) {
myDirty = true;
@@ -578,6 +588,9 @@ public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentLi
@Override
public void documentChanged(DocumentEvent event) {
if (myBulkUpdateInProgress) {
return;
}
myUpdateInProgress = false;
if (!isSoftWrappingEnabled()) {
return;
@@ -587,6 +600,20 @@ public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentLi
}
}
@Override
public void updateStarted(@NotNull Document doc) {
myBulkUpdateInProgress = true;
}
@Override
public void updateFinished(@NotNull Document doc) {
myBulkUpdateInProgress = false;
if (!isSoftWrappingEnabled()) {
return;
}
recalculate();
}
@Override
public void onFoldRegionStateChange(@NotNull FoldRegion region) {
myUpdateInProgress = true;
@@ -619,6 +646,11 @@ public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentLi
return myDataMapper;
}
@Override
public void dispose() {
release();
}
@Override
public void release() {
myDataMapper.release();
@@ -632,6 +664,7 @@ public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentLi
myApplianceManager.reset();
myDeferredFoldRegions.clear();
myEditor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
myApplianceManager.recalculateIfNecessary();
}
public SoftWrapApplianceManager getApplianceManager() {
@@ -0,0 +1,180 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.util.IconLoader;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* @author evgeny zakrevsky
*/
public class HideableDecorator {
private final JPanel myPanel;
private final TitledSeparator myTitledSeparator;
private final boolean myAdjustWindow;
private boolean myOn;
private JComponent myContent;
private Dimension myPreviousContentSize;
public HideableDecorator(JPanel panel, String title, boolean adjustWindow) {
myPanel = panel;
myAdjustWindow = adjustWindow;
myTitledSeparator = new TitledSeparator(title, null) {
@Override
public void addNotify() {
super.addNotify();
registerMnemonic();
}
};
myPanel.add(myTitledSeparator, BorderLayout.NORTH);
myTitledSeparator.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
myTitledSeparator.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
if (myOn) {
off();
}
else {
on();
}
}
});
}
public void setContentComponent(@Nullable JComponent content) {
if (content == null && myContent != null) {
myPanel.remove(myContent);
}
myContent = content;
if (myContent != null) {
myContent.setVisible(myOn);
myPanel.add(myContent, BorderLayout.CENTER);
}
}
public void setOn(boolean on) {
myOn = on;
if (myOn) {
on();
}
else {
off();
}
}
public boolean isExpanded() {
return myOn;
}
public void setTitle(String title) {
myTitledSeparator.setText(title);
}
public String getTitle() {
return myTitledSeparator.getText();
}
protected void on() {
myOn = true;
myTitledSeparator.getLabel().setIcon(AllIcons.General.ComboArrowDown);
myTitledSeparator.getLabel().setDisabledIcon(IconLoader.getTransparentIcon(AllIcons.General.ComboArrowDown, 0.5f));
myTitledSeparator.getLabel().setIconTextGap(5);
if (myContent != null) {
myContent.setVisible(true);
}
adjustWindow();
myPanel.invalidate();
myPanel.repaint();
}
protected void off() {
myOn = false;
myTitledSeparator.getLabel().setIcon(AllIcons.General.ComboArrowRight);
myTitledSeparator.getLabel().setDisabledIcon(IconLoader.getTransparentIcon(AllIcons.General.ComboArrowRight, 0.5f));
myTitledSeparator.getLabel()
.setIconTextGap(5 + AllIcons.General.ComboArrowDown.getIconWidth() - AllIcons.General.ComboArrowRight.getIconWidth());
if (myContent != null) {
myContent.setVisible(false);
myPreviousContentSize = myContent.getSize();
}
adjustWindow();
myPanel.invalidate();
myPanel.repaint();
}
private void adjustWindow() {
if (!myAdjustWindow) return;
final Window window = SwingUtilities.getWindowAncestor(myPanel);
if (window == null) return;
final Dimension size = window.getSize();
final Dimension contentSize = myPreviousContentSize != null && myPreviousContentSize.width > 0 && myPreviousContentSize.height > 0
? myPreviousContentSize
: myContent.getPreferredSize();
final Dimension newSize;
if (myOn) {
newSize = new Dimension(Math.max(size.width, myContent.getSize().width), size.height + contentSize.height);
}
else {
newSize = new Dimension(size.width, size.height - contentSize.height);
}
if (!newSize.equals(size)) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (window.isShowing()) {
window.setSize(newSize);
}
}
});
}
}
public void setEnabled(boolean enabled) {
myTitledSeparator.setEnabled(enabled);
myContent.setEnabled(enabled);
}
private void registerMnemonic() {
final int mnemonicIndex = UIUtil.getDisplayMnemonicIndex(getTitle());
if (mnemonicIndex != -1) {
myPanel.getActionMap().put("Collapse/Expand on mnemonic", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (myOn) {
off();
}
else {
on();
}
}
});
final Character mnemonicCharacter = UIUtil.removeMnemonic(getTitle()).toUpperCase().charAt(mnemonicIndex);
myPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke(mnemonicCharacter, InputEvent.ALT_MASK, false), "Collapse/Expand on mnemonic");
}
}
}
@@ -1,28 +1,16 @@
package com.intellij.ui;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.util.IconLoader;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* @author evgeny zakrevsky
*/
public class HideableTitledPanel extends JPanel {
private final TitledSeparator myTitledSeparator;
private final boolean myAdjustWindow;
private boolean myOn;
private JComponent myContent;
private Dimension myPreviousContentSize;
private final HideableDecorator myDecorator;
public HideableTitledPanel(String title) {
this(title, true);
@@ -30,21 +18,7 @@ public class HideableTitledPanel extends JPanel {
public HideableTitledPanel(String title, boolean adjustWindow) {
super(new BorderLayout());
myAdjustWindow = adjustWindow;
myTitledSeparator = new TitledSeparator(title, null);
add(myTitledSeparator, BorderLayout.NORTH);
myTitledSeparator.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
myTitledSeparator.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
if (myOn) {
off();
}
else {
on();
}
}
});
myDecorator = new HideableDecorator(this, title, adjustWindow);
}
public HideableTitledPanel(String title, JComponent content, boolean on) {
@@ -54,117 +28,27 @@ public class HideableTitledPanel extends JPanel {
}
public void setContentComponent(@Nullable JComponent content) {
if (content == null && myContent != null) {
remove(myContent);
}
myContent = content;
if (myContent != null) {
myContent.setVisible(myOn);
add(myContent, BorderLayout.CENTER);
}
myDecorator.setContentComponent(content);
}
public void setOn(boolean on) {
myOn = on;
if (myOn) {
on();
}
else {
off();
}
myDecorator.setOn(on);
}
public boolean isExpanded() {
return myOn;
return myDecorator.isExpanded();
}
public void setTitle(String title) {
myTitledSeparator.setText(title);
myDecorator.setTitle(title);
}
public String getTitle() {
return myTitledSeparator.getText();
}
protected void on() {
myOn = true;
myTitledSeparator.getLabel().setIcon(AllIcons.General.ComboArrowDown);
myTitledSeparator.getLabel().setDisabledIcon(IconLoader.getTransparentIcon(AllIcons.General.ComboArrowDown, 0.5f));
myTitledSeparator.getLabel().setIconTextGap(5);
if (myContent != null) {
myContent.setVisible(true);
}
adjustWindow();
invalidate();
repaint();
}
protected void off() {
myOn = false;
myTitledSeparator.getLabel().setIcon(AllIcons.General.ComboArrowRight);
myTitledSeparator.getLabel().setDisabledIcon(IconLoader.getTransparentIcon(AllIcons.General.ComboArrowRight, 0.5f));
myTitledSeparator.getLabel()
.setIconTextGap(5 + AllIcons.General.ComboArrowDown.getIconWidth() - AllIcons.General.ComboArrowRight.getIconWidth());
if (myContent != null) {
myContent.setVisible(false);
myPreviousContentSize = myContent.getSize();
}
adjustWindow();
invalidate();
repaint();
}
private void adjustWindow() {
if (!myAdjustWindow) return;
final Window window = SwingUtilities.getWindowAncestor(this);
if (window == null) return;
final Dimension size = window.getSize();
final Dimension contentSize = myPreviousContentSize != null && myPreviousContentSize.width > 0 && myPreviousContentSize.height > 0
? myPreviousContentSize
: myContent.getPreferredSize();
final Dimension newSize;
if (myOn) {
newSize = new Dimension(Math.max(size.width, myContent.getSize().width), size.height + contentSize.height);
}
else {
newSize = new Dimension(size.width, size.height - contentSize.height);
}
if (!newSize.equals(size)) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (window.isShowing()) {
window.setSize(newSize);
}
}
});
}
return myDecorator.getTitle();
}
@Override
public void setEnabled(boolean enabled) {
myTitledSeparator.setEnabled(enabled);
myContent.setEnabled(enabled);
}
@Override
public void addNotify() {
super.addNotify();
final int mnemonicIndex = UIUtil.getDisplayMnemonicIndex(getTitle());
if (mnemonicIndex != -1) {
getActionMap().put("Collapse/Expand on mnemonic", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (myOn) {
off();
}
else {
on();
}
}
});
final Character mnemonicCharacter = UIUtil.removeMnemonic(getTitle()).toUpperCase().charAt(mnemonicIndex);
getInputMap(WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke(mnemonicCharacter, InputEvent.ALT_MASK, false), "Collapse/Expand on mnemonic");
}
myDecorator.setEnabled(enabled);
}
}
@@ -185,7 +185,6 @@
<applicationService serviceImplementation="com.intellij.psi.codeStyle.arrangement.engine.ArrangementEngine"/>
<applicationService serviceImplementation="com.intellij.psi.codeStyle.arrangement.MemberOrderService"/>
<applicationService serviceImplementation="com.intellij.application.options.codeStyle.arrangement.ArrangementColorsService"/>
<projectService serviceInterface="com.intellij.ui.EditorTextFieldProvider"
serviceImplementation="com.intellij.ui.EditorTextFieldProviderImpl"/>
@@ -465,12 +464,12 @@
order="after sameModule"/>
<weigher key="completion" implementationClass="com.intellij.codeInsight.completion.PriorityWeigher" id="priority" order="first"/>
<weigher key="completion" implementationClass="com.intellij.codeInsight.completion.StatisticsWeigher" id="stats"
order="after priority"/>
<weigher key="completion" implementationClass="com.intellij.codeInsight.completion.PrefixMatchingWeigher" id="prefix"
order="after stats"/>
<weigher key="completion" implementationClass="com.intellij.codeInsight.completion.LookupElementProximityWeigher" id="proximity"
order="after priority"/>
<weigher key="completion" implementationClass="com.intellij.codeInsight.completion.StatisticsWeigher" id="stats"
order="after prefix"/>
<weigher key="completion" implementationClass="com.intellij.codeInsight.completion.LookupElementProximityWeigher" id="proximity"
order="after stats"/>
<weigher key="completion" implementationClass="com.intellij.codeInsight.completion.GroupingWeigher" id="grouping"
order="last"/>
@@ -87,6 +87,7 @@
<!-- Edit -->
<action id="CopyReference" class="com.intellij.ide.actions.CopyReferenceAction">
<add-to-group group-id="CutCopyPasteGroup" anchor="after" relative-to-action="CopyPaths"/>
<add-to-group group-id="EditorTabPopupMenu" anchor="after" relative-to-action="CopyPaths"/>
<add-to-group group-id="EditorPopupMenu" anchor="after" relative-to-action="$Copy"/>
</action>
@@ -537,6 +537,7 @@
<action internal="true" id="PruneEmptyDirectories" class="com.intellij.ide.actions.PruneEmptyDirectoriesAction" text="Prune Empty Directories"/>
<action internal="true" id="FixLineSeparators" class="com.intellij.ide.actions.FixLineSeparatorsAction" text="Fix Line Separators"/>
<action id="DumbMode" internal="true" class="com.intellij.internal.ToggleDumbModeAction" text="Dumb mode"/>
<action id="LaggingMode" internal="true" class="com.intellij.internal.ToggleLaggingModeAction" text="Lagging mode"/>
<separator/>
<action id="NotificationTestAction" internal="true" class="com.intellij.notification.impl.actions.NotificationTestAction"
text="Add Test Notification"/>
@@ -259,11 +259,11 @@ public final class IconLoader {
return Toolkit.getDefaultToolkit().createImage(prod);
}
public static Icon getTransparentIcon(final Icon icon) {
public static Icon getTransparentIcon(@NotNull final Icon icon) {
return getTransparentIcon(icon, 0.5f);
}
public static Icon getTransparentIcon(final Icon icon, final float alpha) {
public static Icon getTransparentIcon(@NotNull final Icon icon, final float alpha) {
return new Icon() {
public int getIconHeight() {
return icon.getIconHeight();
@@ -432,6 +432,10 @@ public class UIUtil {
return defColor;
}
public static int getScrollBarWidth() {
return UIManager.getInt("ScrollBar.width");
}
public static Font getLabelFont() {
return UIManager.getFont("Label.font");
}
@@ -57,13 +57,7 @@ public class CommittedChangeListRenderer extends ColoredTreeCellRenderer {
}
public static Pair<String, Boolean> getDescriptionOfChangeList(final String text) {
String description = text;
int pos = description.indexOf("\n");
if (pos >= 0) {
description = description.substring(0, pos).trim();
return new Pair<String, Boolean>(description, Boolean.TRUE);
}
return new Pair<String, Boolean>(description, Boolean.FALSE);
return new Pair<String, Boolean>(text.replaceAll("\n", " // "), text.contains("\n"));
}
public static String truncateDescription(final String initDescription, final FontMetrics fontMetrics, int maxWidth) {
@@ -22,12 +22,15 @@ import com.intellij.notification.NotificationType;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.BalloonBuilder;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.NamedRunnable;
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.IdeFrame;
import com.intellij.ui.awt.RelativePoint;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -35,7 +38,6 @@ import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import java.awt.*;
import java.util.concurrent.TimeUnit;
/**
* Shows a notification balloon over one of version control related tool windows: Changes View or Version Control View.
@@ -127,7 +129,35 @@ public class VcsBalloonProblemNotifier implements Runnable {
notification.notify(myProject.isDefault() ? null : myProject);
}
public static void showBalloonForComponent(@NotNull JComponent component, @NotNull final String message, final MessageType type,
public static void showBalloonForActiveComponent(@NotNull final String message, final MessageType type) {
Window[] windows = Window.getWindows();
Window targetWindow = null;
for (Window each : windows) {
if (each.isActive()) {
targetWindow = each;
break;
}
}
if (targetWindow == null) {
targetWindow = JOptionPane.getRootFrame();
}
if (targetWindow == null) {
final IdeFrame frame = IdeFocusManager.findInstance().getLastFocusedFrame();
if (frame == null) {
final Project[] projects = ProjectManager.getInstance().getOpenProjects();
showOverChangesView(projects == null || projects.length == 0 ? ProjectManager.getInstance().getDefaultProject() : projects[0],
message, type);
return;
}
showBalloonForComponent(frame.getComponent(), message, type, true);
} else {
showBalloonForComponent(targetWindow, message, type, true);
}
}
public static void showBalloonForComponent(@NotNull Component component, @NotNull final String message, final MessageType type,
final boolean atTop) {
BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().createHtmlTextBalloonBuilder(message, type, null);
Balloon balloon = balloonBuilder.createBalloon();
@@ -15,6 +15,7 @@
*/
package git4idea;
import git4idea.branch.GitBranchUtil;
import git4idea.repo.GitRemote;
import org.jetbrains.annotations.NotNull;
@@ -27,9 +28,9 @@ public class GitStandardRemoteBranch extends GitRemoteBranch {
@NotNull private final String myNameAtRemote;
public GitStandardRemoteBranch(@NotNull GitRemote remote, @NotNull String nameAtRemote, @NotNull Hash hash) {
super(formStandardName(remote, nameAtRemote), hash);
super(formStandardName(remote, GitBranchUtil.stripRefsPrefix(nameAtRemote)), hash);
myRemote = remote;
myNameAtRemote = nameAtRemote;
myNameAtRemote = GitBranchUtil.stripRefsPrefix(nameAtRemote);
}
@NotNull
@@ -94,7 +94,7 @@ public class GitBranchUtil {
*/
@Deprecated
@Nullable
public static GitBranch getCurrentBranch(@NotNull Project project, @NotNull VirtualFile root) {
public static GitLocalBranch getCurrentBranch(@NotNull Project project, @NotNull VirtualFile root) {
GitRepository repository = GitUtil.getRepositoryManager(project).getRepositoryForRoot(root);
if (repository != null) {
return repository.getCurrentBranch();
@@ -137,7 +137,7 @@ public class GitBranchUtil {
*/
@Deprecated
@Nullable
public static GitBranch tracked(@NotNull Project project, @NotNull VirtualFile root, @NotNull String branchName) throws VcsException {
public static GitRemoteBranch tracked(@NotNull Project project, @NotNull VirtualFile root, @NotNull String branchName) throws VcsException {
final HashMap<String, String> result = new HashMap<String, String>();
GitConfigUtil.getValues(project, root, null, result);
String remoteName = result.get(trackedRemoteKey(branchName));
@@ -27,7 +27,8 @@ import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vfs.VirtualFile;
import git4idea.GitBranch;
import git4idea.GitLocalBranch;
import git4idea.GitRemoteBranch;
import git4idea.GitUtil;
import git4idea.branch.GitBranchUtil;
import git4idea.repo.GitRepository;
@@ -143,9 +144,9 @@ public class GithubOpenInBrowserAction extends DumbAwareAction {
@Nullable
public static String getBranchNameOnRemote(@NotNull Project project, @NotNull VirtualFile root) {
final GitBranch tracked;
final GitRemoteBranch tracked;
try {
final GitBranch current = GitBranchUtil.getCurrentBranch(project, root);
final GitLocalBranch current = GitBranchUtil.getCurrentBranch(project, root);
if (current == null) {
Messages.showErrorDialog(project, "Cannot find local branch", CANNOT_OPEN_IN_BROWSER);
return null;
@@ -160,11 +161,7 @@ public class GithubOpenInBrowserAction extends DumbAwareAction {
Messages.showErrorDialog(project, "Error occurred while inspecting branches: " + e1, CANNOT_OPEN_IN_BROWSER);
return null;
}
String branch = tracked.getName();
if (branch.startsWith("origin/")) {
branch = branch.substring(7);
}
return branch;
return tracked.getNameForRemoteOperations();
}
}
@@ -1,18 +1,3 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.codeInspection.declaration;
import com.intellij.codeInspection.LocalQuickFix;
@@ -31,7 +16,6 @@ import org.jetbrains.plugins.groovy.codeInspection.GroovyInspectionBundle;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
import org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
@@ -44,9 +28,7 @@ import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;
import javax.swing.*;
/**
* @author Max Medvedev
*/
@SuppressWarnings("JavaStylePropertiesInvocation")
public class GrMethodMayBeStaticInspection extends BaseInspection {
public boolean myOnlyPrivateOrFinal = false;
public boolean myIgnoreEmptyMethods = true;
@@ -59,57 +41,40 @@ public class GrMethodMayBeStaticInspection extends BaseInspection {
return optionsPanel;
}
@Override
protected BaseInspectionVisitor buildVisitor() {
return new BaseInspectionVisitor() {
@Override
public void visitMethod(GrMethod method) {
Result result = checkMethod(method);
LocalQuickFix[] fixes;
switch (result) {
case mayBeStatic:
fixes = new LocalQuickFix[]{new GrModifierLocalFix(method, PsiModifier.STATIC, false, true)};
registerError(method.getNameIdentifierGroovy(), GroovyInspectionBundle.message("method.may.be.static"), fixes,
ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
break;
case mayBeStaticButHaveInstanceRefsInClosure:
break;
case mayNotBeStatic:
break;
if (checkMethod(method)) {
LocalQuickFix[] fixes = new LocalQuickFix[]{new GrModifierLocalFix(method, PsiModifier.STATIC, false, true)};
registerError(method.getNameIdentifierGroovy(), GroovyInspectionBundle.message("method.may.be.static"), fixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
}
}
};
}
enum Result {
mayBeStatic,
mayBeStaticButHaveInstanceRefsInClosure,
mayNotBeStatic
}
private Result checkMethod(final GrMethod method) {
if (method.hasModifierProperty(PsiModifier.STATIC)) return Result.mayNotBeStatic;
if (method.hasModifierProperty(PsiModifier.SYNCHRONIZED)) return Result.mayNotBeStatic;
if (method.isConstructor()) return Result.mayNotBeStatic;
if (method.getContainingClass() instanceof GroovyScriptClass) return Result.mayNotBeStatic;
if (SuperMethodsSearch.search(method, null, true, false).findFirst() != null) return Result.mayNotBeStatic;
if (OverridingMethodsSearch.search(method).findFirst() != null) return Result.mayNotBeStatic;
if (ignoreMethod(method))return Result.mayNotBeStatic;
private boolean checkMethod(final GrMethod method) {
if (method.hasModifierProperty(PsiModifier.STATIC)) return false;
if (method.hasModifierProperty(PsiModifier.SYNCHRONIZED)) return false;
if (method.isConstructor()) return false;
if (method.getContainingClass() instanceof GroovyScriptClass) return false;
if (SuperMethodsSearch.search(method, null, true, false).findFirst() != null) return false;
if (OverridingMethodsSearch.search(method).findFirst() != null) return false;
if (ignoreMethod(method)) return false;
if (myOnlyPrivateOrFinal) {
if (!(method.hasModifierProperty(PsiModifier.FINAL) || method.hasModifierProperty(PsiModifier.PRIVATE))) return Result.mayNotBeStatic;
if (!(method.hasModifierProperty(PsiModifier.FINAL) || method.hasModifierProperty(PsiModifier.PRIVATE))) return false;
}
GrOpenBlock block = method.getBlock();
if (block == null) return Result.mayNotBeStatic;
if (myIgnoreEmptyMethods && block.getStatements().length == 0) return Result.mayNotBeStatic;
if (block == null) return false;
if (myIgnoreEmptyMethods && block.getStatements().length == 0) return false;
PsiClass containingClass = method.getContainingClass();
if (containingClass == null) return Result.mayNotBeStatic;
if (containingClass == null) return false;
if (containingClass.getContainingClass() != null && !containingClass.hasModifierProperty(PsiModifier.STATIC)) {
return Result.mayNotBeStatic;
return false;
}
final ExtensionsArea rootArea = Extensions.getRootArea();
@@ -117,26 +82,14 @@ public class GrMethodMayBeStaticInspection extends BaseInspection {
final Condition<PsiElement>[] addins = extensionPoint.getExtensions();
for (Condition<PsiElement> addin : addins) {
if (addin.value(method)) {
return Result.mayNotBeStatic;
return false;
}
}
MethodMayBeStaticVisitor visitor = new MethodMayBeStaticVisitor();
method.accept(visitor);
boolean haveInstanceRefsInClosure = visitor.haveInstanceRefsInClosure();
boolean haveInstanceRefs = visitor.haveInstanceRefsOutsideClosures();
if (!haveInstanceRefsInClosure && !haveInstanceRefs) {
return Result.mayBeStatic;
}
else if (haveInstanceRefsInClosure && !haveInstanceRefs) {
return Result.mayBeStaticButHaveInstanceRefsInClosure;
}
else {
return Result.mayNotBeStatic;
}
return !visitor.haveInstanceRefsOutsideClosures();
}
private static boolean ignoreMethod(GrMethod method) {
@@ -154,27 +107,34 @@ public class GrMethodMayBeStaticInspection extends BaseInspection {
}
private static boolean isPrintOrPrintln(PsiElement element) {
return element instanceof GrGdkMethod && element instanceof PsiMethod &&
return element instanceof GrGdkMethod &&
element instanceof PsiMethod &&
("print".equals(((PsiMethod)element).getName()) || "println".equals(((PsiMethod)element).getName()));
}
private static class MethodMayBeStaticVisitor extends GroovyRecursiveElementVisitor {
private boolean myHaveNoInstanceRefs = true;
private boolean myHaveNoInstanceRefsInClosure = true;
private int myIsInClosure = 0;
private boolean myHaveInstanceRefs = false;
@Override
public void visitElement(GroovyPsiElement element) {
if (!myHaveNoInstanceRefs) return;
if (myHaveInstanceRefs) return;
super.visitElement(element);
}
@Override
public void visitReferenceExpression(GrReferenceExpression referenceExpression) {
if (PsiUtil.isThisOrSuperRef(referenceExpression)) {
if (referenceExpression.getParent() instanceof GrReferenceExpression) return;
registerInstanceRefs();
if (myHaveInstanceRefs) return;
if (PsiUtil.isSuperReference(referenceExpression)) {
registerInstanceRef();
return;
}
if (PsiUtil.isThisReference(referenceExpression)) {
if (!(referenceExpression.getParent() instanceof GrReferenceExpression)) {//if we have reference parent -- check it instead of this ref
registerInstanceRef();
}
return;
}
@@ -182,13 +142,16 @@ public class GrMethodMayBeStaticInspection extends BaseInspection {
if (qualifier == null || PsiUtil.isThisOrSuperRef(qualifier)) {
GroovyResolveResult result = referenceExpression.advancedResolve();
PsiElement element = result.getElement();
if (isPrintOrPrintln(element)) return; //print & println are resolved in all places
if (isPrintOrPrintln(element)) return;
GroovyPsiElement resolveContext = result.getCurrentFileResolveContext();
if (qualifier == null && resolveContext != null) return;
if (element instanceof PsiClass && ((PsiClass)element).getContainingClass() == null) return;
if (element instanceof PsiMember && !((PsiMember)element).hasModifierProperty(PsiModifier.STATIC)) {
registerInstanceRefs();
registerInstanceRef();
}
if (element == null) {
registerInstanceRef();
}
}
else {
@@ -196,27 +159,15 @@ public class GrMethodMayBeStaticInspection extends BaseInspection {
}
}
private void registerInstanceRefs() {
if (myIsInClosure > 0) {
myHaveNoInstanceRefsInClosure = false;
}
else {
myHaveNoInstanceRefs = false;
}
}
@Override
public void visitClosure(GrClosableBlock closure) {
myIsInClosure++;
super.visitClosure(closure);
myIsInClosure--;
private void registerInstanceRef() {
myHaveInstanceRefs = true;
}
@Override
public void visitCodeReferenceElement(GrCodeReferenceElement refElement) {
super.visitCodeReferenceElement(refElement);
if (!myHaveNoInstanceRefs) return;
if (myHaveInstanceRefs) return;
final PsiElement resolvedElement = refElement.resolve();
if (!(resolvedElement instanceof PsiClass)) return;
@@ -226,16 +177,12 @@ public class GrMethodMayBeStaticInspection extends BaseInspection {
if (!(scope instanceof PsiClass)) return;
if (!aClass.hasModifierProperty(PsiModifier.STATIC)) {
registerInstanceRefs();
registerInstanceRef();
}
}
public boolean haveInstanceRefsOutsideClosures() {
return !myHaveNoInstanceRefs;
}
public boolean haveInstanceRefsInClosure() {
return !myHaveNoInstanceRefsInClosure;
return myHaveInstanceRefs;
}
}
}
@@ -200,10 +200,6 @@ public class GroovyBlock implements Block, GroovyElementTypes, ASTBlock {
}
if (BLOCK_SET.contains(astNode.getElementType()) || SWITCH_STATEMENT.equals(astNode.getElementType())) {
// List<Block> blocks = getSubBlocks();
// if (newChildIndex != 0 && newChildIndex <= blocks.size() && blocks.get(newChildIndex - 1) instanceof ClosureBodyBlock) {
// return new ChildAttributes(Indent.getSpaceIndent(mySettings.getIndentOptions().INDENT_SIZE * 2), null);
// }
return new ChildAttributes(Indent.getNormalIndent(), null);
}
if (CASE_SECTION.equals(astNode.getElementType())) {
@@ -110,16 +110,6 @@ public class GroovyBlockGenerator implements GroovyElementTypes {
if (first.getElementType() == GroovyTokenTypes.mLCURLY) children.remove(0);
}
/* if (!children.isEmpty()) {
ASTNode second = children.get(0);
if (second.getElementType() == GroovyElementTypes.PARAMETERS_LIST) children.remove(0);
}
if (!children.isEmpty()) {
ASTNode second = children.get(0);
if (second.getElementType() == GroovyTokenTypes.mCLOSABLE_BLOCK_OP) children.remove(0);
}*/
if (!children.isEmpty()) {
ASTNode last = children.get(children.size() - 1);
if (last.getElementType() == GroovyTokenTypes.mRCURLY) children.remove(children.size() - 1);
@@ -132,14 +122,14 @@ public class GroovyBlockGenerator implements GroovyElementTypes {
//For binary expressions
PsiElement blockPsi = myNode.getPsi();
IElementType elementType = myNode.getElementType();
if (blockPsi instanceof GrBinaryExpression && !(blockPsi.getParent() instanceof GrBinaryExpression)) {
return generateForBinaryExpr();
}
//For multiline strings
if ((myNode.getElementType() == mSTRING_LITERAL || myNode.getElementType() == mGSTRING_LITERAL) &&
myBlock.getTextRange().equals(myNode.getTextRange())) {
if ((elementType == mSTRING_LITERAL || elementType == mGSTRING_LITERAL) && myBlock.getTextRange().equals(myNode.getTextRange())) {
String text = myNode.getText();
if (text.length() > 6) {
if (text.substring(0, 3).equals("'''") && text.substring(text.length() - 3).equals("'''") ||
@@ -149,19 +139,8 @@ public class GroovyBlockGenerator implements GroovyElementTypes {
}
}
if (myNode.getElementType() == mGSTRING_BEGIN &&
myBlock.getTextRange().equals(myNode.getTextRange())) {
String text = myNode.getText();
if (text.length() > 3) {
if (text.substring(0, 3).equals("\"\"\"")) {
return generateForMultiLineGStringBegin();
}
}
}
//for gstrings
if (myNode.getElementType() == GSTRING) {
if (elementType == GSTRING || elementType == REGEX || elementType == mREGEX_LITERAL || elementType == mDOLLAR_SLASH_REGEX_LITERAL) {
final ArrayList<Block> subBlocks = new ArrayList<Block>();
ASTNode[] children = getGroovyChildren(myNode);
for (ASTNode childNode : children) {
@@ -174,7 +153,7 @@ public class GroovyBlockGenerator implements GroovyElementTypes {
}
// chained properties, calls, indexing, etc
if (NESTED.contains(myNode.getElementType()) && blockPsi.getParent() != null && !NESTED.contains(blockPsi.getParent().getNode().getElementType())) {
if (NESTED.contains(elementType) && blockPsi.getParent() != null && !NESTED.contains(blockPsi.getParent().getNode().getElementType())) {
final List<Block> subBlocks = new ArrayList<Block>();
AlignmentProvider.Aligner dotsAligner = mySettings.ALIGN_MULTILINE_CHAINED_METHODS ? myAlignmentProvider.createAligner(true) : null;
addNestedChildren(myNode.getPsi(), subBlocks, dotsAligner, true);
@@ -490,26 +469,6 @@ public class GroovyBlockGenerator implements GroovyElementTypes {
return subBlocks;
}
private List<Block> generateForMultiLineGStringBegin() {
final ArrayList<Block> subBlocks = new ArrayList<Block>();
final int start = myNode.getTextRange().getStartOffset();
final int end = myNode.getTextRange().getEndOffset();
subBlocks.add(new GroovyBlock(myNode, Indent.getNoneIndent(), myWrap, mySettings, myGroovySettings, myAlignmentProvider) {
@NotNull
public TextRange getTextRange() {
return new TextRange(start, start + 3);
}
});
subBlocks.add(new GroovyBlock(myNode, Indent.getAbsoluteNoneIndent(), myWrap, mySettings, myGroovySettings, myAlignmentProvider) {
@NotNull
public TextRange getTextRange() {
return new TextRange(start + 3, end);
}
});
return subBlocks;
}
/**
* @param node Tree node
* @return true, if the current node can be myBlock node, else otherwise
@@ -126,6 +126,19 @@ class Bar extends Base {
super.var()
}
}
''')
}
void testUnresolvedRef() {
doTest('''\
class Bar {
def b() {
print unresolved
}
def <warning descr="Method may be static">abc</warning>() {
print 2
}
}
''')
}
}
@@ -81,6 +81,7 @@ public class FormatterTest extends GroovyFormatterTestCase {
public void testPointer1() throws Throwable { doTest(); }
public void testRange1() throws Throwable { doTest(); }
public void testRegex1() throws Throwable { doTest(); }
public void testRegex2() { doTest() }
public void testSh1() throws Throwable { doTest(); }
public void testSh2() throws Throwable { doTest(); }
public void testSqr1() throws Throwable { doTest(); }
@@ -248,7 +249,6 @@ public class FormatterTest extends GroovyFormatterTestCase {
void testAssertDescriptionIndent() { doTest() }
private void doGeeseTest() {
GroovyCodeStyleSettings customSettings = myTempSettings.getCustomSettings(GroovyCodeStyleSettings.class);
boolean oldvalue = customSettings.USE_FLYING_GEESE_BRACES;
+11
View File
@@ -0,0 +1,11 @@
print(/ /)
print(/ $x /)
print($/ /$)
print($/ $x /$)
-----
print(/ /)
print(/ $x /)
print($/ /$)
print($/ $x /$)
@@ -316,6 +316,7 @@ public class CustomMaven3Artifact implements Artifact {
}
public int compareTo(Artifact o) {
if (o instanceof CustomMaven3Artifact) o = ((CustomMaven3Artifact)o).myWrapee;
return myWrapee.compareTo(o);
}
@@ -29,9 +29,11 @@ import org.jetbrains.idea.maven.server.MavenModelConverter;
import org.jetbrains.idea.maven.server.UnresolvedArtifactsCollector;
import org.sonatype.aether.RepositorySystem;
import org.sonatype.aether.RepositorySystemSession;
import org.sonatype.aether.repository.LocalRepository;
import org.sonatype.aether.repository.LocalRepositoryManager;
import org.sonatype.aether.resolution.ArtifactRequest;
import org.sonatype.aether.resolution.ArtifactResult;
import org.sonatype.aether.util.FilterRepositorySystemSession;
import java.io.File;
import java.util.*;
@@ -108,9 +110,16 @@ public class CustomMaven3ArtifactResolver
}
}
private RepositorySystemSession getSession( ArtifactRepository localRepository )
{
return LegacyLocalRepositoryManager.overlay( localRepository, legacySupport.getRepositorySession(), repoSystem );
private RepositorySystemSession getSession(ArtifactRepository localRepository) {
RepositorySystemSession session =
LegacyLocalRepositoryManager.overlay(localRepository, legacySupport.getRepositorySession(), repoSystem);
return new FilterRepositorySystemSession(session) {
@Override
public LocalRepository getLocalRepository() {
return getLocalRepositoryManager().getRepository(); // avoid NPE in DefaultMetadataResolver.resolve(RepositorySystemSession,Collection<? extends MetadataRequest>) : 318
}
};
}
private void injectSession1( RepositoryRequest request, MavenSession session )
@@ -262,6 +262,7 @@ progress.text2.processing.file=Processing file {0}
progress.title.lock.files=Lock Files
exception.text.locking.file.failed=Failed to lock file: {0}
message.title.lock.failures=Lock Failures
message.text.files.lock.failed={0,choice, 0#Failed to lock file.|1#Failed to lock files.}
message.text.files.locked={0,choice, 0#Failed to lock files.|1#1 file locked|2#{0,number} files locked}
progress.text.unlocking.files=Unlocking files in repository...
progress.title.unlock.files=Unlock Files
@@ -196,11 +196,16 @@ public class SvnUtil {
if (!failedLocks.isEmpty()) {
String[] failedFiles = ArrayUtil.toStringArray(failedLocks);
List<VcsException> exceptions = new ArrayList<VcsException>();
for (String file : failedFiles) {
exceptions.add(new VcsException(SvnBundle.message("exception.text.locking.file.failed", file)));
}
final StringBuilder sb = new StringBuilder(SvnBundle.message("message.text.files.lock.failed", failedFiles.length == 1 ? 0 : 1));
for (VcsException vcsException : exceptions) {
if (sb.length() > 0) sb.append('\n');
sb.append(vcsException.getMessage());
}
AbstractVcsHelper.getInstance(project).showErrors(exceptions, SvnBundle.message("message.title.lock.failures"));
throw new VcsException(sb.toString());
}
StatusBarUtil.setStatusBarInfo(project, SvnBundle.message("message.text.files.locked", count[0]));
@@ -8,7 +8,7 @@
<properties/>
<border type="none"/>
<children>
<tabbedpane id="87eba" class="com.intellij.ui.components.JBTabbedPane">
<tabbedpane id="87eba" class="com.intellij.ui.components.JBTabbedPane" binding="myTabbedPane">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
@@ -35,7 +35,7 @@
<properties>
<horizontalAlignment value="4"/>
<labelFor value="4045e"/>
<text value="&amp;URL:"/>
<text value="Server U&amp;RL:"/>
</properties>
</component>
<component id="4045e" class="javax.swing.JTextField" binding="myURLText">
@@ -60,7 +60,7 @@
</constraints>
<properties>
<horizontalAlignment value="4"/>
<text value="Use pro&amp;xy"/>
<text value="Use prox&amp;y"/>
</properties>
</component>
<component id="39542" class="javax.swing.JButton" binding="myProxySettingsButton" default-binding="true">
@@ -68,7 +68,7 @@
<grid row="6" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Proxy settings..."/>
<text value="Pr&amp;oxy settings..."/>
</properties>
</component>
<component id="d86a3" class="javax.swing.JCheckBox" binding="myUseHTTPAuthentication">
@@ -76,7 +76,7 @@
<grid row="6" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Use HTTP authentication"/>
<text value="Use &amp;HTTP authentication"/>
</properties>
</component>
<hspacer id="122ff">
@@ -89,7 +89,7 @@
<grid row="7" column="3" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="4" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="&amp;Test"/>
<text value="Te&amp;st"/>
</properties>
</component>
<component id="8abc1" class="javax.swing.JCheckBox" binding="myShareURL">
@@ -97,7 +97,7 @@
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="&amp;Share URL"/>
<text value="Sh&amp;are URL"/>
</properties>
</component>
<component id="93b1c" class="com.intellij.ui.components.JBCheckBox" binding="myLoginAnonymouslyJBCheckBox" default-binding="true">
@@ -105,7 +105,7 @@
<grid row="2" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Login Anonymously"/>
<text value="Lo&amp;gin Anonymously"/>
</properties>
</component>
<component id="22736" class="com.intellij.ui.components.JBLabel" binding="myUsernameLabel">
@@ -115,7 +115,7 @@
<properties>
<horizontalAlignment value="4"/>
<labelFor value="63a48"/>
<text value="User&amp;name:"/>
<text value="Userna&amp;me:"/>
</properties>
</component>
<component id="63a48" class="javax.swing.JTextField" binding="myUserNameText">
@@ -25,10 +25,9 @@ import com.intellij.tasks.TaskRepositoryType;
import com.intellij.tasks.impl.BaseRepository;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.PanelWithAnchor;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.SideBorder;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBTabbedPane;
import com.intellij.util.Consumer;
import com.intellij.util.net.HttpConfigurable;
import org.jetbrains.annotations.Nullable;
@@ -65,6 +64,7 @@ public class BaseRepositoryEditor<T extends BaseRepository> extends TaskReposito
private JBLabel myComment;
private JPanel myEditorPanel;
protected JBCheckBox myLoginAnonymouslyJBCheckBox;
protected JBTabbedPane myTabbedPane;
private boolean myApplying;
protected Project myProject;
@@ -113,7 +113,7 @@ public class BaseRepositoryEditor<T extends BaseRepository> extends TaskReposito
myAddCommitMessage.setSelected(repository.isShouldFormatCommitMessage());
myDocument = EditorFactory.getInstance().createDocument(repository.getCommitMessageFormat());
myEditor = EditorFactory.getInstance().createEditor(myDocument);
myEditorPanel.add(ScrollPaneFactory.createScrollPane(myEditor.getComponent(), SideBorder.NONE), BorderLayout.CENTER);
myEditorPanel.add(myEditor.getComponent(), BorderLayout.CENTER);
myComment.setText("Available placeholders: " + repository.getComment());
installListener(myAddCommitMessage);
@@ -139,11 +139,12 @@ public class BaseRepositoryEditor<T extends BaseRepository> extends TaskReposito
loginAnonymouslyChanged(!myLoginAnonymouslyJBCheckBox.isSelected());
}
protected void loginAnonymouslyChanged(boolean enabled) {
private void loginAnonymouslyChanged(boolean enabled) {
myUsernameLabel.setEnabled(enabled);
myUserNameText.setEnabled(enabled);
myPasswordLabel.setEnabled(enabled);
myPasswordText.setEnabled(enabled);
myUseHTTPAuthentication.setEnabled(enabled);
}
@Nullable
@@ -50,7 +50,7 @@ public class TaskCellRenderer extends DefaultListCellRenderer implements Matcher
panel.setBackground(bg);
SimpleTextAttributes attr = getAttributes(sel, task.isClosed());
c.setIcon(isLocalTask && isOld ? IconLoader.getTransparentIcon(task.getIcon(), 0.5f) : task.getIcon());
c.setIcon(isLocalTask && isOld && task.getIcon() != null ? IconLoader.getTransparentIcon(task.getIcon()) : task.getIcon());
SpeedSearchUtil.appendColoredFragmentForMatcher(TaskUtil.getTrimmedSummary(task), c, attr, myMatcher, bg, sel);
panel.add(c, BorderLayout.CENTER);
}
@@ -29,7 +29,8 @@ public class GenericWebRepository extends BaseRepositoryImpl {
private String myTaskPattern = "";
private String myLoginURL = "";
private String myLoginMethodType = GenericWebRepositoryEditor.GET;
private String myGetTasksMethodType = GenericWebRepositoryEditor.GET;
private String myTasksListMethodType = GenericWebRepositoryEditor.GET;
private ResponseType myResponseType = ResponseType.XML;
final static String SERVER_URL_PLACEHOLDER = "{serverUrl}";
final static String USERNAME_PLACEHOLDER = "{username}";
@@ -57,21 +58,21 @@ public class GenericWebRepository extends BaseRepositoryImpl {
myTaskPattern = other.getTaskPattern();
myLoginURL = other.getLoginURL();
myLoginMethodType = other.getLoginMethodType();
myGetTasksMethodType = other.getGetTasksMethodType();
myTasksListMethodType = other.getTasksListMethodType();
myResponseType = other.getResponseType();
}
@Override
public Task[] getIssues(@Nullable final String query, final int max, final long since) throws Exception {
final HttpClient httpClient = getHttpClient();
if (!isLoginAnonymously()) login(httpClient);
if (!isLoginAnonymously() && !isUseHttpAuthentication()) login(httpClient);
final List<String> placeholders = getPlaceholders(myTaskPattern);
if (!placeholders.contains(ID_PLACEHOLDER) || !placeholders.contains(SUMMARY_PLACEHOLDER)) {
throw new Exception("Incorrect Task Pattern");
}
//todo add possibility to select method type
final HttpMethod method = getTaskListsMethod(query != null ? query : "", max);
httpClient.executeMethod(method);
if (method.getStatusCode() != 200) throw new Exception("Cannot get tasks: HTTP status code " + method.getStatusCode());
@@ -87,7 +88,7 @@ public class GenericWebRepository extends BaseRepositoryImpl {
while (matcher.find()) {
final String id = matcher.group(placeholders.indexOf(ID_PLACEHOLDER) + 1);
final String summary = matcher.group(placeholders.indexOf(SUMMARY_PLACEHOLDER) + 1);
tasks.add(new GenericWebTask(id, summary));
tasks.add(new GenericWebTask(id, summary, this));
}
tasks = TaskSearchSupport.filterTasks(query != null ? query : "", tasks);
@@ -98,7 +99,16 @@ public class GenericWebRepository extends BaseRepositoryImpl {
private HttpMethod getTaskListsMethod(final String query, final int max) {
String requestUrl = getFullTasksUrl(query, max);
return GenericWebRepositoryEditor.GET.equals(myGetTasksMethodType) ? new GetMethod(requestUrl) : getPostMethodFromURL(requestUrl);
final HttpMethod method =
GenericWebRepositoryEditor.GET.equals(myTasksListMethodType) ? new GetMethod(requestUrl) : getPostMethodFromURL(requestUrl);
configureHttpMethod(method);
return method;
}
@Override
protected void configureHttpMethod(final HttpMethod method) {
super.configureHttpMethod(method);
method.addRequestHeader("accept", myResponseType.getMimeType());
}
private void login(final HttpClient httpClient) throws Exception {
@@ -170,22 +180,6 @@ public class GenericWebRepository extends BaseRepositoryImpl {
return new GenericWebRepository(this);
}
public String getTasksListURL() {
return myTasksListURL;
}
public void setTasksListURL(final String tasksListURL) {
myTasksListURL = tasksListURL;
}
public String getTaskPattern() {
return myTaskPattern;
}
public void setTaskPattern(final String taskPattern) {
myTaskPattern = taskPattern;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
@@ -196,7 +190,8 @@ public class GenericWebRepository extends BaseRepositoryImpl {
if (!Comparing.equal(getTaskPattern(), that.getTaskPattern())) return false;
if (!Comparing.equal(getLoginURL(), that.getLoginURL())) return false;
if (!Comparing.equal(getLoginMethodType(), that.getLoginMethodType())) return false;
if (!Comparing.equal(getGetTasksMethodType(), that.getGetTasksMethodType())) return false;
if (!Comparing.equal(getTasksListMethodType(), that.getTasksListMethodType())) return false;
if (!Comparing.equal(getResponseType(), that.getResponseType())) return false;
return true;
}
@@ -216,6 +211,12 @@ public class GenericWebRepository extends BaseRepositoryImpl {
};
}
@Nullable
@Override
public String getTaskComment(final Task task) {
return super.getTaskComment(task);
}
public String getLoginURL() {
return myLoginURL;
}
@@ -228,15 +229,39 @@ public class GenericWebRepository extends BaseRepositoryImpl {
myLoginMethodType = loginMethodType;
}
public void setGetTasksMethodType(final String getTasksMethodType) {
myGetTasksMethodType = getTasksMethodType;
public void setTasksListMethodType(final String tasksListMethodType) {
myTasksListMethodType = tasksListMethodType;
}
public String getLoginMethodType() {
return myLoginMethodType;
}
public String getGetTasksMethodType() {
return myGetTasksMethodType;
public String getTasksListMethodType() {
return myTasksListMethodType;
}
public ResponseType getResponseType() {
return myResponseType;
}
public void setResponseType(final ResponseType responseType) {
myResponseType = responseType;
}
public String getTasksListURL() {
return myTasksListURL;
}
public void setTasksListURL(final String tasksListURL) {
myTasksListURL = tasksListURL;
}
public String getTaskPattern() {
return myTaskPattern;
}
public void setTaskPattern(final String taskPattern) {
myTaskPattern = taskPattern;
}
}
@@ -0,0 +1,195 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.tasks.generic.GenericWebRepositoryEditor">
<grid id="27dc6" binding="myPanel" layout-manager="GridLayoutManager" row-count="5" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="8">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="500" height="400"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="5918d" layout-manager="GridLayoutManager" row-count="2" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="2">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="3" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="true"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="37da0" class="com.intellij.ui.components.JBLabel" binding="myLoginURLLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="4" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="a0a2f"/>
<text value="Lo&amp;gin URL:"/>
</properties>
</component>
<component id="a0a2f" class="com.intellij.ui.EditorTextField" binding="myLoginURLText" custom-create="true">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
</component>
<component id="ce0fe" class="com.intellij.ui.components.JBLabel" binding="myLoginTooltip">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="8" fill="0" indent="1" use-parent-layout="false"/>
</constraints>
<properties>
<componentStyle value="SMALL"/>
<fontColor value="BRIGHTER"/>
<text value="tooltip"/>
</properties>
</component>
<component id="eee0a" class="com.intellij.openapi.ui.ComboBox" binding="myLoginMethodType">
<constraints>
<grid row="0" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="2" anchor="0" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<model>
<item value="GET"/>
<item value="POST"/>
</model>
</properties>
</component>
</children>
</grid>
<grid id="294f1" layout-manager="GridLayoutManager" row-count="2" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="2">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="0" row-span="1" col-span="3" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="true"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="6dd8" class="com.intellij.ui.components.JBLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="4" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="87697"/>
<text value="Tasks &amp;List URL:"/>
</properties>
</component>
<component id="87697" class="com.intellij.ui.EditorTextField" binding="myTasksListURLText" custom-create="true">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
</component>
<component id="24df4" class="com.intellij.ui.components.JBLabel" binding="myTaskListTooltip">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="8" fill="0" indent="1" use-parent-layout="false"/>
</constraints>
<properties>
<componentStyle value="SMALL"/>
<fontColor value="BRIGHTER"/>
<text value="tooltip"/>
</properties>
</component>
<component id="d1239" class="com.intellij.openapi.ui.ComboBox" binding="myTasksListMethodType">
<constraints>
<grid row="0" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="2" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<model>
<item value="GET"/>
<item value="POST"/>
</model>
</properties>
</component>
</children>
</grid>
<grid id="ab85c" layout-manager="GridLayoutManager" row-count="2" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="2">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="3" column="0" row-span="1" col-span="3" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="true"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="8cc78" class="com.intellij.ui.components.JBLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="5" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="a91dc"/>
<text value="Task &amp;Pattern:"/>
</properties>
</component>
<component id="21e89" class="com.intellij.ui.components.JBLabel" binding="myTaskPatternTooltip">
<constraints>
<grid row="1" column="1" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="8" fill="0" indent="1" use-parent-layout="false"/>
</constraints>
<properties>
<componentStyle value="SMALL"/>
<fontColor value="BRIGHTER"/>
<text value="tooltip"/>
</properties>
</component>
<component id="a91dc" class="com.intellij.ui.EditorTextField" binding="myTaskPatternText" custom-create="true">
<constraints>
<grid row="0" column="1" row-span="1" col-span="2" vsize-policy="7" hsize-policy="6" anchor="0" fill="3" indent="0" use-parent-layout="false">
<preferred-size width="1" height="1"/>
</grid>
</constraints>
<properties/>
</component>
</children>
</grid>
<component id="df2e4" class="com.intellij.ui.components.JBLabel">
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="4" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Response Type:"/>
</properties>
</component>
<grid id="d68b9" layout-manager="GridLayoutManager" row-count="1" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="2" column="1" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="7c3b0" class="javax.swing.JRadioButton" binding="myXmlRadioButton">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="X&amp;ML"/>
</properties>
</component>
<component id="90539" class="javax.swing.JRadioButton" binding="myHtmlRadioButton">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="&amp;HTML"/>
</properties>
</component>
<hspacer id="cebcb">
<constraints>
<grid row="0" column="2" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
</hspacer>
</children>
</grid>
<component id="536c8" class="javax.swing.JButton" binding="myTest2Button">
<constraints>
<grid row="4" column="1" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="4" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Te&amp;st"/>
</properties>
</component>
</children>
</grid>
<buttonGroups>
<group name="myGroup1">
<member id="7c3b0"/>
<member id="90539"/>
</group>
</buttonGroups>
</form>
@@ -1,30 +1,27 @@
package com.intellij.tasks.generic;
import com.intellij.ide.highlighter.HtmlFileType;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.tasks.TaskManager;
import com.intellij.tasks.config.BaseRepositoryEditor;
import com.intellij.ui.EditorTextField;
import com.intellij.ui.TextFieldWithAutoCompletion;
import com.intellij.ui.TextFieldWithAutoCompletionContributor;
import com.intellij.ui.components.JBLabel;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.FormBuilder;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import static com.intellij.tasks.generic.GenericWebRepository.*;
import static com.intellij.ui.TextFieldWithAutoCompletion.StringsCompletionProvider;
/**
* User: Evgeny.Zakrevsky
@@ -33,28 +30,101 @@ import static com.intellij.ui.TextFieldWithAutoCompletion.StringsCompletionProvi
public class GenericWebRepositoryEditor extends BaseRepositoryEditor<GenericWebRepository> {
public static final String POST = "POST";
public static final String GET = "GET";
private JBLabel myTasksListURLLabel;
private JBLabel myTaskPatternLabel;
private TextFieldWithAutoCompletion<String> myTasksListURLText;
private Editor myTaskPatternText;
private EditorTextField myTasksListURLText;
private EditorTextField myTaskPatternText;
private JBLabel myLoginURLLabel;
private TextFieldWithAutoCompletion<String> myLoginURLText;
private EditorTextField myLoginURLText;
private ComboBox myLoginMethodType;
private ComboBox myGetTasksMethodType;
private ComboBox myTasksListMethodType;
private JBLabel myLoginTooltip;
private JBLabel myTaskListTooltip;
private JBLabel myTaskPatternTooltip;
private JPanel myPanel;
private JRadioButton myXmlRadioButton;
private JRadioButton myHtmlRadioButton;
private JButton myTest2Button;
public GenericWebRepositoryEditor(final Project project,
final GenericWebRepository repository,
final Consumer<GenericWebRepository> changeListener) {
super(project, repository, changeListener);
myUrlLabel.setText("Server URL");
myTest2Button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
afterTestConnection(TaskManager.getManager(project).testConnection(repository));
}
});
myLoginAnonymouslyJBCheckBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
loginUrlEnablingChanged();
}
});
myUseHTTPAuthentication.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
loginUrlEnablingChanged();
}
});
switch (myRepository.getResponseType()) {
case XML:
myXmlRadioButton.setSelected(true);
myHtmlRadioButton.setSelected(false);
break;
case HTML:
myXmlRadioButton.setSelected(false);
myHtmlRadioButton.setSelected(true);
break;
}
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
responseTypeChanged();
}
};
myXmlRadioButton.addActionListener(listener);
myHtmlRadioButton.addActionListener(listener);
myLoginMethodType.setSelectedItem(myRepository.getLoginMethodType());
myTasksListMethodType.setSelectedItem(myRepository.getTasksListMethodType());
installListener(myLoginMethodType);
installListener(myTasksListMethodType);
installListener(myTasksListURLText.getDocument());
installListener(myLoginURLText.getDocument());
installListener(myTaskPatternText.getDocument());
String useCompletionText = ". Use " +
KeymapUtil
.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction(IdeActions.ACTION_CODE_COMPLETION)) +
" for completion.";
myLoginTooltip.setText("<html>Available placeholders: " + SERVER_URL_PLACEHOLDER + ", " + USERNAME_PLACEHOLDER + ", " +
PASSWORD_PLACEHOLDER + useCompletionText + "</html>");
myTaskListTooltip.setText("<html>Available placeholders: " + SERVER_URL_PLACEHOLDER + ", " + MAX_COUNT_PLACEHOLDER + ", " +
QUERY_PLACEHOLDER + " (use for faster tasks search)" + useCompletionText + "</html>");
myTaskPatternTooltip.setText(
"<html>Task pattern should be a regexp with two matching groups: ({id}.+?) and ({summary}.+?)" + useCompletionText + "</html>");
myTabbedPane.addTab("Additional", myPanel);
loginUrlEnablingChanged();
}
@Override
protected void loginAnonymouslyChanged(boolean enabled) {
super.loginAnonymouslyChanged(enabled);
private void responseTypeChanged() {
doApply();
myTaskPatternText.setFileType(myRepository.getResponseType().getFileType());
}
private void loginUrlEnablingChanged() {
final boolean enabled = !myLoginAnonymouslyJBCheckBox.isSelected() && !myUseHTTPAuthentication.isSelected();
myLoginURLLabel.setEnabled(enabled);
myLoginURLText.setEnabled(enabled);
myLoginMethodType.setEnabled(enabled);
myLoginTooltip.setEnabled(enabled);
}
@Override
@@ -63,74 +133,25 @@ public class GenericWebRepositoryEditor extends BaseRepositoryEditor<GenericWebR
myRepository.setTaskPattern(myTaskPatternText.getDocument().getText());
myRepository.setLoginURL(myLoginURLText.getText());
myRepository.setLoginMethodType((String)myLoginMethodType.getModel().getSelectedItem());
myRepository.setGetTasksMethodType((String)myGetTasksMethodType.getModel().getSelectedItem());
myRepository.setTasksListMethodType((String)myTasksListMethodType.getModel().getSelectedItem());
myRepository.setResponseType(myXmlRadioButton.isSelected() ? ResponseType.XML : ResponseType.HTML);
super.apply();
}
@Nullable
@Override
protected JComponent createCustomPanel() {
myLoginURLLabel = new JBLabel("Login URL:", SwingConstants.RIGHT);
myLoginURLText = TextFieldWithAutoCompletion
.create(myProject, ContainerUtil.newArrayList(SERVER_URL_PLACEHOLDER, USERNAME_PLACEHOLDER, PASSWORD_PLACEHOLDER), null, false,
myRepository.getLoginURL());
installListener(myLoginURLText.getDocument());
myLoginMethodType = new ComboBox(new String[]{GET, POST}, -1);
myLoginMethodType.setSelectedItem(myRepository.getLoginMethodType());
installListener(myLoginMethodType);
JPanel loginPanel = new JPanel(new BorderLayout(UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP));
loginPanel.add(myLoginURLText, BorderLayout.CENTER);
loginPanel.add(myLoginMethodType, BorderLayout.EAST);
myTasksListURLLabel = new JBLabel("Tasks List URL:", SwingConstants.RIGHT);
final ArrayList<String> completionList1 = ContainerUtil.newArrayList(SERVER_URL_PLACEHOLDER, QUERY_PLACEHOLDER, MAX_COUNT_PLACEHOLDER);
myTasksListURLText = TextFieldWithAutoCompletion.create(myProject, completionList1, null, false, myRepository.getTasksListURL());
installListener(myTasksListURLText.getDocument());
myGetTasksMethodType = new ComboBox(new String[]{GET, POST}, -1);
myGetTasksMethodType.setSelectedItem(myRepository.getGetTasksMethodType());
installListener(myGetTasksMethodType);
JPanel tasksPanel = new JPanel(new BorderLayout(UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP));
tasksPanel.add(myTasksListURLText, BorderLayout.CENTER);
tasksPanel.add(myGetTasksMethodType, BorderLayout.EAST);
myTaskPatternLabel = new JBLabel("Task Pattern:", SwingConstants.RIGHT);
final Document document = EditorFactory.getInstance().createDocument(myRepository.getTaskPattern());
myTaskPatternText = EditorFactory.getInstance().createEditor(document, myProject, HtmlFileType.INSTANCE, false);
final ArrayList<String> completionList2 = ContainerUtil.newArrayList("({id}.+?)", "({summary}.+?)");
TextFieldWithAutoCompletionContributor
.installCompletion(document, myProject, new StringsCompletionProvider(completionList2, null), true);
installListener(document);
myTaskPatternText.getSettings().setLineMarkerAreaShown(false);
myTaskPatternText.getSettings().setFoldingOutlineShown(false);
//todo correct resizing
private void createUIComponents() {
//todo completion
//todo completion without whitespace before cursor
final ArrayList<String> completionList = ContainerUtil.newArrayList(SERVER_URL_PLACEHOLDER, USERNAME_PLACEHOLDER, PASSWORD_PLACEHOLDER);
myLoginURLText = TextFieldWithAutoCompletion.create(myProject, completionList, null, false, myRepository.getLoginURL());
String useCompletionText = ". Use " +
KeymapUtil
.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction(IdeActions.ACTION_CODE_COMPLETION)) +
" for completion.";
final ArrayList<String> completionList1 = ContainerUtil.newArrayList(SERVER_URL_PLACEHOLDER, QUERY_PLACEHOLDER, MAX_COUNT_PLACEHOLDER);
myTasksListURLText = TextFieldWithAutoCompletion.create(myProject, completionList1, null, false, myRepository.getTasksListURL());
return FormBuilder.createFormBuilder().setAlignLabelOnRight(true)
.addLabeledComponent(myLoginURLLabel, loginPanel)
.addTooltip(
"<html>Available placeholders: " + SERVER_URL_PLACEHOLDER + ", " + USERNAME_PLACEHOLDER + ", " + PASSWORD_PLACEHOLDER +
useCompletionText + "</html>")
.addLabeledComponent(myTasksListURLLabel, tasksPanel)
.addTooltip(
"<html>Available placeholders: " + SERVER_URL_PLACEHOLDER + ", " + MAX_COUNT_PLACEHOLDER + ", " + QUERY_PLACEHOLDER +
" (use for faster tasks search)" + useCompletionText + "</html>")
.addLabeledComponent(myTaskPatternLabel, myTaskPatternText.getComponent())
.addTooltip(
"<html>Task pattern should be a regexp with two matching groups: ({id}.+?) and ({summary}.+?)" + useCompletionText + "</html>")
.getPanel();
}
@Override
public void setAnchor(@Nullable final JComponent anchor) {
super.setAnchor(anchor);
myTasksListURLLabel.setAnchor(anchor);
myTaskPatternLabel.setAnchor(anchor);
myLoginURLLabel.setAnchor(anchor);
final Document document = EditorFactory.getInstance().createDocument(myRepository.getTaskPattern());
myTaskPatternText = new EditorTextField(document, myProject, myRepository.getResponseType().getFileType(), false, false);
final ArrayList<String> completionList2 = ContainerUtil.newArrayList("({id}.+?)", "({summary}.+?)");
TextFieldWithAutoCompletionContributor
.installCompletion(document, myProject, new TextFieldWithAutoCompletion.StringsCompletionProvider(completionList2, null), true);
myTaskPatternText.setFontInheritedFromLAF(false);
}
}
@@ -47,6 +47,6 @@ public class GenericWebRepositoryType extends BaseRepositoryType<GenericWebRepos
@Override
protected int getFeatures() {
return LOGIN_ANONYMOUSLY;
return LOGIN_ANONYMOUSLY | BASIC_HTTP_AUTHORIZATION;
}
}
@@ -2,6 +2,7 @@ package com.intellij.tasks.generic;
import com.intellij.tasks.Comment;
import com.intellij.tasks.Task;
import com.intellij.tasks.TaskRepository;
import com.intellij.tasks.TaskType;
import icons.TasksIcons;
import org.jetbrains.annotations.NotNull;
@@ -13,10 +14,12 @@ import java.util.Date;
public class GenericWebTask extends Task {
private final String myId;
private final String myDescription;
private TaskRepository myRepository;
public GenericWebTask(final String id, final String description) {
public GenericWebTask(final String id, final String description, final TaskRepository repository) {
myId = id;
myDescription = description;
myRepository = repository;
}
@NotNull
@@ -82,4 +85,10 @@ public class GenericWebTask extends Task {
public String getIssueUrl() {
return null;
}
@Nullable
@Override
public TaskRepository getRepository() {
return myRepository;
}
}
@@ -0,0 +1,31 @@
package com.intellij.tasks.generic;
import com.intellij.ide.highlighter.HtmlFileType;
import com.intellij.ide.highlighter.XmlFileType;
import com.intellij.openapi.fileTypes.FileType;
/**
* User: evgeny.zakrevsky
* Date: 10/25/12
*/
public enum ResponseType {
XML("application/xml", XmlFileType.INSTANCE),
HTML("text/html", HtmlFileType.INSTANCE);
//todo JSON("application/json")
private String myMimeType;
private FileType myFileType;
ResponseType(final String s, final FileType fileType) {
myMimeType = s;
myFileType = fileType;
}
public String getMimeType() {
return myMimeType;
}
public FileType getFileType() {
return myFileType;
}
}
-1
View File
@@ -38,7 +38,6 @@
</library>
</orderEntry>
<orderEntry type="library" name="gson" level="project" />
<orderEntry type="module" module-name="RegExpSupport" />
<orderEntry type="module" module-name="xml" />
</component>
</module>
@@ -39,11 +39,10 @@ import java.util.List;
public abstract class DomStub extends ObjectStubBase<DomStub> {
protected final StringRef myLocalName;
@Nullable
private final StringRef myNamespace;
private DomInvocationHandler myHandler;
public DomStub(DomStub parent, @NotNull StringRef localName, @Nullable StringRef namespace) {
public DomStub(DomStub parent, @NotNull StringRef localName, StringRef namespace) {
super(parent);
myNamespace = namespace;
if (parent != null) {
@@ -69,11 +68,12 @@ public abstract class DomStub extends ObjectStubBase<DomStub> {
}
public List<DomStub> getChildrenByName(final CharSequence name, @Nullable final String nsKey) {
final String s = nsKey == null ? "" : nsKey;
return ContainerUtil.filter(getChildrenStubs(), new Condition<DomStub>() {
@Override
public boolean value(DomStub stub) {
return XmlUtil.getLocalName(stub.getName()).equals(name) &&
Comparing.equal(nsKey, stub.getNamespaceKey());
Comparing.equal(s, stub.getNamespaceKey());
}
});
}