issue_id
int64
2.03k
426k
title
stringlengths
9
251
body
stringlengths
1
32.8k
status
stringclasses
6 values
after_fix_sha
stringlengths
7
7
project_name
stringclasses
6 values
repo_url
stringclasses
6 values
repo_name
stringclasses
6 values
language
stringclasses
1 value
issue_url
null
before_fix_sha
null
pull_url
null
commit_datetime
timestamp[us, tz=UTC]
report_datetime
timestamp[us, tz=UTC]
updated_file
stringlengths
2
187
file_content
stringlengths
0
368k
38,086
Bug 38086 Add suggestion "array.length()" -> array.length [quick fix]
When referring to an array's length, it would be useful if the developer made a mistake of using array.length() to be prompted with a suggestion to change it to array.length instead, as opposed to 'no suggestion' that it currently says at the moment Mac OS X.2.6 with Eclipse 2.1
resolved fixed
a271da5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T10:18:30Z
2003-05-24T23:46:40Z
org.eclipse.jdt.ui/core
38,086
Bug 38086 Add suggestion "array.length()" -> array.length [quick fix]
When referring to an array's length, it would be useful if the developer made a mistake of using array.length() to be prompted with a suggestion to change it to array.length instead, as opposed to 'no suggestion' that it currently says at the moment Mac OS X.2.6 with Eclipse 2.1
resolved fixed
a271da5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T10:18:30Z
2003-05-24T23:46:40Z
extension/org/eclipse/jdt/internal/corext/dom/ScopeAnalyzer.java
38,086
Bug 38086 Add suggestion "array.length()" -> array.length [quick fix]
When referring to an array's length, it would be useful if the developer made a mistake of using array.length() to be prompted with a suggestion to change it to array.length instead, as opposed to 'no suggestion' that it currently says at the moment Mac OS X.2.6 with Eclipse 2.1
resolved fixed
a271da5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T10:18:30Z
2003-05-24T23:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickFixProcessor.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.ui.text.java.IInvocationContext; import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal; import org.eclipse.jdt.ui.text.java.IProblemLocation; import org.eclipse.jdt.ui.text.java.IQuickFixProcessor; /** */ public class QuickFixProcessor implements IQuickFixProcessor { public boolean hasCorrections(ICompilationUnit cu, int problemId) { switch (problemId) { case IProblem.UnterminatedString: case IProblem.UnusedImport: case IProblem.DuplicateImport: case IProblem.CannotImportPackage: case IProblem.ConflictingImport: case IProblem.ImportNotFound: case IProblem.UndefinedMethod: case IProblem.UndefinedConstructor: case IProblem.ParameterMismatch: case IProblem.MethodButWithConstructorName: case IProblem.UndefinedField: case IProblem.UndefinedName: case IProblem.PublicClassMustMatchFileName: case IProblem.PackageIsNotExpectedPackage: case IProblem.UndefinedType: case IProblem.FieldTypeNotFound: case IProblem.ArgumentTypeNotFound: case IProblem.ReturnTypeNotFound: case IProblem.SuperclassNotFound: case IProblem.ExceptionTypeNotFound: case IProblem.InterfaceNotFound: case IProblem.TypeMismatch: case IProblem.UnhandledException: case IProblem.UnreachableCatch: case IProblem.InvalidCatchBlockSequence: case IProblem.VoidMethodReturnsValue: case IProblem.ShouldReturnValue: case IProblem.MissingReturnType: case IProblem.NonExternalizedStringLiteral: case IProblem.NonStaticAccessToStaticField: case IProblem.NonStaticAccessToStaticMethod: case IProblem.StaticMethodRequested: case IProblem.NonStaticFieldFromStaticInvocation: case IProblem.InstanceMethodDuringConstructorInvocation: case IProblem.InstanceFieldDuringConstructorInvocation: case IProblem.NotVisibleMethod: case IProblem.NotVisibleConstructor: case IProblem.NotVisibleType: case IProblem.SuperclassNotVisible: case IProblem.InterfaceNotVisible: case IProblem.FieldTypeNotVisible: case IProblem.ArgumentTypeNotVisible: case IProblem.ReturnTypeNotVisible: case IProblem.ExceptionTypeNotVisible: case IProblem.NotVisibleField: case IProblem.ImportNotVisible: case IProblem.BodyForAbstractMethod: case IProblem.AbstractMethodInAbstractClass: case IProblem.AbstractMethodMustBeImplemented: case IProblem.BodyForNativeMethod: case IProblem.OuterLocalMustBeFinal: case IProblem.UninitializedLocalVariable: case IProblem.UndefinedConstructorInDefaultConstructor: case IProblem.UnhandledExceptionInDefaultConstructor: case IProblem.NotVisibleConstructorInDefaultConstructor: case IProblem.FieldTypeAmbiguous: case IProblem.ArgumentTypeAmbiguous: case IProblem.ExceptionTypeAmbiguous: case IProblem.ReturnTypeAmbiguous: case IProblem.SuperclassAmbiguous: case IProblem.InterfaceAmbiguous: case IProblem.AmbiguousType: case IProblem.UnusedPrivateMethod: case IProblem.UnusedPrivateConstructor: case IProblem.UnusedPrivateField: case IProblem.UnusedPrivateType: case IProblem.LocalVariableIsNeverUsed: case IProblem.ArgumentIsNeverUsed: case IProblem.MethodRequiresBody: case IProblem.NeedToEmulateFieldReadAccess: case IProblem.NeedToEmulateFieldWriteAccess: case IProblem.NeedToEmulateMethodAccess: case IProblem.NeedToEmulateConstructorAccess: case IProblem.SuperfluousSemicolon: case IProblem.UnnecessaryCast: case IProblem.UnnecessaryArgumentCast: case IProblem.UnnecessaryInstanceof: case IProblem.IndirectAccessToStaticField: case IProblem.IndirectAccessToStaticMethod: case IProblem.Task: case IProblem.UnusedMethodDeclaredThrownException: case IProblem.UnusedConstructorDeclaredThrownException: case IProblem.UnqualifiedFieldAccess: case IProblem.JavadocMissing: case IProblem.JavadocMissingParamTag: case IProblem.JavadocMissingReturnTag: case IProblem.JavadocMissingThrowsTag: case IProblem.JavadocUndefinedType: case IProblem.JavadocAmbiguousType: case IProblem.JavadocNotVisibleType: case IProblem.NonBlankFinalLocalAssignment: case IProblem.DuplicateFinalLocalInitialization: case IProblem.FinalFieldAssignment: case IProblem.DuplicateBlankFinalFieldInitialization: case IProblem.AnonymousClassCannotExtendFinalClass: case IProblem.ClassExtendFinalClass: case IProblem.FinalMethodCannotBeOverridden: case IProblem.InheritedMethodReducesVisibility: case IProblem.MethodReducesVisibility: case IProblem.OverridingNonVisibleMethod: case IProblem.CannotOverrideAStaticMethodWithAnInstanceMethod: case IProblem.CannotHideAnInstanceMethodWithAStaticMethod: case IProblem.LocalVariableHidingLocalVariable: case IProblem.LocalVariableHidingField: case IProblem.FieldHidingLocalVariable: case IProblem.FieldHidingField: case IProblem.ArgumentHidingLocalVariable: case IProblem.ArgumentHidingField: case IProblem.IllegalModifierForInterfaceMethod: case IProblem.IllegalModifierForInterface: case IProblem.IllegalModifierForClass: case IProblem.IllegalModifierForInterfaceField: case IProblem.IllegalModifierForMemberInterface: case IProblem.IllegalModifierForMemberClass: case IProblem.IllegalModifierForLocalClass: case IProblem.IllegalModifierForArgument: case IProblem.IllegalModifierForField: case IProblem.IllegalModifierForMethod: case IProblem.IllegalModifierForVariable: case IProblem.IllegalVisibilityModifierForInterfaceMemberType: case IProblem.IncompatibleReturnType: case IProblem.IncompatibleExceptionInThrowsClause: return true; default: return false; } } private static int moveBack(int offset, int start, String ignoreCharacters, ICompilationUnit cu) { try { IBuffer buf= cu.getBuffer(); while (offset >= start) { if (ignoreCharacters.indexOf(buf.getChar(offset - 1)) == -1) { //$NON-NLS-1$ return offset; } offset--; } } catch(JavaModelException e) { } return start; } /* (non-Javadoc) * @see IAssistProcessor#getCorrections(org.eclipse.jdt.internal.ui.text.correction.IAssistContext, org.eclipse.jdt.internal.ui.text.correction.IProblemLocation[]) */ public IJavaCompletionProposal[] getCorrections(IInvocationContext context, IProblemLocation[] locations) throws CoreException { if (locations == null || locations.length == 0) { return null; } HashSet handledProblems= new HashSet(locations.length); ArrayList resultingCollections= new ArrayList(); for (int i= 0; i < locations.length; i++) { IProblemLocation curr= locations[i]; Integer id= new Integer(curr.getProblemId()); if (handledProblems.add(id)) { process(context, curr, resultingCollections); } } return (IJavaCompletionProposal[]) resultingCollections.toArray(new IJavaCompletionProposal[resultingCollections.size()]); } private void process(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { int id= problem.getProblemId(); if (id == 0) { // no proposals for none-problem locations return; } switch (id) { case IProblem.UnterminatedString: String quoteLabel= CorrectionMessages.getString("JavaCorrectionProcessor.addquote.description"); //$NON-NLS-1$ int pos= moveBack(problem.getOffset() + problem.getLength(), problem.getOffset(), "\n\r", context.getCompilationUnit()); //$NON-NLS-1$ proposals.add(new ReplaceCorrectionProposal(quoteLabel, context.getCompilationUnit(), pos, 0, "\"", 0)); //$NON-NLS-1$ break; case IProblem.UnusedImport: case IProblem.DuplicateImport: case IProblem.CannotImportPackage: case IProblem.ConflictingImport: ReorgCorrectionsSubProcessor.removeImportStatementProposals(context, problem, proposals); break; case IProblem.ImportNotFound: ReorgCorrectionsSubProcessor.importNotFoundProposals(context, problem, proposals); ReorgCorrectionsSubProcessor.removeImportStatementProposals(context, problem, proposals); break; case IProblem.UndefinedMethod: UnresolvedElementsSubProcessor.getMethodProposals(context, problem, false, proposals); break; case IProblem.UndefinedConstructor: UnresolvedElementsSubProcessor.getConstructorProposals(context, problem, proposals); break; case IProblem.ParameterMismatch: UnresolvedElementsSubProcessor.getMethodProposals(context, problem, true, proposals); break; case IProblem.MethodButWithConstructorName: ReturnTypeSubProcessor.addMethodWithConstrNameProposals(context, problem, proposals); break; case IProblem.UndefinedField: case IProblem.UndefinedName: UnresolvedElementsSubProcessor.getVariableProposals(context, problem, proposals); break; case IProblem.FieldTypeAmbiguous: case IProblem.ArgumentTypeAmbiguous: case IProblem.ExceptionTypeAmbiguous: case IProblem.ReturnTypeAmbiguous: case IProblem.SuperclassAmbiguous: case IProblem.InterfaceAmbiguous: case IProblem.AmbiguousType: case IProblem.JavadocAmbiguousType: UnresolvedElementsSubProcessor.getAmbiguosTypeReferenceProposals(context, problem, proposals); break; case IProblem.PublicClassMustMatchFileName: ReorgCorrectionsSubProcessor.getWrongTypeNameProposals(context, problem, proposals); break; case IProblem.PackageIsNotExpectedPackage: ReorgCorrectionsSubProcessor.getWrongPackageDeclNameProposals(context, problem, proposals); break; case IProblem.UndefinedType: case IProblem.FieldTypeNotFound: case IProblem.ArgumentTypeNotFound: case IProblem.ReturnTypeNotFound: case IProblem.SuperclassNotFound: case IProblem.ExceptionTypeNotFound: case IProblem.InterfaceNotFound: case IProblem.JavadocUndefinedType: UnresolvedElementsSubProcessor.getTypeProposals(context, problem, proposals); break; case IProblem.TypeMismatch: TypeMismatchSubProcessor.addTypeMismatchProposals(context, problem, proposals); break; case IProblem.IncompatibleReturnType: TypeMismatchSubProcessor.addIncompatibleReturnTypeProposals(context, problem, proposals); break; case IProblem.IncompatibleExceptionInThrowsClause: TypeMismatchSubProcessor.addIncompatibleThrowsProposals(context, problem, proposals); break; case IProblem.UnhandledException: LocalCorrectionsSubProcessor.addUncaughtExceptionProposals(context, problem, proposals); break; case IProblem.UnreachableCatch: case IProblem.InvalidCatchBlockSequence: LocalCorrectionsSubProcessor.addUnreachableCatchProposals(context, problem, proposals); break; case IProblem.VoidMethodReturnsValue: ReturnTypeSubProcessor.addVoidMethodReturnsProposals(context, problem, proposals); break; case IProblem.MissingReturnType: ReturnTypeSubProcessor.addMissingReturnTypeProposals(context, problem, proposals); break; case IProblem.ShouldReturnValue: ReturnTypeSubProcessor.addMissingReturnStatementProposals(context, problem, proposals); break; case IProblem.NonExternalizedStringLiteral: LocalCorrectionsSubProcessor.addNLSProposals(context, problem, proposals); break; case IProblem.NonStaticAccessToStaticField: case IProblem.NonStaticAccessToStaticMethod: case IProblem.IndirectAccessToStaticField: case IProblem.IndirectAccessToStaticMethod: LocalCorrectionsSubProcessor.addCorrectAccessToStaticProposals(context, problem, proposals); break; case IProblem.StaticMethodRequested: case IProblem.NonStaticFieldFromStaticInvocation: case IProblem.InstanceMethodDuringConstructorInvocation: case IProblem.InstanceFieldDuringConstructorInvocation: ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_STATIC, 5); break; case IProblem.NonBlankFinalLocalAssignment: case IProblem.DuplicateFinalLocalInitialization: case IProblem.FinalFieldAssignment: case IProblem.DuplicateBlankFinalFieldInitialization: case IProblem.AnonymousClassCannotExtendFinalClass: case IProblem.ClassExtendFinalClass: ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_FINAL, 9); break; case IProblem.InheritedMethodReducesVisibility: case IProblem.MethodReducesVisibility: case IProblem.OverridingNonVisibleMethod: ModifierCorrectionSubProcessor.addChangeOverriddenModfierProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_VISIBLE); break; case IProblem.FinalMethodCannotBeOverridden: ModifierCorrectionSubProcessor.addChangeOverriddenModfierProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_FINAL); break; case IProblem.CannotOverrideAStaticMethodWithAnInstanceMethod: ModifierCorrectionSubProcessor.addChangeOverriddenModfierProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_STATIC); break; case IProblem.CannotHideAnInstanceMethodWithAStaticMethod: case IProblem.IllegalModifierForInterfaceMethod: case IProblem.IllegalModifierForInterface: case IProblem.IllegalModifierForClass: case IProblem.IllegalModifierForInterfaceField: case IProblem.IllegalModifierForMemberInterface: case IProblem.IllegalModifierForMemberClass: case IProblem.IllegalModifierForLocalClass: case IProblem.IllegalModifierForArgument: case IProblem.IllegalModifierForField: case IProblem.IllegalModifierForMethod: case IProblem.IllegalModifierForVariable: case IProblem.IllegalVisibilityModifierForInterfaceMemberType: ModifierCorrectionSubProcessor.addRemoveInvalidModfiersProposal(context, problem, proposals, 5); break; case IProblem.NotVisibleMethod: case IProblem.NotVisibleConstructor: case IProblem.NotVisibleType: case IProblem.SuperclassNotVisible: case IProblem.InterfaceNotVisible: case IProblem.FieldTypeNotVisible: case IProblem.ArgumentTypeNotVisible: case IProblem.ReturnTypeNotVisible: case IProblem.ExceptionTypeNotVisible: case IProblem.NotVisibleField: case IProblem.ImportNotVisible: case IProblem.JavadocNotVisibleType: ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_VISIBLE, 10); break; case IProblem.BodyForAbstractMethod: case IProblem.AbstractMethodInAbstractClass: ModifierCorrectionSubProcessor.addAbstractMethodProposals(context, problem, proposals); break; case IProblem.AbstractMethodMustBeImplemented: LocalCorrectionsSubProcessor.addUnimplementedMethodsProposals(context, problem, proposals); break; case IProblem.BodyForNativeMethod: ModifierCorrectionSubProcessor.addNativeMethodProposals(context, problem, proposals); break; case IProblem.MethodRequiresBody: ModifierCorrectionSubProcessor.addMethodRequiresBodyProposals(context, problem, proposals); break; case IProblem.OuterLocalMustBeFinal: ModifierCorrectionSubProcessor.addNonFinalLocalProposal(context, problem, proposals); break; case IProblem.UninitializedLocalVariable: LocalCorrectionsSubProcessor.addUninitializedLocalVariableProposal(context, problem, proposals); break; case IProblem.UnhandledExceptionInDefaultConstructor: case IProblem.UndefinedConstructorInDefaultConstructor: case IProblem.NotVisibleConstructorInDefaultConstructor: LocalCorrectionsSubProcessor.addConstructorFromSuperclassProposal(context, problem, proposals); break; case IProblem.UnusedPrivateMethod: case IProblem.UnusedPrivateConstructor: case IProblem.UnusedPrivateField: case IProblem.UnusedPrivateType: case IProblem.LocalVariableIsNeverUsed: case IProblem.ArgumentIsNeverUsed: LocalCorrectionsSubProcessor.addUnusedMemberProposal(context, problem, proposals); break; case IProblem.NeedToEmulateFieldReadAccess: case IProblem.NeedToEmulateFieldWriteAccess: case IProblem.NeedToEmulateMethodAccess: case IProblem.NeedToEmulateConstructorAccess: ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_PRIVATE, 5); break; case IProblem.SuperfluousSemicolon: LocalCorrectionsSubProcessor.addSuperfluousSemicolonProposal(context, problem, proposals); break; case IProblem.UnnecessaryCast: case IProblem.UnnecessaryArgumentCast: LocalCorrectionsSubProcessor.addUnnecessaryCastProposal(context, problem, proposals); break; case IProblem.UnnecessaryInstanceof: LocalCorrectionsSubProcessor.addUnnecessaryInstanceofProposal(context, problem, proposals); break; case IProblem.UnusedMethodDeclaredThrownException: case IProblem.UnusedConstructorDeclaredThrownException: LocalCorrectionsSubProcessor.addUnnecessaryThrownExceptionProposal(context, problem, proposals); break; case IProblem.UnqualifiedFieldAccess: LocalCorrectionsSubProcessor.addUnqualifiedFieldAccessProposal(context, problem, proposals); break; case IProblem.Task: proposals.add(new TaskMarkerProposal(context.getCompilationUnit(), problem, 10)); break; case IProblem.JavadocMissing: JavadocTagsSubProcessor.getMissingJavadocCommentProposals(context, problem, proposals); break; case IProblem.JavadocMissingParamTag: case IProblem.JavadocMissingReturnTag: case IProblem.JavadocMissingThrowsTag: JavadocTagsSubProcessor.getMissingJavadocTagProposals(context, problem, proposals); break; case IProblem.LocalVariableHidingLocalVariable: case IProblem.LocalVariableHidingField: case IProblem.FieldHidingLocalVariable: case IProblem.FieldHidingField: case IProblem.ArgumentHidingLocalVariable: case IProblem.ArgumentHidingField: LocalCorrectionsSubProcessor.addHidingVariablesProposals(context, problem, proposals); break; default: } } }
38,086
Bug 38086 Add suggestion "array.length()" -> array.length [quick fix]
When referring to an array's length, it would be useful if the developer made a mistake of using array.length() to be prompted with a suggestion to change it to array.length instead, as opposed to 'no suggestion' that it currently says at the moment Mac OS X.2.6 with Eclipse 2.1
resolved fixed
a271da5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T10:18:30Z
2003-05-24T23:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Renaud Waldura &lt;renaud+eclipse@waldura.com&gt; - New class/interface with wizard *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.ui.ISharedImages; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.ui.text.java.IInvocationContext; import org.eclipse.jdt.ui.text.java.IProblemLocation; import org.eclipse.jdt.internal.corext.codemanipulation.ImportRewrite; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer; import org.eclipse.jdt.internal.corext.dom.TypeRules; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Strings; import org.eclipse.jdt.internal.corext.util.TypeFilter; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.ChangeDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.EditDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.InsertDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.RemoveDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.SwapDescription; public class UnresolvedElementsSubProcessor { public static void getVariableProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveredNode(astRoot); if (selectedNode == null) { return; } // type that defines the variable ITypeBinding binding= null; ITypeBinding declaringTypeBinding= Bindings.getBindingOfParentType(selectedNode); if (declaringTypeBinding == null) { return; } // possible type kind of the node boolean suggestVariableProposals= true; int typeKind= 0; while (selectedNode instanceof ParenthesizedExpression) { selectedNode= ((ParenthesizedExpression) selectedNode).getExpression(); } Name node= null; switch (selectedNode.getNodeType()) { case ASTNode.SIMPLE_NAME: node= (SimpleName) selectedNode; ASTNode parent= node.getParent(); if (parent instanceof MethodInvocation && node.equals(((MethodInvocation)parent).getExpression())) { typeKind= SimilarElementsRequestor.CLASSES; } else if (parent instanceof SimpleType) { suggestVariableProposals= false; typeKind= SimilarElementsRequestor.REF_TYPES; } else if (parent instanceof QualifiedName) { Name qualifier= ((QualifiedName) parent).getQualifier(); if (qualifier != node) { binding= qualifier.resolveTypeBinding(); } else { typeKind= SimilarElementsRequestor.REF_TYPES; } ASTNode outerParent= parent.getParent(); while (outerParent instanceof QualifiedName) { outerParent= outerParent.getParent(); } if (outerParent instanceof SimpleType) { typeKind= SimilarElementsRequestor.REF_TYPES; suggestVariableProposals= false; } } break; case ASTNode.QUALIFIED_NAME: QualifiedName qualifierName= (QualifiedName) selectedNode; ITypeBinding qualifierBinding= qualifierName.getQualifier().resolveTypeBinding(); if (qualifierBinding != null) { node= qualifierName.getName(); binding= qualifierBinding; } else { node= qualifierName.getQualifier(); typeKind= SimilarElementsRequestor.REF_TYPES; suggestVariableProposals= node.isSimpleName(); } if (selectedNode.getParent() instanceof SimpleType) { typeKind= SimilarElementsRequestor.REF_TYPES; suggestVariableProposals= false; } break; case ASTNode.FIELD_ACCESS: FieldAccess access= (FieldAccess) selectedNode; Expression expression= access.getExpression(); if (expression != null) { binding= expression.resolveTypeBinding(); if (binding != null) { node= access.getName(); } } break; case ASTNode.SUPER_FIELD_ACCESS: binding= declaringTypeBinding.getSuperclass(); node= ((SuperFieldAccess) selectedNode).getName(); break; default: } if (node == null) { return; } // add type proposals if (typeKind != 0) { int relevance= Character.isUpperCase(ASTResolving.getSimpleName(node).charAt(0)) ? 3 : 0; addSimilarTypeProposals(typeKind, cu, node, relevance + 1, proposals); addNewTypeProposals(cu, node, SimilarElementsRequestor.REF_TYPES, relevance, proposals); } if (!suggestVariableProposals) { return; } SimpleName simpleName= node.isSimpleName() ? (SimpleName) node : ((QualifiedName) node).getName(); boolean isWriteAccess= ASTResolving.isWriteAccess(node); // similar variables addSimilarVariableProposals(cu, astRoot, simpleName, isWriteAccess, proposals); // new fields addNewFieldProposals(cu, astRoot, binding, declaringTypeBinding, simpleName, isWriteAccess, proposals); // new parameters and local variables if (binding == null) { addNewVariableProposals(cu, node, simpleName, proposals); } } private static void addNewVariableProposals(ICompilationUnit cu, Name node, SimpleName simpleName, Collection proposals) { String name= simpleName.getIdentifier(); BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(node); int type= bodyDeclaration.getNodeType(); if (type == ASTNode.METHOD_DECLARATION) { int relevance= StubUtility.hasParameterName(cu.getJavaProject(), name) ? 8 : 5; String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createparameter.description", simpleName.getIdentifier()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.PARAM, simpleName, null, relevance, image)); } if (type == ASTNode.METHOD_DECLARATION || type == ASTNode.INITIALIZER) { int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7; String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createlocal.description", simpleName.getIdentifier()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.LOCAL, simpleName, null, relevance, image)); } if (node.getParent().getNodeType() == ASTNode.ASSIGNMENT) { Assignment assignment= (Assignment) node.getParent(); if (assignment.getLeftHandSide() == node && assignment.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) { ASTNode statement= assignment.getParent(); ASTRewrite rewrite= ASTRewrite.create(statement.getAST()); rewrite.remove(statement, null); String label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.removestatement.description"); //$NON-NLS-1$ Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 4, image); proposals.add(proposal); } } } private static void addNewFieldProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, ITypeBinding declaringTypeBinding, SimpleName simpleName, boolean isWriteAccess, Collection proposals) throws JavaModelException { // new variables ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding); ITypeBinding senderBinding= binding != null ? binding : declaringTypeBinding; if (!senderBinding.isFromSource() || targetCU == null || !JavaModelUtil.isEditable(targetCU)) { return; } ITypeBinding outsideAnonymous= null; if (binding == null && senderBinding.isAnonymous()) { ASTNode anonymDecl= astRoot.findDeclaringNode(senderBinding); if (anonymDecl != null) { ITypeBinding bind= Bindings.getBindingOfParentType(anonymDecl.getParent()); if (!bind.isAnonymous()) { outsideAnonymous= bind; } } } String name= simpleName.getIdentifier(); int relevance= StubUtility.hasFieldName(cu.getJavaProject(), name) ? 9 : 6; String label; Image image; if (binding == null) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.description", name); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE); } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { name, binding.getName() } ); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC); } proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, relevance, image)); // create field in outer class (if inside anonymous) if (outsideAnonymous != null) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { name, outsideAnonymous.getName() } ); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC); proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, outsideAnonymous, relevance + 1, image)); } // create constant if (!isWriteAccess) { relevance= StubUtility.hasConstantName(name) ? 9 : 4; ITypeBinding target= (outsideAnonymous != null) ? outsideAnonymous : senderBinding; if (binding == null) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconst.description", name); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE); } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconst.other.description", new Object[] { name, binding.getName() } ); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC); } proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.CONST_FIELD, simpleName, target, relevance, image)); } } private static void addSimilarVariableProposals(ICompilationUnit cu, CompilationUnit astRoot, SimpleName node, boolean isWriteAccess, Collection proposals) { IBinding[] varsInScope= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(node, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY); if (varsInScope.length > 0) { // avoid corrections like int i= i; String otherNameInAssign= null; ASTNode parent= node.getParent(); if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) { // node must be initializer otherNameInAssign= ((VariableDeclarationFragment) parent).getName().getIdentifier(); } else if (parent.getNodeType() == ASTNode.ASSIGNMENT) { Assignment assignment= (Assignment) parent; if (isWriteAccess && assignment.getRightHandSide() instanceof SimpleName) { otherNameInAssign= ((SimpleName) assignment.getRightHandSide()).getIdentifier(); } else if (!isWriteAccess && assignment.getLeftHandSide() instanceof SimpleName) { otherNameInAssign= ((SimpleName) assignment.getLeftHandSide()).getIdentifier(); } } ITypeBinding guessedType= ASTResolving.guessBindingForReference(node); if (astRoot.getAST().resolveWellKnownType("java.lang.Object") == guessedType) { //$NON-NLS-1$ guessedType= null; // too many suggestions } String identifier= node.getIdentifier(); for (int i= 0; i < varsInScope.length; i++) { IVariableBinding curr= (IVariableBinding) varsInScope[i]; String currName= curr.getName(); boolean isFinal= Modifier.isFinal(curr.getModifiers()); if (!currName.equals(otherNameInAssign) && !(isFinal && curr.isField() && isWriteAccess)) { int relevance= 0; if (NameMatcher.isSimilarName(currName, identifier)) { relevance += 3; // variable with a similar name than the unresolved variable } if (currName.equalsIgnoreCase(identifier)) { relevance+= 5; } ITypeBinding varType= curr.getType(); if (guessedType != null && varType != null) { if (!isWriteAccess && TypeRules.canAssign(varType, guessedType) || isWriteAccess && TypeRules.canAssign(guessedType, varType)) { relevance += 2; // unresolved variable can be assign to this variable } } if (relevance > 0) { String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changevariable.description", currName); //$NON-NLS-1$ proposals.add(new RenameNodeCompletionProposal(label, cu, node.getStartPosition(), node.getLength(), currName, relevance)); } } } } } public static void getTypeProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (selectedNode == null) { return; } int kind= SimilarElementsRequestor.ALL_TYPES; ASTNode parent= selectedNode.getParent(); while (parent.getLength() == selectedNode.getLength()) { // get parent of type or variable fragment parent= parent.getParent(); } switch (parent.getNodeType()) { case ASTNode.TYPE_DECLARATION: TypeDeclaration typeDeclaration=(TypeDeclaration) parent; if (typeDeclaration.superInterfaces().contains(selectedNode)) { kind= SimilarElementsRequestor.INTERFACES; } else if (selectedNode.equals(typeDeclaration.getSuperclass())) { kind= SimilarElementsRequestor.CLASSES; } break; case ASTNode.METHOD_DECLARATION: MethodDeclaration methodDeclaration= (MethodDeclaration) parent; if (methodDeclaration.thrownExceptions().contains(selectedNode)) { kind= SimilarElementsRequestor.CLASSES; } else if (selectedNode.equals(methodDeclaration.getReturnType())) { kind= SimilarElementsRequestor.ALL_TYPES | SimilarElementsRequestor.VOIDTYPE; } break; case ASTNode.INSTANCEOF_EXPRESSION: kind= SimilarElementsRequestor.REF_TYPES; break; case ASTNode.THROW_STATEMENT: kind= SimilarElementsRequestor.REF_TYPES; break; case ASTNode.CLASS_INSTANCE_CREATION: if (((ClassInstanceCreation) parent).getAnonymousClassDeclaration() == null) { kind= SimilarElementsRequestor.CLASSES; } else { kind= SimilarElementsRequestor.REF_TYPES; } break; case ASTNode.SINGLE_VARIABLE_DECLARATION: int superParent= parent.getParent().getNodeType(); if (superParent == ASTNode.CATCH_CLAUSE) { kind= SimilarElementsRequestor.CLASSES; } break; case ASTNode.TAG_ELEMENT: kind= SimilarElementsRequestor.REF_TYPES; break; default: } Name node= null; if (selectedNode instanceof SimpleType) { node= ((SimpleType) selectedNode).getName(); } else if (selectedNode instanceof ArrayType) { Type elementType= ((ArrayType) selectedNode).getElementType(); if (elementType.isSimpleType()) { node= ((SimpleType) elementType).getName(); } } else if (selectedNode instanceof Name) { node= (Name) selectedNode; } else { return; } // change to similar type proposals addSimilarTypeProposals(kind, cu, node, 3, proposals); // add type addNewTypeProposals(cu, node, kind, 0, proposals); } private static void addSimilarTypeProposals(int kind, ICompilationUnit cu, Name node, int relevance, Collection proposals) throws CoreException { SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, node, kind); // try to resolve type in context -> highest severity String resolvedTypeName= null; ITypeBinding binding= ASTResolving.guessBindingForTypeReference(node); if (binding != null) { if (binding.isArray()) { binding= binding.getElementType(); } resolvedTypeName= binding.getQualifiedName(); proposals.add(createTypeRefChangeProposal(cu, resolvedTypeName, node, relevance + 2)); } // add all similar elements for (int i= 0; i < elements.length; i++) { SimilarElement elem= elements[i]; if ((elem.getKind() & SimilarElementsRequestor.ALL_TYPES) != 0) { String fullName= elem.getName(); if (!fullName.equals(resolvedTypeName)) { proposals.add(createTypeRefChangeProposal(cu, fullName, node, relevance)); } } } } private static CUCorrectionProposal createTypeRefChangeProposal(ICompilationUnit cu, String fullName, Name node, int relevance) throws CoreException { ImportRewrite importRewrite= new ImportRewrite(cu); importRewrite.setFindAmbiguosImports(true); String simpleName= importRewrite.addImport(fullName); String packName= Signature.getQualifier(fullName); String[] arg= { simpleName, packName }; CUCorrectionProposal proposal; if (node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) { // import only // import only String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importtype.description", arg); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL); proposal= new CUCorrectionProposal(label, cu, relevance + 100, image); } else { String label; if (packName.length() == 0) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.nopack.description", simpleName); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.description", arg); //$NON-NLS-1$ } proposal= new RenameNodeCompletionProposal(label, cu, node.getStartPosition(), node.getLength(), simpleName, relevance); //$NON-NLS-1$ } proposal.setImportRewrite(importRewrite); return proposal; } private static void addNewTypeProposals(ICompilationUnit cu, Name refNode, int kind, int relevance, Collection proposals) throws JavaModelException { Name node= refNode; do { String typeName= ASTResolving.getSimpleName(node); Name qualifier= null; // only propose to create types for qualifiers when the name starts with upper case boolean isPossibleName= Character.isUpperCase(typeName.charAt(0)) || (node == refNode); if (isPossibleName) { IPackageFragment enclosingPackage= null; IType enclosingType= null; if (node.isSimpleName()) { enclosingPackage= (IPackageFragment) cu.getParent(); // don't suggest member type, user can select it in wizard } else { Name qualifierName= ((QualifiedName) node).getQualifier(); // 24347 // IBinding binding= qualifierName.resolveBinding(); // if (binding instanceof ITypeBinding) { // enclosingType= Binding2JavaModel.find((ITypeBinding) binding, cu.getJavaProject()); IJavaElement[] res= cu.codeSelect(qualifierName.getStartPosition(), qualifierName.getLength()); if (res!= null && res.length > 0 && res[0] instanceof IType) { enclosingType= (IType) res[0]; } else { qualifier= qualifierName; enclosingPackage= JavaModelUtil.getPackageFragmentRoot(cu).getPackageFragment(ASTResolving.getFullName(qualifierName)); } } // new top level type if (enclosingPackage != null && !enclosingPackage.getCompilationUnit(typeName + ".java").exists()) { //$NON-NLS-1$ if ((kind & SimilarElementsRequestor.CLASSES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingPackage, relevance)); } if ((kind & SimilarElementsRequestor.INTERFACES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingPackage, relevance)); } } // new member type if (enclosingType != null && !enclosingType.isReadOnly() && !enclosingType.getType(typeName).exists()) { if ((kind & SimilarElementsRequestor.CLASSES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingType, relevance)); } if ((kind & SimilarElementsRequestor.INTERFACES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingType, relevance)); } } } node= qualifier; } while (node != null); } public static void getMethodProposals(IInvocationContext context, IProblemLocation problem, boolean needsNewName, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (!(selectedNode instanceof SimpleName)) { return; } SimpleName nameNode= (SimpleName) selectedNode; List arguments; Expression sender; boolean isSuperInvocation; ASTNode invocationNode= nameNode.getParent(); if (invocationNode instanceof MethodInvocation) { MethodInvocation methodImpl= (MethodInvocation) invocationNode; arguments= methodImpl.arguments(); sender= methodImpl.getExpression(); isSuperInvocation= false; } else if (invocationNode instanceof SuperMethodInvocation) { SuperMethodInvocation methodImpl= (SuperMethodInvocation) invocationNode; arguments= methodImpl.arguments(); sender= methodImpl.getQualifier(); isSuperInvocation= true; } else { return; } String methodName= nameNode.getIdentifier(); int nArguments= arguments.size(); // corrections IBinding[] bindings= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(nameNode, ScopeAnalyzer.METHODS); ArrayList parameterMismatchs= new ArrayList(); for (int i= 0; i < bindings.length; i++) { IMethodBinding binding= (IMethodBinding) bindings[i]; String curr= binding.getName(); if (curr.equals(methodName) && needsNewName) { parameterMismatchs.add(binding); } else if (binding.getParameterTypes().length == nArguments && NameMatcher.isSimilarName(methodName, curr)) { String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changemethod.description", curr); //$NON-NLS-1$ proposals.add(new RenameNodeCompletionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), curr, 6)); } } addParameterMissmatchProposals(context, problem, parameterMismatchs, invocationNode, arguments, proposals); // new method ITypeBinding binding= null; if (sender != null) { binding= sender.resolveTypeBinding(); } else { binding= Bindings.getBindingOfParentType(invocationNode); if (isSuperInvocation && binding != null) { binding= binding.getSuperclass(); } } if (binding != null && binding.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding); if (targetCU != null) { String label; Image image; String sig= getMethodSignature(methodName, arguments); if (cu.equals(targetCU)) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.description", sig); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE); } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", new Object[] { sig, targetCU.getElementName() } ); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); } proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 5, image)); if (binding.isAnonymous() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(binding, methodName, null) == null) { // no covering method ASTNode anonymDecl= astRoot.findDeclaringNode(binding); if (anonymDecl != null) { binding= Bindings.getBindingOfParentType(anonymDecl.getParent()); if (!binding.isAnonymous()) { String[] args= new String[] { sig, binding.getName() }; label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", args); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED); proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 5, image)); } } } } } if (!isSuperInvocation) { ASTNode parent= invocationNode.getParent(); while (parent instanceof Expression && parent.getNodeType() != ASTNode.CAST_EXPRESSION) { parent= parent.getParent(); } if (!isSuperInvocation && parent instanceof CastExpression) { addMissingCastParentsProposal(cu, (CastExpression) parent, sender, nameNode, getArgumentTypes(arguments), proposals); } } } private static void addMissingCastParentsProposal(ICompilationUnit cu, CastExpression expression, Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes, Collection proposals) { ITypeBinding castType= expression.getType().resolveBinding(); if (castType == null) { return; } if (paramTypes != null) { if (Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes) == null) { return; } } else if (Bindings.findFieldInHierarchy(castType, accessSelector.getIdentifier()) == null) { return; } ITypeBinding bindingToCast= accessExpression.resolveTypeBinding(); if (bindingToCast != null && !TypeRules.canCast(castType, bindingToCast)) { return; } IMethodBinding res= Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes); if (res != null) { AST ast= expression.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); CastExpression newCast= ast.newCastExpression(); newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType())); newCast.setExpression((Expression) rewrite.createCopyTarget(accessExpression)); ParenthesizedExpression parents= ast.newParenthesizedExpression(); parents.setExpression(newCast); ASTNode node= rewrite.createCopyTarget(expression.getExpression()); rewrite.replace(expression, node, null); rewrite.replace(accessExpression, parents, null); String label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.missingcastbrackets.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 8, image); proposals.add(proposal); } } private static void addParameterMissmatchProposals(IInvocationContext context, IProblemLocation problem, List similarElements, ASTNode invocationNode, List arguments, Collection proposals) throws CoreException { int nSimilarElements= similarElements.size(); ITypeBinding[] argTypes= getArgumentTypes(arguments); if (argTypes == null || nSimilarElements == 0) { return; } for (int i= 0; i < nSimilarElements; i++) { IMethodBinding elem = (IMethodBinding) similarElements.get(i); int diff= elem.getParameterTypes().length - argTypes.length; if (diff == 0) { int nProposals= proposals.size(); doEqualNumberOfParameters(context, invocationNode, problem, arguments, argTypes, elem, proposals); if (nProposals != proposals.size()) { return; // only suggest for one method (avoid duplicated proposals) } } else if (diff > 0) { doMoreParameters(context, problem, invocationNode, arguments, argTypes, elem, proposals); } else { doMoreArguments(context, problem, invocationNode, arguments, argTypes, elem, proposals); } } } private static void doMoreParameters(IInvocationContext context, IProblemLocation problem, ASTNode invocationNode, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException { ITypeBinding[] paramTypes= methodBinding.getParameterTypes(); int k= 0, nSkipped= 0; int diff= paramTypes.length - argTypes.length; int[] indexSkipped= new int[diff]; for (int i= 0; i < paramTypes.length; i++) { if (k < argTypes.length && TypeRules.canAssign(argTypes[k], paramTypes[i])) { k++; // match } else { if (nSkipped >= diff) { return; // too different } indexSkipped[nSkipped++]= i; } } ITypeBinding declaringType= methodBinding.getDeclaringClass(); ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); // add arguments { String[] arg= new String[] { getMethodSignature(methodBinding, false) }; String label; if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargument.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addarguments.description", arg); //$NON-NLS-1$ } AddArgumentCorrectionProposal proposal= new AddArgumentCorrectionProposal(label, context.getCompilationUnit(), invocationNode, indexSkipped, paramTypes, 8); proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD)); proposals.add(proposal); } // remove parameters if (!declaringType.isFromSource()) { return; } ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); if (targetCU != null) { ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length]; ITypeBinding[] changedTypes= new ITypeBinding[diff]; for (int i= diff - 1; i >= 0; i--) { int idx= indexSkipped[i]; changeDesc[idx]= new RemoveDescription(); changedTypes[i]= paramTypes[idx]; } String[] arg= new String[] { getMethodSignature(methodBinding, !cu.equals(targetCU)), getTypeNames(changedTypes) }; String label; if (methodBinding.isConstructor()) { if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparam.constr.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparams.constr.description", arg); //$NON-NLS-1$ } } else { if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparam.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparams.description", arg); //$NON-NLS-1$ } } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE); ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, null, 5, image); proposals.add(proposal); } } private static String getTypeNames(ITypeBinding[] types) { StringBuffer buf= new StringBuffer(); for (int i= 0; i < types.length; i++) { if (i > 0) { buf.append(", "); //$NON-NLS-1$ } buf.append(types[i].getName()); } return buf.toString(); } private static String getArgumentName(ICompilationUnit cu, List arguments, int index) { String def= String.valueOf(index + 1); ASTNode expr= (ASTNode) arguments.get(index); if (expr.getLength() > 18) { return def; } try { String str= cu.getBuffer().getText(expr.getStartPosition(), expr.getLength()); for (int i= 0; i < str.length(); i++) { if (Strings.isLineDelimiterChar(str.charAt(i))) { return def; } } ASTMatcher matcher= new ASTMatcher(); for (int i= 0; i < arguments.size(); i++) { if (i != index && matcher.safeSubtreeMatch(expr, arguments.get(i))) { return def; } } return '\'' + str + '\''; } catch (JavaModelException e) { JavaPlugin.log(e); } return def; } private static void doMoreArguments(IInvocationContext context, IProblemLocation problem, ASTNode invocationNode, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException { ITypeBinding[] paramTypes= methodBinding.getParameterTypes(); int k= 0, nSkipped= 0; int diff= argTypes.length - paramTypes.length; int[] indexSkipped= new int[diff]; for (int i= 0; i < argTypes.length; i++) { if (k < paramTypes.length && TypeRules.canAssign(argTypes[i], paramTypes[k])) { k++; // match } else { if (nSkipped >= diff) { return; // too different } indexSkipped[nSkipped++]= i; } } ITypeBinding declaringType= methodBinding.getDeclaringClass(); ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); // remove arguments { ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST()); for (int i= diff - 1; i >= 0; i--) { rewrite.remove((Expression) arguments.get(indexSkipped[i]), null); } String[] arg= new String[] { getMethodSignature(methodBinding, false) }; String label; if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeargument.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removearguments.description", arg); //$NON-NLS-1$ } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image); proposals.add(proposal); } // add parameters if (!declaringType.isFromSource()) { return; } ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); if (targetCU != null) { boolean isDifferentCU= !cu.equals(targetCU); if (isImplicitConstructor(methodBinding, targetCU)) { return; } ChangeDescription[] changeDesc= new ChangeDescription[argTypes.length]; ITypeBinding[] changeTypes= new ITypeBinding[diff]; for (int i= diff - 1; i >= 0; i--) { int idx= indexSkipped[i]; Expression arg= (Expression) arguments.get(idx); String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null; ITypeBinding newType= Bindings.normalizeTypeBinding(argTypes[idx]); if (newType == null) { newType= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } changeDesc[idx]= new InsertDescription(newType, name); changeTypes[i]= newType; } String[] arg= new String[] { getMethodSignature(methodBinding, isDifferentCU), getTypeNames(changeTypes) }; String label; if (methodBinding.isConstructor()) { if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparam.constr.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparams.constr.description", arg); //$NON-NLS-1$ } } else { if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparam.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparams.description", arg); //$NON-NLS-1$ } } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD); ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, null, 5, image); proposals.add(proposal); } } private static boolean isImplicitConstructor(IMethodBinding meth, ICompilationUnit targetCU) { if (meth.isConstructor() && meth.getParameterTypes().length == 0) { IMethodBinding[] bindings= meth.getDeclaringClass().getDeclaredMethods(); // implicit constructors must be the only constructor for (int i= 0; i < bindings.length; i++) { IMethodBinding curr= bindings[i]; if (curr.isConstructor() && curr != meth) { return false; } } ASTParser parser= ASTParser.newParser(AST.JLS2); parser.setSource(targetCU); parser.setFocalPosition(0); parser.setResolveBindings(true); CompilationUnit unit= (CompilationUnit) parser.createAST(null); return unit.findDeclaringNode(meth.getKey()) == null; } return false; } private static String getMethodSignature(IMethodBinding binding, boolean inOtherCU) { StringBuffer buf= new StringBuffer(); if (inOtherCU && !binding.isConstructor()) { buf.append(binding.getDeclaringClass().getName()).append('.'); } buf.append(binding.getName()); return getMethodSignature(buf.toString(), binding.getParameterTypes()); } private static String getMethodSignature(String name, List args) { ITypeBinding[] params= new ITypeBinding[args.size()]; for (int i= 0; i < args.size(); i++) { Expression expr= (Expression) args.get(i); ITypeBinding curr= Bindings.normalizeTypeBinding(expr.resolveTypeBinding()); if (curr == null) { curr= expr.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } params[i]= curr; } return getMethodSignature(name, params); } private static String getMethodSignature(String name, ITypeBinding[] params) { StringBuffer buf= new StringBuffer(); buf.append(name).append('('); for (int i= 0; i < params.length; i++) { if (i > 0) { buf.append(", "); //$NON-NLS-1$ } buf.append(params[i].getName()); } buf.append(')'); return buf.toString(); } private static void doEqualNumberOfParameters(IInvocationContext context, ASTNode invocationNode, IProblemLocation problem, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException { ITypeBinding[] paramTypes= methodBinding.getParameterTypes(); int[] indexOfDiff= new int[paramTypes.length]; int nDiffs= 0; for (int n= 0; n < argTypes.length; n++) { if (!TypeRules.canAssign(argTypes[n], paramTypes[n])) { indexOfDiff[nDiffs++]= n; } } ITypeBinding declaringType= methodBinding.getDeclaringClass(); ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode nameNode= problem.getCoveringNode(astRoot); if (nameNode == null) { return; } if (nDiffs == 0) { if (nameNode.getParent() instanceof MethodInvocation) { MethodInvocation inv= (MethodInvocation) nameNode.getParent(); if (inv.getExpression() == null) { addQualifierToOuterProposal(context, inv, methodBinding, proposals); } } return; } if (nDiffs == 1) { // one argument mismatching: try to fix int idx= indexOfDiff[0]; Expression nodeToCast= (Expression) arguments.get(idx); ITypeBinding castType= paramTypes[idx]; ITypeBinding binding= nodeToCast.resolveTypeBinding(); if (binding == null || TypeRules.canCast(castType, binding)) { String castTypeName= castType.getQualifiedName(); ASTRewriteCorrectionProposal proposal= TypeMismatchSubProcessor.createCastProposal(context, castTypeName, nodeToCast, 6); String[] arg= new String[] { getArgumentName(cu, arguments, idx), castTypeName}; proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargumentcast.description", arg)); //$NON-NLS-1$ proposals.add(proposal); } TypeMismatchSubProcessor.addChangeSenderTypeProposals(context, nodeToCast, castType, false, 5, proposals); } if (nDiffs == 2) { // try to swap int idx1= indexOfDiff[0]; int idx2= indexOfDiff[1]; boolean canSwap= TypeRules.canAssign(argTypes[idx1], paramTypes[idx2]) && TypeRules.canAssign(argTypes[idx2], paramTypes[idx1]); if (canSwap) { Expression arg1= (Expression) arguments.get(idx1); Expression arg2= (Expression) arguments.get(idx2); ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST()); rewrite.replace(arg1, rewrite.createCopyTarget(arg2), null); rewrite.replace(arg2, rewrite.createCopyTarget(arg1), null); { String[] arg= new String[] { getArgumentName(cu, arguments, idx1), getArgumentName(cu, arguments, idx2) }; String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swaparguments.description", arg); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image); proposals.add(proposal); } if (declaringType.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); if (targetCU != null) { ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length]; for (int i= 0; i < nDiffs; i++) { changeDesc[idx1]= new SwapDescription(idx2); } ITypeBinding[] swappedTypes= new ITypeBinding[] { paramTypes[idx1], paramTypes[idx2] }; String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getTypeNames(swappedTypes) }; String label; if (methodBinding.isConstructor()) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swapparams.constr.description", args); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swapparams.description", args); //$NON-NLS-1$ } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, null, 5, image); proposals.add(proposal); } } return; } } if (declaringType.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); if (targetCU != null) { ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length]; for (int i= 0; i < nDiffs; i++) { int diffIndex= indexOfDiff[i]; Expression arg= (Expression) arguments.get(diffIndex); String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null; changeDesc[diffIndex]= new EditDescription(argTypes[diffIndex], name); } String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getMethodSignature(methodBinding.getName(), arguments) }; String label; if (methodBinding.isConstructor()) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changeparamsignature.constr.description", args); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changeparamsignature.description", args); //$NON-NLS-1$ } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, null, 7, image); proposals.add(proposal); } } } private static ITypeBinding[] getArgumentTypes(List arguments) { ITypeBinding[] res= new ITypeBinding[arguments.size()]; for (int i= 0; i < res.length; i++) { Expression expression= (Expression) arguments.get(i); ITypeBinding curr= expression.resolveTypeBinding(); if (curr == null) { return null; } curr= Bindings.normalizeTypeBinding(curr); if (curr == null) { curr= expression.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } res[i]= curr; } return res; } private static void addQualifierToOuterProposal(IInvocationContext context, MethodInvocation invocationNode, IMethodBinding binding, Collection proposals) throws CoreException { ITypeBinding declaringType= binding.getDeclaringClass(); ITypeBinding parentType= Bindings.getBindingOfParentType(invocationNode); ITypeBinding currType= parentType; boolean isInstanceMethod= !Modifier.isStatic(binding.getModifiers()); while (currType != null && !Bindings.isSuperType(declaringType, currType)) { if (isInstanceMethod && Modifier.isStatic(currType.getModifiers())) { return; } currType= currType.getDeclaringClass(); } if (currType == null || currType == parentType) { return; } ASTRewrite rewrite= ASTRewrite.create(invocationNode.getAST()); ImportRewrite imports= new ImportRewrite(context.getCompilationUnit()); AST ast= invocationNode.getAST(); String qualifier= imports.addImport(currType); Name name= ASTNodeFactory.newName(ast, qualifier); Expression newExpression; if (isInstanceMethod) { ThisExpression expr= ast.newThisExpression(); expr.setQualifier(name); newExpression= expr; } else { newExpression= name; } rewrite.set(invocationNode, MethodInvocation.EXPRESSION_PROPERTY, newExpression, null); String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetoouter.description", currType.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image); proposal.setImportRewrite(imports); proposals.add(proposal); } public static void getConstructorProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (selectedNode == null) { return; } ITypeBinding targetBinding= null; List arguments= null; IMethodBinding recursiveConstructor= null; int type= selectedNode.getNodeType(); if (type == ASTNode.CLASS_INSTANCE_CREATION) { ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode; IBinding binding= creation.getName().resolveBinding(); if (binding instanceof ITypeBinding) { targetBinding= (ITypeBinding) binding; arguments= creation.arguments(); } } else if (type == ASTNode.SUPER_CONSTRUCTOR_INVOCATION) { ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode); if (typeBinding != null && !typeBinding.isAnonymous()) { targetBinding= typeBinding.getSuperclass(); arguments= ((SuperConstructorInvocation) selectedNode).arguments(); } } else if (type == ASTNode.CONSTRUCTOR_INVOCATION) { ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode); if (typeBinding != null && !typeBinding.isAnonymous()) { targetBinding= typeBinding; arguments= ((ConstructorInvocation) selectedNode).arguments(); recursiveConstructor= ASTResolving.findParentMethodDeclaration(selectedNode).resolveBinding(); } } if (targetBinding == null) { return; } IMethodBinding[] methods= targetBinding.getDeclaredMethods(); ArrayList similarElements= new ArrayList(); for (int i= 0; i < methods.length; i++) { IMethodBinding curr= methods[i]; if (curr.isConstructor() && recursiveConstructor != curr) { similarElements.add(curr); // similar elements can contain a implicit default constructor } } addParameterMissmatchProposals(context, problem, similarElements, selectedNode, arguments, proposals); if (targetBinding.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, targetBinding); if (targetCU != null) { String[] args= new String[] { getMethodSignature( targetBinding.getName(), arguments) }; String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconstructor.description", args); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); proposals.add(new NewMethodCompletionProposal(label, targetCU, selectedNode, arguments, targetBinding, 5, image)); } } } public static void getAmbiguosTypeReferenceProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { final ICompilationUnit cu= context.getCompilationUnit(); int offset= problem.getOffset(); int len= problem.getLength(); IJavaElement[] elements= cu.codeSelect(offset, len); for (int i= 0; i < elements.length; i++) { IJavaElement curr= elements[i]; if (curr instanceof IType && !TypeFilter.isFiltered((IType) curr)) { String qualifiedTypeName= JavaModelUtil.getFullyQualifiedName((IType) curr); ImportRewrite imports= new ImportRewrite(cu); imports.setFindAmbiguosImports(true); imports.addImport(qualifiedTypeName); String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importexplicit.description", qualifiedTypeName); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL); CUCorrectionProposal proposal= new CUCorrectionProposal(label, cu, 5, image); proposal.setImportRewrite(imports); proposals.add(proposal); } } } }
61,286
Bug 61286 StringOutOfBoundsException during NLS search
Build id: 200404281424 I did an NLS search with Resource bundle accessor class: org.eclipse.ui.internal.WorkbenchMessages Property file name: /org.eclipse.ui.workbench/Eclipse UI/org/eclipse/ui/internal/messages.properties Some results are reported in the Search view, but there was an error dialog and I found the following exception in the log file: !MESSAGE An internal error occurred during: "Search for broken NLS keys". !STACK 0 java.lang.StringIndexOutOfBoundsException: String index out of range: -44 at java.lang.String.substring(Unknown Source) at java.lang.String.substring(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.nls.search. NLSSearchResultRequestor.findKey(NLSSearchResultRequestor.java:155) at org.eclipse.jdt.internal.ui.refactoring.nls.search. NLSSearchResultRequestor.acceptSearchMatch(NLSSearchResultRequestor.java:96) at org.eclipse.jdt.internal.core.search.matching.MatchLocator. report(MatchLocator.java:1168) at org.eclipse.jdt.internal.core.search.matching.TypeReferenceLocator. matchReportImportRef(TypeReferenceLocator.java:143) at org.eclipse.jdt.internal.core.search.matching.PatternLocator. matchLevelAndReportImportRef(PatternLocator.java:207) at org.eclipse.jdt.internal.core.search.matching.MatchLocator. reportMatching(MatchLocator.java:1378) at org.eclipse.jdt.internal.core.search.matching.MatchLocator. process(MatchLocator.java:1101) at org.eclipse.jdt.internal.core.search.matching.MatchLocator. locateMatches(MatchLocator.java:739) at org.eclipse.jdt.internal.core.search.matching.MatchLocator. locateMatches(MatchLocator.java:770) at org.eclipse.jdt.internal.core.search.matching.MatchLocator. locateMatches(MatchLocator.java:867) at org.eclipse.jdt.internal.core.search.JavaSearchParticipant. locateMatches(JavaSearchParticipant.java:94) at org.eclipse.jdt.core.search.SearchEngine.findMatches(SearchEngine.java: 468) at org.eclipse.jdt.core.search.SearchEngine.search(SearchEngine.java:760) at org.eclipse.jdt.internal.ui.refactoring.nls.search.NLSSearchQuery. run(NLSSearchQuery.java:67) at org.eclipse.search2.internal.ui.InternalSearchUI$InternalSearchJob. run(InternalSearchUI.java:71) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:66)
resolved fixed
24f6cb7
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T10:23:56Z
2004-05-06T19:00:00Z
org.eclipse.jdt.ui/ui
61,286
Bug 61286 StringOutOfBoundsException during NLS search
Build id: 200404281424 I did an NLS search with Resource bundle accessor class: org.eclipse.ui.internal.WorkbenchMessages Property file name: /org.eclipse.ui.workbench/Eclipse UI/org/eclipse/ui/internal/messages.properties Some results are reported in the Search view, but there was an error dialog and I found the following exception in the log file: !MESSAGE An internal error occurred during: "Search for broken NLS keys". !STACK 0 java.lang.StringIndexOutOfBoundsException: String index out of range: -44 at java.lang.String.substring(Unknown Source) at java.lang.String.substring(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.nls.search. NLSSearchResultRequestor.findKey(NLSSearchResultRequestor.java:155) at org.eclipse.jdt.internal.ui.refactoring.nls.search. NLSSearchResultRequestor.acceptSearchMatch(NLSSearchResultRequestor.java:96) at org.eclipse.jdt.internal.core.search.matching.MatchLocator. report(MatchLocator.java:1168) at org.eclipse.jdt.internal.core.search.matching.TypeReferenceLocator. matchReportImportRef(TypeReferenceLocator.java:143) at org.eclipse.jdt.internal.core.search.matching.PatternLocator. matchLevelAndReportImportRef(PatternLocator.java:207) at org.eclipse.jdt.internal.core.search.matching.MatchLocator. reportMatching(MatchLocator.java:1378) at org.eclipse.jdt.internal.core.search.matching.MatchLocator. process(MatchLocator.java:1101) at org.eclipse.jdt.internal.core.search.matching.MatchLocator. locateMatches(MatchLocator.java:739) at org.eclipse.jdt.internal.core.search.matching.MatchLocator. locateMatches(MatchLocator.java:770) at org.eclipse.jdt.internal.core.search.matching.MatchLocator. locateMatches(MatchLocator.java:867) at org.eclipse.jdt.internal.core.search.JavaSearchParticipant. locateMatches(JavaSearchParticipant.java:94) at org.eclipse.jdt.core.search.SearchEngine.findMatches(SearchEngine.java: 468) at org.eclipse.jdt.core.search.SearchEngine.search(SearchEngine.java:760) at org.eclipse.jdt.internal.ui.refactoring.nls.search.NLSSearchQuery. run(NLSSearchQuery.java:67) at org.eclipse.search2.internal.ui.InternalSearchUI$InternalSearchJob. run(InternalSearchUI.java:71) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:66)
resolved fixed
24f6cb7
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T10:23:56Z
2004-05-06T19:00:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/nls/search/NLSSearchResultRequestor.java
38,482
Bug 38482 Alignment problem in Java Editor pref page
I20030604 Incorrect alignment of radio buttons and color chooser button (see attached screenshot).
resolved fixed
659c552
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T10:58:47Z
2003-06-05T10:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorPreferencePage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Preferences; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.IColorProvider; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchViewerSorter; import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.ChainedPreferenceStore; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer; import org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlighting; import org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightingManager; import org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightings; import org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightingManager.HighlightedRange; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.PreferencesAdapter; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; /** * The page for setting the editor options. */ public class JavaEditorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { /** * Item in the highlighting color list. * * @since 3.0 */ private class HighlightingColorListItem { /** Display name */ private String fDisplayName; /** Color preference key */ private String fColorKey; /** Bold preference key */ private String fBoldKey; /** Italic preference key */ private String fItalicKey; /** Item color */ private Color fItemColor; /** * Initialize the item with the given values. * * @param displayName the display name * @param colorKey the color preference key * @param boldKey the bold preference key * @param italicKey the italic preference key * @param itemColor the item color */ public HighlightingColorListItem(String displayName, String colorKey, String boldKey, String italicKey, Color itemColor) { fDisplayName= displayName; fColorKey= colorKey; fBoldKey= boldKey; fItalicKey= italicKey; fItemColor= itemColor; } /** * @return the bold preference key */ public String getBoldKey() { return fBoldKey; } /** * @return the bold preference key */ public String getItalicKey() { return fItalicKey; } /** * @return the color preference key */ public String getColorKey() { return fColorKey; } /** * @return the display name */ public String getDisplayName() { return fDisplayName; } /** * @return the item color */ public Color getItemColor() { return fItemColor; } } /** * Color list label provider. * * @since 3.0 */ private class ColorListLabelProvider extends LabelProvider implements IColorProvider { /* * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) */ public String getText(Object element) { return ((HighlightingColorListItem)element).getDisplayName(); } /* * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object) */ public Color getForeground(Object element) { return ((HighlightingColorListItem)element).getItemColor(); } /* * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object) */ public Color getBackground(Object element) { return null; } } /** * Color list content provider. * * @since 3.0 */ private class ColorListContentProvider implements IStructuredContentProvider { /* * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) */ public Object[] getElements(Object inputElement) { return ((java.util.List)inputElement).toArray(); } /* * @see org.eclipse.jface.viewers.IContentProvider#dispose() */ public void dispose() { } /* * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object) */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } } private static final String BOLD= PreferenceConstants.EDITOR_BOLD_SUFFIX; /** * Preference key suffix for italic preferences. * @since 3.0 */ private static final String ITALIC= PreferenceConstants.EDITOR_ITALIC_SUFFIX; private static final String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS; private static final String DELIMITER= PreferencesMessages.getString("JavaEditorPreferencePage.navigation.delimiter"); //$NON-NLS-1$ /** The keys of the overlay store. */ private final String[][] fSyntaxColorListModel= new String[][] { { PreferencesMessages.getString("JavaEditorPreferencePage.multiLineComment"), PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.singleLineComment"), PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.returnKeyword"), PreferenceConstants.EDITOR_JAVA_KEYWORD_RETURN_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.keywords"), PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.strings"), PreferenceConstants.EDITOR_STRING_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.methodNames"), PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.operators"), PreferenceConstants.EDITOR_JAVA_OPERATOR_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.others"), PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaCommentTaskTags"), PreferenceConstants.EDITOR_TASK_TAG_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocKeywords"), PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocHtmlTags"), PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocLinks"), PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocOthers"), PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR } //$NON-NLS-1$ }; private final String[][] fAppearanceColorListModel= new String[][] { {PreferencesMessages.getString("JavaEditorPreferencePage.lineNumberForegroundColor"), AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR, null}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.matchingBracketsHighlightColor2"), PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, null}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.currentLineHighlighColor"), AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR, null}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.printMarginColor2"), AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR, null}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.findScopeColor2"), PreferenceConstants.EDITOR_FIND_SCOPE_COLOR, null}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.linkColor2"), PreferenceConstants.EDITOR_LINK_COLOR, null}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.selectionForegroundColor"), AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_DEFAULT_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.selectionBackgroundColor"), AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_DEFAULT_COLOR}, //$NON-NLS-1$ }; private OverlayPreferenceStore fOverlayStore; private JavaEditorHoverConfigurationBlock fJavaEditorHoverConfigurationBlock; private FoldingConfigurationBlock fFoldingConfigurationBlock; private Map fColorButtons= new HashMap(); private Map fCheckBoxes= new HashMap(); private SelectionListener fCheckBoxListener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { Button button= (Button) e.widget; fOverlayStore.setValue((String) fCheckBoxes.get(button), button.getSelection()); } }; private Map fTextFields= new HashMap(); private ModifyListener fTextFieldListener= new ModifyListener() { public void modifyText(ModifyEvent e) { Text text= (Text) e.widget; fOverlayStore.setValue((String) fTextFields.get(text), text.getText()); } }; private ArrayList fNumberFields= new ArrayList(); private ModifyListener fNumberFieldListener= new ModifyListener() { public void modifyText(ModifyEvent e) { numberFieldChanged((Text) e.widget); } }; private List fAppearanceColorList; private ColorEditor fSyntaxForegroundColorEditor; private ColorEditor fAppearanceColorEditor; private Button fAppearanceColorDefault; private ColorEditor fBackgroundColorEditor; private Button fBackgroundDefaultRadioButton; private Button fBackgroundCustomRadioButton; private Button fBackgroundColorButton; private Button fBoldCheckBox; /** * Check box for italic preference. * @since 3.0 */ private Button fItalicCheckBox; private JavaSourceViewer fPreviewViewer; private Color fBackgroundColor; private Text fBrowserLikeLinksKeyModifierText; private Button fBrowserLikeLinksCheckBox; private StatusInfo fBrowserLikeLinksKeyModifierStatus; /** * Tells whether the fields are initialized. * @since 3.0 */ private boolean fFieldsInitialized= false; /** * List of master/slave listeners when there's a dependency. * * @see #createDependency(Button, String, Control) * @since 3.0 */ private ArrayList fMasterSlaveListeners= new ArrayList(); /** * Highlighting color list * @since 3.0 */ private final java.util.List fHighlightingColorList= new ArrayList(); /** * Highlighting color list viewer * @since 3.0 */ private TableViewer fHighlightingColorListViewer; /** * Color of Semantic Highlighting items in color list (RGB) * @since 3.0 */ private static final int[] SEMANTIC_HIGHLIGHTING_ITEM_COLOR= new int[] { 0, 0, 0x80 }; /** * Semantic Highlighting color list * @since 3.0 */ private java.util.List fSemanticHighlightingColorList= new ArrayList(); /** * Semantic highlighting manager * @since 3.0 */ private SemanticHighlightingManager fSemanticHighlightingManager; /** * Semantic highlighting check-box * @since 3.0 */ private Button fSemanticHighlightingEnabled; /** * Creates a new preference page. */ public JavaEditorPreferencePage() { setDescription(PreferencesMessages.getString("JavaEditorPreferencePage.description")); //$NON-NLS-1$ setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); Color itemColor= JavaPlugin.getDefault().getJavaTextTools().getColorManager().getColor(new RGB(SEMANTIC_HIGHLIGHTING_ITEM_COLOR[0], SEMANTIC_HIGHLIGHTING_ITEM_COLOR[1], SEMANTIC_HIGHLIGHTING_ITEM_COLOR[2])); SemanticHighlighting[] semanticHighlightings= SemanticHighlightings.getSemanticHighlightings(); for (int i= 0, n= semanticHighlightings.length; i < n; i++) fSemanticHighlightingColorList.add(new HighlightingColorListItem(semanticHighlightings[i].getDisplayName(), SemanticHighlightings.getColorPreferenceKey(semanticHighlightings[i]), SemanticHighlightings.getBoldPreferenceKey(semanticHighlightings[i]), SemanticHighlightings.getItalicPreferenceKey(semanticHighlightings[i]), itemColor)); fOverlayStore= new OverlayPreferenceStore(getPreferenceStore(), createOverlayStoreKeys()); } private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() { ArrayList overlayKeys= new ArrayList(); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_FOREGROUND_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_BACKGROUND_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_DEFAULT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_DEFAULT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH)); for (int i= 0; i < fSyntaxColorListModel.length; i++) { String colorKey= fSyntaxColorListModel[i][1]; overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, colorKey)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, colorKey + BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, colorKey + ITALIC)); } overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MATCHING_BRACKETS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_USE_CUSTOM_CARETS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_WIDE_CARET)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_QUICKASSIST_LIGHTBULB)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_FIND_SCOPE_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_LINK_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CORRECTION_INDICATION)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SPACES_FOR_TABS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_PASTE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_IMPORTS_ON_PASTE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_STRINGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_BRACKETS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_BRACES)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_JAVADOCS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_WRAP_STRINGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_ESCAPE_STRINGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_HOME_END)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_SEMICOLON)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_TAB)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_OPENING_BRACE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED)); for (int i= 0, n= fSemanticHighlightingColorList.size(); i < n; i++) { HighlightingColorListItem item= (HighlightingColorListItem) fSemanticHighlightingColorList.get(i); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, item.getColorKey())); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, item.getBoldKey())); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, item.getItalicKey())); } OverlayPreferenceStore.OverlayKey[] keys= new OverlayPreferenceStore.OverlayKey[overlayKeys.size()]; overlayKeys.toArray(keys); return keys; } /* * @see IWorkbenchPreferencePage#init() */ public void init(IWorkbench workbench) { } /* * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); } private void handleSyntaxColorListSelection() { HighlightingColorListItem item= getHighlightingColorListItem(); RGB rgb= PreferenceConverter.getColor(fOverlayStore, item.getColorKey()); fSyntaxForegroundColorEditor.setColorValue(rgb); fBoldCheckBox.setSelection(fOverlayStore.getBoolean(item.getBoldKey())); fItalicCheckBox.setSelection(fOverlayStore.getBoolean(item.getItalicKey())); } private void handleAppearanceColorListSelection() { int i= fAppearanceColorList.getSelectionIndex(); String key= fAppearanceColorListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fAppearanceColorEditor.setColorValue(rgb); updateAppearanceColorWidgets(fAppearanceColorListModel[i][2]); } private void updateAppearanceColorWidgets(String systemDefaultKey) { if (systemDefaultKey == null) { fAppearanceColorDefault.setSelection(false); fAppearanceColorDefault.setVisible(false); fAppearanceColorEditor.getButton().setEnabled(true); } else { boolean systemDefault= fOverlayStore.getBoolean(systemDefaultKey); fAppearanceColorDefault.setSelection(systemDefault); fAppearanceColorDefault.setVisible(true); fAppearanceColorEditor.getButton().setEnabled(!systemDefault); } } private Control createSyntaxPage(Composite parent) { Composite colorComposite= new Composite(parent, SWT.NULL); colorComposite.setLayout(new GridLayout()); Group backgroundComposite= new Group(colorComposite, SWT.SHADOW_ETCHED_IN); backgroundComposite.setLayout(new RowLayout()); backgroundComposite.setText(PreferencesMessages.getString("JavaEditorPreferencePage.backgroundColor"));//$NON-NLS-1$ SelectionListener backgroundSelectionListener= new SelectionListener() { public void widgetSelected(SelectionEvent e) { boolean custom= fBackgroundCustomRadioButton.getSelection(); fBackgroundColorButton.setEnabled(custom); fOverlayStore.setValue(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, !custom); } public void widgetDefaultSelected(SelectionEvent e) {} }; fBackgroundDefaultRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); fBackgroundDefaultRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.systemDefault")); //$NON-NLS-1$ fBackgroundDefaultRadioButton.addSelectionListener(backgroundSelectionListener); fBackgroundCustomRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); fBackgroundCustomRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.custom")); //$NON-NLS-1$ fBackgroundCustomRadioButton.addSelectionListener(backgroundSelectionListener); fBackgroundColorEditor= new ColorEditor(backgroundComposite); fBackgroundColorButton= fBackgroundColorEditor.getButton(); fSemanticHighlightingEnabled= addCheckBox(colorComposite, PreferencesMessages.getString("JavaEditorPreferencePage.semanticHighlighting.option"), PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED, 0); //$NON-NLS-1$ fSemanticHighlightingEnabled.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { fHighlightingColorListViewer.getControl().setRedraw(false); if (fSemanticHighlightingEnabled.getSelection()) { fHighlightingColorList.addAll(fSemanticHighlightingColorList); fHighlightingColorListViewer.add(fSemanticHighlightingColorList.toArray()); } else { int fullSize= fHighlightingColorList.size(); fHighlightingColorList.removeAll(fSemanticHighlightingColorList); HighlightingColorListItem item= getHighlightingColorListItem(); if (!fHighlightingColorList.contains(item)) { int i= 0; while (item != fHighlightingColorListViewer.getElementAt(i)) i++; while (!fHighlightingColorList.contains(fHighlightingColorListViewer.getElementAt(i)) && i < fullSize) i++; while (!fHighlightingColorList.contains(fHighlightingColorListViewer.getElementAt(i)) && i >= 0) i--; // Assume non-empty list fHighlightingColorListViewer.setSelection(new StructuredSelection(fHighlightingColorListViewer.getElementAt(i))); } fHighlightingColorListViewer.remove(fSemanticHighlightingColorList.toArray()); } fHighlightingColorListViewer.getControl().setRedraw(true); fHighlightingColorListViewer.reveal(getHighlightingColorListItem()); } }); Label label= new Label(colorComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.foreground")); //$NON-NLS-1$ label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Composite editorComposite= new Composite(colorComposite, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); GridData gd= new GridData(GridData.FILL_BOTH); editorComposite.setLayoutData(gd); fHighlightingColorListViewer= new TableViewer(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); fHighlightingColorListViewer.setLabelProvider(new ColorListLabelProvider()); fHighlightingColorListViewer.setContentProvider(new ColorListContentProvider()); fHighlightingColorListViewer.setSorter(new WorkbenchViewerSorter()); gd= new GridData(GridData.FILL_BOTH); gd.heightHint= convertHeightInCharsToPixels(5); fHighlightingColorListViewer.getControl().setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); label= new Label(stylesComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; label.setLayoutData(gd); fSyntaxForegroundColorEditor= new ColorEditor(stylesComposite); Button foregroundColorButton= fSyntaxForegroundColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; foregroundColorButton.setLayoutData(gd); fBoldCheckBox= new Button(stylesComposite, SWT.CHECK); fBoldCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.bold")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fBoldCheckBox.setLayoutData(gd); fItalicCheckBox= new Button(stylesComposite, SWT.CHECK); fItalicCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.italic")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fItalicCheckBox.setLayoutData(gd); label= new Label(colorComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.preview")); //$NON-NLS-1$ label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Control previewer= createPreviewer(colorComposite); gd= new GridData(GridData.FILL_BOTH); gd.widthHint= convertWidthInCharsToPixels(20); gd.heightHint= convertHeightInCharsToPixels(5); previewer.setLayoutData(gd); fHighlightingColorListViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { handleSyntaxColorListSelection(); } }); foregroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { HighlightingColorListItem item= getHighlightingColorListItem(); PreferenceConverter.setValue(fOverlayStore, item.getColorKey(), fSyntaxForegroundColorEditor.getColorValue()); } }); fBackgroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { PreferenceConverter.setValue(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR, fBackgroundColorEditor.getColorValue()); } }); fBoldCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { HighlightingColorListItem item= getHighlightingColorListItem(); fOverlayStore.setValue(item.getBoldKey(), fBoldCheckBox.getSelection()); } }); fItalicCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { HighlightingColorListItem item= getHighlightingColorListItem(); fOverlayStore.setValue(item.getItalicKey(), fItalicCheckBox.getSelection()); } }); return colorComposite; } private Control createPreviewer(Composite parent) { IPreferenceStore store= new ChainedPreferenceStore(new IPreferenceStore[] { fOverlayStore, new PreferencesAdapter(createTemporaryCorePreferenceStore()) }); fPreviewViewer= new JavaSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER, store); JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools(); JavaSourceViewerConfiguration configuration= new JavaSourceViewerConfiguration(tools.getColorManager(), store, null, IJavaPartitions.JAVA_PARTITIONING); fPreviewViewer.configure(configuration); Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT); fPreviewViewer.getTextWidget().setFont(font); new JavaSourcePreviewerUpdater(fPreviewViewer, configuration, store); fPreviewViewer.setEditable(false); String content= loadPreviewContentFromFile("ColorSettingPreviewCode.txt"); //$NON-NLS-1$ IDocument document= new Document(content); tools.setupJavaDocumentPartitioner(document, IJavaPartitions.JAVA_PARTITIONING); fPreviewViewer.setDocument(document); installSemanticHighlighting(); return fPreviewViewer.getControl(); } private Preferences createTemporaryCorePreferenceStore() { Preferences result= new Preferences(); result.setValue(COMPILER_TASK_TAGS, "TASK,TODO"); //$NON-NLS-1$ return result; } private Control createAppearancePage(Composite parent) { Composite appearanceComposite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; appearanceComposite.setLayout(layout); String label= PreferencesMessages.getString("JavaEditorPreferencePage.displayedTabWidth"); //$NON-NLS-1$ addTextField(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH, 3, 0, true); label= PreferencesMessages.getString("JavaEditorPreferencePage.printMarginColumn"); //$NON-NLS-1$ addTextField(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 3, 0, true); label= PreferencesMessages.getString("JavaEditorPreferencePage.showOverviewRuler"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.showLineNumbers"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.highlightMatchingBrackets"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_MATCHING_BRACKETS, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.highlightCurrentLine"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.showPrintMargin"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.quickassist.lightbulb"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_QUICKASSIST_LIGHTBULB, 0); //$NON-NLS-1$ label= PreferencesMessages.getString("JavaEditorPreferencePage.showQuickFixables"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_CORRECTION_INDICATION, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.accessibility.disableCustomCarets"); //$NON-NLS-1$ Button master= addCheckBox(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_USE_CUSTOM_CARETS, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.accessibility.wideCaret"); //$NON-NLS-1$ Button slave= addCheckBox(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_WIDE_CARET, 0); createDependency(master, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_USE_CUSTOM_CARETS, slave); Label l= new Label(appearanceComposite, SWT.LEFT ); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; l.setLayoutData(gd); l= new Label(appearanceComposite, SWT.LEFT); l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.appearanceOptions")); //$NON-NLS-1$ gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; l.setLayoutData(gd); Composite editorComposite= new Composite(appearanceComposite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); gd.horizontalSpan= 2; editorComposite.setLayoutData(gd); fAppearanceColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); gd.heightHint= convertHeightInCharsToPixels(8); fAppearanceColorList.setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); l= new Label(stylesComposite, SWT.LEFT); l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; l.setLayoutData(gd); fAppearanceColorEditor= new ColorEditor(stylesComposite); Button foregroundColorButton= fAppearanceColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; foregroundColorButton.setLayoutData(gd); SelectionListener colorDefaultSelectionListener= new SelectionListener() { public void widgetSelected(SelectionEvent e) { boolean systemDefault= fAppearanceColorDefault.getSelection(); fAppearanceColorEditor.getButton().setEnabled(!systemDefault); int i= fAppearanceColorList.getSelectionIndex(); String key= fAppearanceColorListModel[i][2]; if (key != null) fOverlayStore.setValue(key, systemDefault); } public void widgetDefaultSelected(SelectionEvent e) {} }; fAppearanceColorDefault= new Button(stylesComposite, SWT.CHECK); fAppearanceColorDefault.setText(PreferencesMessages.getString("JavaEditorPreferencePage.systemDefault")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fAppearanceColorDefault.setLayoutData(gd); fAppearanceColorDefault.setVisible(false); fAppearanceColorDefault.addSelectionListener(colorDefaultSelectionListener); fAppearanceColorList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleAppearanceColorListSelection(); } }); foregroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAppearanceColorList.getSelectionIndex(); String key= fAppearanceColorListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fAppearanceColorEditor.getColorValue()); } }); return appearanceComposite; } private Control createTypingPage(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 1; composite.setLayout(layout); String label= PreferencesMessages.getString("JavaEditorPreferencePage.analyseAnnotationsWhileTyping"); //$NON-NLS-1$ addCheckBox(composite, label, PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, 0); addFiller(composite); label= PreferencesMessages.getString("JavaEditorPreferencePage.overwriteMode"); //$NON-NLS-1$ addCheckBox(composite, label, PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE, 1); addFiller(composite); Group group= new Group(composite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; group.setLayout(layout); group.setText(PreferencesMessages.getString("JavaEditorPreferencePage.typing.description")); //$NON-NLS-1$ label= PreferencesMessages.getString("JavaEditorPreferencePage.wrapStrings"); //$NON-NLS-1$ Button master= addCheckBox(group, label, PreferenceConstants.EDITOR_WRAP_STRINGS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.escapeStrings"); //$NON-NLS-1$ Button slave= addCheckBox(group, label, PreferenceConstants.EDITOR_ESCAPE_STRINGS, 1); createDependency(master, PreferenceConstants.EDITOR_WRAP_STRINGS, slave); label= PreferencesMessages.getString("JavaEditorPreferencePage.smartPaste"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_SMART_PASTE, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.importsOnPaste"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_IMPORTS_ON_PASTE, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.insertSpaceForTabs"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_SPACES_FOR_TABS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeStrings"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_STRINGS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeBrackets"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_BRACKETS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeBraces"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_BRACES, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeJavaDocs"); //$NON-NLS-1$ master= addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_JAVADOCS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.addJavaDocTags"); //$NON-NLS-1$ slave= addCheckBox(group, label, PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, 1); createDependency(master, PreferenceConstants.EDITOR_CLOSE_JAVADOCS, slave); label= PreferencesMessages.getString("JavaEditorPreferencePage.typing.smartSemicolon"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_SMART_SEMICOLON, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.typing.smartOpeningBrace"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_SMART_OPENING_BRACE, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.typing.smartTab"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_SMART_TAB, 1); // label= PreferencesMessages.getString("JavaEditorPreferencePage.formatJavaDocs"); //$NON-NLS-1$ // addCheckBox(group, label, PreferenceConstants.EDITOR_FORMAT_JAVADOCS, 1); return composite; } private void addFiller(Composite composite) { Label filler= new Label(composite, SWT.LEFT ); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; filler.setLayoutData(gd); } private static void indent(Control control) { GridData gridData= new GridData(); gridData.horizontalIndent= 20; control.setLayoutData(gridData); } private void createDependency(final Button master, String masterKey, final Control slave) { indent(slave); boolean masterState= fOverlayStore.getBoolean(masterKey); slave.setEnabled(masterState); SelectionListener listener= new SelectionListener() { public void widgetSelected(SelectionEvent e) { slave.setEnabled(master.getSelection()); } public void widgetDefaultSelected(SelectionEvent e) {} }; master.addSelectionListener(listener); fMasterSlaveListeners.add(listener); } private Control createNavigationPage(Composite parent) { Composite composite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; composite.setLayout(layout); String label= PreferencesMessages.getString("JavaEditorPreferencePage.smartHomeEnd"); //$NON-NLS-1$ addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_HOME_END, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.subWordNavigation"); //$NON-NLS-1$ addCheckBox(composite, label, PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, 1); addFiller(composite); label= PreferencesMessages.getString("JavaEditorPreferencePage.navigation.browserLikeLinks"); //$NON-NLS-1$ fBrowserLikeLinksCheckBox= addCheckBox(composite, label, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, 0); fBrowserLikeLinksCheckBox.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { boolean state= fBrowserLikeLinksCheckBox.getSelection(); fBrowserLikeLinksKeyModifierText.setEnabled(state); handleBrowserLikeLinksKeyModifierModified(); } public void widgetDefaultSelected(SelectionEvent e) { } }); // Text field for modifier string label= PreferencesMessages.getString("JavaEditorPreferencePage.navigation.browserLikeLinksKeyModifier"); //$NON-NLS-1$ fBrowserLikeLinksKeyModifierText= addTextField(composite, label, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, 20, 0, false); fBrowserLikeLinksKeyModifierText.setTextLimit(Text.LIMIT); if (computeStateMask(fOverlayStore.getString(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER)) == -1) { // Fix possible illegal modifier string int stateMask= fOverlayStore.getInt(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); if (stateMask == -1) fBrowserLikeLinksKeyModifierText.setText(""); //$NON-NLS-1$ else fBrowserLikeLinksKeyModifierText.setText(EditorUtility.getModifierString(stateMask)); } fBrowserLikeLinksKeyModifierText.addKeyListener(new KeyListener() { private boolean isModifierCandidate; public void keyPressed(KeyEvent e) { isModifierCandidate= e.keyCode > 0 && e.character == 0 && e.stateMask == 0; } public void keyReleased(KeyEvent e) { if (isModifierCandidate && e.stateMask > 0 && e.stateMask == e.stateMask && e.character == 0) {// && e.time -time < 1000) { String modifierString= fBrowserLikeLinksKeyModifierText.getText(); Point selection= fBrowserLikeLinksKeyModifierText.getSelection(); int i= selection.x - 1; while (i > -1 && Character.isWhitespace(modifierString.charAt(i))) { i--; } boolean needsPrefixDelimiter= i > -1 && !String.valueOf(modifierString.charAt(i)).equals(DELIMITER); i= selection.y; while (i < modifierString.length() && Character.isWhitespace(modifierString.charAt(i))) { i++; } boolean needsPostfixDelimiter= i < modifierString.length() && !String.valueOf(modifierString.charAt(i)).equals(DELIMITER); String insertString; if (needsPrefixDelimiter && needsPostfixDelimiter) insertString= PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.insertDelimiterAndModifierAndDelimiter", new String[] {Action.findModifierString(e.stateMask)}); //$NON-NLS-1$ else if (needsPrefixDelimiter) insertString= PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.insertDelimiterAndModifier", new String[] {Action.findModifierString(e.stateMask)}); //$NON-NLS-1$ else if (needsPostfixDelimiter) insertString= PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.insertModifierAndDelimiter", new String[] {Action.findModifierString(e.stateMask)}); //$NON-NLS-1$ else insertString= Action.findModifierString(e.stateMask); fBrowserLikeLinksKeyModifierText.insert(insertString); } } }); fBrowserLikeLinksKeyModifierText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleBrowserLikeLinksKeyModifierModified(); } }); return composite; } private void handleBrowserLikeLinksKeyModifierModified() { String modifiers= fBrowserLikeLinksKeyModifierText.getText(); int stateMask= computeStateMask(modifiers); if (fBrowserLikeLinksCheckBox.getSelection() && (stateMask == -1 || (stateMask & SWT.SHIFT) != 0)) { if (stateMask == -1) fBrowserLikeLinksKeyModifierStatus= new StatusInfo(IStatus.ERROR, PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.modifierIsNotValid", modifiers)); //$NON-NLS-1$ else fBrowserLikeLinksKeyModifierStatus= new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("JavaEditorPreferencePage.navigation.shiftIsDisabled")); //$NON-NLS-1$ setValid(false); StatusUtil.applyToStatusLine(this, fBrowserLikeLinksKeyModifierStatus); } else { fBrowserLikeLinksKeyModifierStatus= new StatusInfo(); updateStatus(fBrowserLikeLinksKeyModifierStatus); } } private IStatus getBrowserLikeLinksKeyModifierStatus() { if (fBrowserLikeLinksKeyModifierStatus == null) fBrowserLikeLinksKeyModifierStatus= new StatusInfo(); return fBrowserLikeLinksKeyModifierStatus; } /** * Computes the state mask for the given modifier string. * * @param modifiers the string with the modifiers, separated by '+', '-', ';', ',' or '.' * @return the state mask or -1 if the input is invalid */ private int computeStateMask(String modifiers) { if (modifiers == null) return -1; if (modifiers.length() == 0) return SWT.NONE; int stateMask= 0; StringTokenizer modifierTokenizer= new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$ while (modifierTokenizer.hasMoreTokens()) { int modifier= EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken()); if (modifier == 0 || (stateMask & modifier) == modifier) return -1; stateMask= stateMask | modifier; } return stateMask; } /* * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { initializeDefaultColors(); fJavaEditorHoverConfigurationBlock= new JavaEditorHoverConfigurationBlock(this, fOverlayStore); fFoldingConfigurationBlock= new FoldingConfigurationBlock(fOverlayStore); fOverlayStore.load(); fOverlayStore.start(); TabFolder folder= new TabFolder(parent, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new GridData(GridData.FILL_BOTH)); TabItem item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.general")); //$NON-NLS-1$ item.setControl(createAppearancePage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.colors")); //$NON-NLS-1$ item.setControl(createSyntaxPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.typing.tabTitle")); //$NON-NLS-1$ item.setControl(createTypingPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.hoverTab.title")); //$NON-NLS-1$ item.setControl(fJavaEditorHoverConfigurationBlock.createControl(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.navigationTab.title")); //$NON-NLS-1$ item.setControl(createNavigationPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.folding.title")); //$NON-NLS-1$ item.setControl(fFoldingConfigurationBlock.createControl(folder)); initialize(); Dialog.applyDialogFont(folder); return folder; } private void initialize() { initializeFields(); for (int i= 0, n= fSyntaxColorListModel.length; i < n; i++) fHighlightingColorList.add(new HighlightingColorListItem (fSyntaxColorListModel[i][0], fSyntaxColorListModel[i][1], fSyntaxColorListModel[i][1] + BOLD, fSyntaxColorListModel[i][1] + ITALIC, null)); if (fSemanticHighlightingEnabled.getSelection()) fHighlightingColorList.addAll(fSemanticHighlightingColorList); fHighlightingColorListViewer.setInput(fHighlightingColorList); fHighlightingColorListViewer.setSelection(new StructuredSelection(fHighlightingColorListViewer.getElementAt(0))); for (int i= 0; i < fAppearanceColorListModel.length; i++) fAppearanceColorList.add(fAppearanceColorListModel[i][0]); fAppearanceColorList.getDisplay().asyncExec(new Runnable() { public void run() { if (fAppearanceColorList != null && !fAppearanceColorList.isDisposed()) { fAppearanceColorList.select(0); handleAppearanceColorListSelection(); } } }); fFoldingConfigurationBlock.initialize(); } private void initializeFields() { Iterator e= fColorButtons.keySet().iterator(); while (e.hasNext()) { ColorEditor c= (ColorEditor) e.next(); String key= (String) fColorButtons.get(c); RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); c.setColorValue(rgb); } e= fCheckBoxes.keySet().iterator(); while (e.hasNext()) { Button b= (Button) e.next(); String key= (String) fCheckBoxes.get(b); b.setSelection(fOverlayStore.getBoolean(key)); } e= fTextFields.keySet().iterator(); while (e.hasNext()) { Text t= (Text) e.next(); String key= (String) fTextFields.get(t); t.setText(fOverlayStore.getString(key)); } RGB rgb= PreferenceConverter.getColor(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR); fBackgroundColorEditor.setColorValue(rgb); boolean default_= fOverlayStore.getBoolean(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR); fBackgroundDefaultRadioButton.setSelection(default_); fBackgroundCustomRadioButton.setSelection(!default_); fBackgroundColorButton.setEnabled(!default_); fBrowserLikeLinksKeyModifierText.setEnabled(fBrowserLikeLinksCheckBox.getSelection()); fFieldsInitialized= true; updateStatus(validatePositiveNumber("0")); //$NON-NLS-1$ // Update slaves Iterator iter= fMasterSlaveListeners.iterator(); while (iter.hasNext()) { SelectionListener listener= (SelectionListener)iter.next(); listener.widgetSelected(null); } } private void initializeDefaultColors() { if (!getPreferenceStore().contains(PreferenceConstants.EDITOR_BACKGROUND_COLOR)) { RGB rgb= getControl().getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB(); PreferenceConverter.setDefault(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgb); PreferenceConverter.setDefault(getPreferenceStore(), PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgb); } if (!getPreferenceStore().contains(PreferenceConstants.EDITOR_FOREGROUND_COLOR)) { RGB rgb= getControl().getDisplay().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(); PreferenceConverter.setDefault(fOverlayStore, PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgb); PreferenceConverter.setDefault(getPreferenceStore(), PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgb); } if (!getPreferenceStore().contains(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR)) { RGB rgb= getControl().getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION).getRGB(); PreferenceConverter.setDefault(fOverlayStore, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR, rgb); PreferenceConverter.setDefault(getPreferenceStore(), AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR, rgb); } if (!getPreferenceStore().contains(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR)) { RGB rgb= getControl().getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT).getRGB(); PreferenceConverter.setDefault(fOverlayStore, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR, rgb); PreferenceConverter.setDefault(getPreferenceStore(), AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR, rgb); } } /* * @see PreferencePage#performOk() */ public boolean performOk() { fJavaEditorHoverConfigurationBlock.performOk(); fFoldingConfigurationBlock.performOk(); fOverlayStore.setValue(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, computeStateMask(fBrowserLikeLinksKeyModifierText.getText())); fOverlayStore.propagate(); JavaPlugin.getDefault().savePluginPreferences(); return true; } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { fOverlayStore.loadDefaults(); initializeFields(); handleSyntaxColorListSelection(); handleAppearanceColorListSelection(); fJavaEditorHoverConfigurationBlock.performDefaults(); fFoldingConfigurationBlock.performDefaults(); super.performDefaults(); fPreviewViewer.invalidateTextPresentation(); } /* * @see DialogPage#dispose() */ public void dispose() { uninstallSemanticHighlighting(); fFoldingConfigurationBlock.dispose(); if (fOverlayStore != null) { fOverlayStore.stop(); fOverlayStore= null; } if (fBackgroundColor != null && !fBackgroundColor.isDisposed()) fBackgroundColor.dispose(); super.dispose(); } private Button addCheckBox(Composite parent, String label, String key, int indentation) { Button checkBox= new Button(parent, SWT.CHECK); checkBox.setText(label); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalIndent= indentation; gd.horizontalSpan= 2; checkBox.setLayoutData(gd); checkBox.addSelectionListener(fCheckBoxListener); fCheckBoxes.put(checkBox, key); return checkBox; } private Text addTextField(Composite composite, String label, String key, int textLimit, int indentation, boolean isNumber) { return getTextControl(addLabelledTextField(composite, label, key, textLimit, indentation, isNumber)); } private static Text getTextControl(Control[] labelledTextField){ return (Text)labelledTextField[1]; } /** * Returns an array of size 2: * - first element is of type <code>Label</code> * - second element is of type <code>Text</code> * Use <code>getLabelControl</code> and <code>getTextControl</code> to get the 2 controls. * * @param composite the parent composite * @param label the text field's label * @param key the preference key * @param textLimit the text limit * @param indentation the field's indentation * @param isNumber <code>true</code> iff this text field is used to e4dit a number * @return */ private Control[] addLabelledTextField(Composite composite, String label, String key, int textLimit, int indentation, boolean isNumber) { Label labelControl= new Label(composite, SWT.NONE); labelControl.setText(label); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalIndent= indentation; labelControl.setLayoutData(gd); Text textControl= new Text(composite, SWT.BORDER | SWT.SINGLE); gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.widthHint= convertWidthInCharsToPixels(textLimit + 1); textControl.setLayoutData(gd); textControl.setTextLimit(textLimit); fTextFields.put(textControl, key); if (isNumber) { fNumberFields.add(textControl); textControl.addModifyListener(fNumberFieldListener); } else { textControl.addModifyListener(fTextFieldListener); } return new Control[]{labelControl, textControl}; } private String loadPreviewContentFromFile(String filename) { String line; String separator= System.getProperty("line.separator"); //$NON-NLS-1$ StringBuffer buffer= new StringBuffer(512); BufferedReader reader= null; try { reader= new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename))); while ((line= reader.readLine()) != null) { buffer.append(line); buffer.append(separator); } } catch (IOException io) { JavaPlugin.log(io); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) {} } } return buffer.toString(); } private void numberFieldChanged(Text textControl) { String number= textControl.getText(); IStatus status= validatePositiveNumber(number); if (!status.matches(IStatus.ERROR)) fOverlayStore.setValue((String) fTextFields.get(textControl), number); updateStatus(status); } private IStatus validatePositiveNumber(String number) { StatusInfo status= new StatusInfo(); if (number.length() == 0) { status.setError(PreferencesMessages.getString("JavaEditorPreferencePage.empty_input")); //$NON-NLS-1$ } else { try { int value= Integer.parseInt(number); if (value < 0) status.setError(PreferencesMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ } catch (NumberFormatException e) { status.setError(PreferencesMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ } } return status; } void updateStatus(IStatus status) { if (!fFieldsInitialized) return; if (!status.matches(IStatus.ERROR)) { for (int i= 0; i < fNumberFields.size(); i++) { Text text= (Text) fNumberFields.get(i); IStatus s= validatePositiveNumber(text.getText()); status= StatusUtil.getMoreSevere(s, status); } } status= StatusUtil.getMoreSevere(fJavaEditorHoverConfigurationBlock.getStatus(), status); status= StatusUtil.getMoreSevere(getBrowserLikeLinksKeyModifierStatus(), status); setValid(!status.matches(IStatus.ERROR)); StatusUtil.applyToStatusLine(this, status); } /** * Install Semantic Highlighting on the previewer * * @since 3.0 */ private void installSemanticHighlighting() { if (fSemanticHighlightingManager == null) { fSemanticHighlightingManager= new SemanticHighlightingManager(); fSemanticHighlightingManager.install(fPreviewViewer, JavaPlugin.getDefault().getJavaTextTools().getColorManager(), fOverlayStore, createPreviewerRanges()); } } /** * Uninstall Semantic Highlighting from the previewer * * @since 3.0 */ private void uninstallSemanticHighlighting() { if (fSemanticHighlightingManager != null) { fSemanticHighlightingManager.uninstall(); fSemanticHighlightingManager= null; } } /** * Create the hard coded previewer ranges * * @return the hard coded previewer ranges * @since 3.0 */ private SemanticHighlightingManager.HighlightedRange[] createPreviewerRanges() { return new SemanticHighlightingManager.HighlightedRange[] { createHighlightedRange(6, 26, 8, SemanticHighlightings.STATIC_FINAL_FIELD), createHighlightedRange(8, 20, 11, SemanticHighlightings.STATIC_FIELD), createHighlightedRange(10, 16, 5, SemanticHighlightings.FIELD), createHighlightedRange(12, 12, 3, SemanticHighlightings.METHOD_DECLARATION), createHighlightedRange(12, 20, 9, SemanticHighlightings.PARAMETER_VARIABLE), createHighlightedRange(13, 6, 5, SemanticHighlightings.LOCAL_VARIABLE_DECLARATION), createHighlightedRange(13, 16, 8, SemanticHighlightings.INHERITED_METHOD_INVOCATION), createHighlightedRange(14, 2, 12, SemanticHighlightings.STATIC_METHOD), createHighlightedRange(15, 13, 5, SemanticHighlightings.LOCAL_VARIABLE), createHighlightedRange(17, 20, 12, SemanticHighlightings.STATIC_METHOD_DECLARATION), }; } /** * Create a highlighted range on the previewers document with the given line, column, length and key. * * @param line the line * @param column the column * @param length the length * @param key the key * @return the highlighted range * @since 3.0 */ private HighlightedRange createHighlightedRange(int line, int column, int length, String key) { try { IDocument document= fPreviewViewer.getDocument(); int offset= document.getLineOffset(line) + column; return new HighlightedRange(offset, length, key); } catch (BadLocationException x) { JavaPlugin.log(x); } return null; } /** * Returns the current highlighting color list item. * * @return the current highlighting color list item * @since 3.0 */ private HighlightingColorListItem getHighlightingColorListItem() { IStructuredSelection selection= (IStructuredSelection) fHighlightingColorListViewer.getSelection(); return (HighlightingColorListItem) selection.getFirstElement(); } }
38,483
Bug 38483 Delete: buttons on the 'Found Problems' page [refactoring]
20030604 1. make Java file read-only and delete a method in it 2. On the first dialog, press ok, a 'Found Problems' dialog shows up 3. The dialog has two buttons: Back and cancel Back is not too helpfull as you can't change anything on the first dialog Cancel should probably be better 'Ok'
resolved fixed
105f818
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T13:22:54Z
2003-06-05T10:46:40Z
org.eclipse.jdt.ui/ui
38,483
Bug 38483 Delete: buttons on the 'Found Problems' page [refactoring]
20030604 1. make Java file read-only and delete a method in it 2. On the first dialog, press ok, a 'Found Problems' dialog shows up 3. The dialog has two buttons: Back and cancel Back is not too helpfull as you can't change anything on the first dialog Cancel should probably be better 'Ok'
resolved fixed
105f818
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T13:22:54Z
2003-06-05T10:46:40Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/InlineTempWizard.java
38,483
Bug 38483 Delete: buttons on the 'Found Problems' page [refactoring]
20030604 1. make Java file read-only and delete a method in it 2. On the first dialog, press ok, a 'Found Problems' dialog shows up 3. The dialog has two buttons: Back and cancel Back is not too helpfull as you can't change anything on the first dialog Cancel should probably be better 'Ok'
resolved fixed
105f818
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T13:22:54Z
2003-06-05T10:46:40Z
org.eclipse.jdt.ui/ui
38,483
Bug 38483 Delete: buttons on the 'Found Problems' page [refactoring]
20030604 1. make Java file read-only and delete a method in it 2. On the first dialog, press ok, a 'Found Problems' dialog shows up 3. The dialog has two buttons: Back and cancel Back is not too helpfull as you can't change anything on the first dialog Cancel should probably be better 'Ok'
resolved fixed
105f818
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T13:22:54Z
2003-06-05T10:46:40Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/reorg/DeleteWizard.java
38,483
Bug 38483 Delete: buttons on the 'Found Problems' page [refactoring]
20030604 1. make Java file read-only and delete a method in it 2. On the first dialog, press ok, a 'Found Problems' dialog shows up 3. The dialog has two buttons: Back and cancel Back is not too helpfull as you can't change anything on the first dialog Cancel should probably be better 'Ok'
resolved fixed
105f818
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T13:22:54Z
2003-06-05T10:46:40Z
org.eclipse.ltk.ui.refactoring/src/org/eclipse/ltk/internal/ui/refactoring/RefactoringStatusDialog.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.ltk.internal.ui.refactoring; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ViewForm; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.ltk.core.refactoring.RefactoringStatus; public class RefactoringStatusDialog extends Dialog { private RefactoringStatus fStatus; private String fWindowTitle; private boolean fBackButton; public RefactoringStatusDialog(RefactoringStatus status, Shell parent, String windowTitle, boolean backButton) { super(parent); fStatus= status; fWindowTitle= windowTitle; fBackButton= backButton; setShellStyle(getShellStyle() | SWT.RESIZE); } public RefactoringStatusDialog(Shell parent, ErrorWizardPage page, boolean backButton) { this(page.getStatus(), parent, parent.getText(), backButton); } protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(fWindowTitle); } protected Control createDialogArea(Composite parent) { Composite result= new Composite(parent, SWT.NONE); initializeDialogUnits(result); GridLayout layout= new GridLayout(); result.setLayout(layout); GridData gd= new GridData(GridData.FILL_BOTH); gd.widthHint= 600; gd.heightHint= 400; result.setLayoutData(gd); Color background= parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND); ViewForm messagePane= new ViewForm(result, SWT.BORDER | SWT.FLAT); messagePane.marginWidth= layout.marginWidth; messagePane.marginHeight= layout.marginHeight; gd= new GridData(GridData.FILL_HORIZONTAL); // XXX http://bugs.eclipse.org/bugs/show_bug.cgi?id=27572 Rectangle rect= messagePane.computeTrim(0, 0, 0, convertHeightInCharsToPixels(2) + messagePane.marginHeight * 2); gd.heightHint= rect.height; messagePane.setLayoutData(gd); messagePane.setBackground(background); Label label= new Label(messagePane, SWT.LEFT | SWT.WRAP); if (fStatus.hasFatalError()) label.setText(RefactoringUIMessages.getString("RefactoringStatusDialog.Cannot_proceed")); //$NON-NLS-1$ else label.setText(RefactoringUIMessages.getString("RefactoringStatusDialog.Please_look")); //$NON-NLS-1$ label.setBackground(background); messagePane.setContent(label); RefactoringStatusViewer viewer= new RefactoringStatusViewer(result, SWT.NONE); viewer.setLayoutData(new GridData(GridData.FILL_BOTH)); viewer.setStatus(fStatus); applyDialogFont(result); return result; } protected void buttonPressed(int buttonId) { if (buttonId == IDialogConstants.BACK_ID) { setReturnCode(IDialogConstants.BACK_ID); close(); } else { super.buttonPressed(buttonId); } } protected void createButtonsForButtonBar(Composite parent) { if (!fStatus.hasFatalError()) { if (fBackButton) createButton(parent, IDialogConstants.BACK_ID, IDialogConstants.BACK_LABEL, false); //$NON-NLS-1$ createButton(parent, IDialogConstants.OK_ID, RefactoringUIMessages.getString("RefactoringStatusDialog.Continue"), true); //$NON-NLS-1$ createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } else { if (fBackButton) createButton(parent, IDialogConstants.BACK_ID, IDialogConstants.BACK_LABEL, true); //$NON-NLS-1$ createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } } }
38,483
Bug 38483 Delete: buttons on the 'Found Problems' page [refactoring]
20030604 1. make Java file read-only and delete a method in it 2. On the first dialog, press ok, a 'Found Problems' dialog shows up 3. The dialog has two buttons: Back and cancel Back is not too helpfull as you can't change anything on the first dialog Cancel should probably be better 'Ok'
resolved fixed
105f818
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T13:22:54Z
2003-06-05T10:46:40Z
org.eclipse.ltk.ui.refactoring/src/org/eclipse/ltk/internal/ui/refactoring/RefactoringWizardDialog2.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.ltk.internal.ui.refactoring; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StackLayout; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.ControlEnableState; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.DialogSettings; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.operation.ModalContext; import org.eclipse.jface.util.Assert; import org.eclipse.jface.wizard.IWizardContainer; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.ProgressMonitorPart; import org.eclipse.ltk.ui.refactoring.RefactoringWizard; public class RefactoringWizardDialog2 extends Dialog implements IWizardContainer { private RefactoringWizard fWizard; private IWizardPage fCurrentPage; private IWizardPage fVisiblePage; private boolean fMakeNextButtonDefault; private PageBook fPageContainer; private PageBook fStatusContainer; private MessageBox fMessageBox; private ProgressMonitorPart fProgressMonitorPart; private int fActiveRunningOperations; private Cursor fWaitCursor; private Cursor fArrowCursor; private static final int PREVIEW_ID= IDialogConstants.CLIENT_ID + 1; private int fPreviewWidth; private int fPreviewHeight; private IDialogSettings fSettings; private static final String DIALOG_SETTINGS= "RefactoringWizard.preview"; //$NON-NLS-1$ private static final String WIDTH= "width"; //$NON-NLS-1$ private static final String HEIGHT= "height"; //$NON-NLS-1$ private static final Image INFO= RefactoringPluginImages.get(RefactoringPluginImages.IMG_OBJS_REFACTORING_INFO); private static final Image WARNING= RefactoringPluginImages.get(RefactoringPluginImages.IMG_OBJS_REFACTORING_WARNING); private static final Image ERROR= RefactoringPluginImages.get(RefactoringPluginImages.IMG_OBJS_REFACTORING_ERROR); private static class MessageBox extends Composite { private Label fImage; private Label fText; public MessageBox(Composite parent, int style) { super(parent, style); GridLayout layout= new GridLayout(); layout.numColumns= 2; setLayout(layout); fImage= new Label(this, SWT.NONE); fImage.setImage(INFO); Point size= fImage.computeSize(SWT.DEFAULT, SWT.DEFAULT); GridData gd= new GridData(); gd.verticalAlignment= SWT.TOP; gd.widthHint= size.x; gd.heightHint= size.y; fImage.setLayoutData(gd); fImage.setImage(null); fText= new Label(this, SWT.WRAP); fText.setText(" \n "); //$NON-NLS-1$ size= fText.computeSize(SWT.DEFAULT, SWT.DEFAULT); gd= new GridData(GridData.FILL_HORIZONTAL); gd.heightHint= size.y; gd.verticalAlignment= SWT.TOP; fText.setLayoutData(gd); } public void setMessage(IWizardPage page) { String msg= page.getErrorMessage(); int type= IMessageProvider.ERROR; if (msg == null || msg.length() == 0) { msg= page.getMessage(); type= IMessageProvider.NONE; if (msg != null && page instanceof IMessageProvider) type = ((IMessageProvider)page).getMessageType(); } Image image= null; switch (type) { case IMessageProvider.INFORMATION: image= INFO; break; case IMessageProvider.WARNING: image= WARNING; break; case IMessageProvider.ERROR: image= ERROR; break; } if (msg == null) msg= ""; //$NON-NLS-1$ fText.setText(msg); if (image == null && msg.length() > 0) image= INFO; fImage.setImage(image); } } private static class PageBook extends Composite { private StackLayout fLayout; public PageBook(Composite parent, int style) { super(parent, style); fLayout= new StackLayout(); setLayout(fLayout); fLayout.marginWidth= 5; fLayout.marginHeight= 5; } public void showPage(Control page) { fLayout.topControl= page; layout(); } public Control getTopPage() { return fLayout.topControl; } } public RefactoringWizardDialog2(Shell shell, RefactoringWizard wizard) { super(shell); Assert.isNotNull(wizard); setShellStyle(getShellStyle() | SWT.RESIZE); wizard.setDialogSettings(RefactoringUIPlugin.getDefault().getDialogSettings()); fWizard= wizard; fWizard.setContainer(this); fWizard.addPages(); initSize(); } private void initSize() { IDialogSettings settings= RefactoringUIPlugin.getDefault().getDialogSettings(); fSettings= settings.getSection(DIALOG_SETTINGS); if (fSettings == null) { fSettings= new DialogSettings(DIALOG_SETTINGS); settings.addSection(fSettings); fSettings.put(WIDTH, 600); fSettings.put(HEIGHT, 400); } fPreviewWidth= 600; fPreviewHeight= 400; try { fPreviewWidth= fSettings.getInt(WIDTH); fPreviewHeight= fSettings.getInt(HEIGHT); } catch (NumberFormatException e) { } } private void saveSize() { if (fCurrentPage instanceof PreviewWizardPage) { Control control= fCurrentPage.getControl().getParent(); Point size = control.getSize(); fSettings.put(WIDTH, size.x); fSettings.put(HEIGHT, size.y); } } //---- IRefactoringWizardDialog ------------------------------------ public void makeNextButtonDefault() { fMakeNextButtonDefault= true; } //---- IWizardContainer -------------------------------------------- /* (non-Javadoc) * Method declared on IWizardContainer. */ public void showPage(IWizardPage page) { fCurrentPage= page; } /* (non-Javadoc) * Method declared on IWizardContainer. */ public void updateButtons() { boolean previewPage= isPreviewPageActive(); boolean ok= fWizard.canFinish(); boolean canFlip= fCurrentPage.canFlipToNextPage(); Button previewButton= getButton(PREVIEW_ID); Button defaultButton= null; if (previewButton != null && !previewButton.isDisposed()) { previewButton.setEnabled(!previewPage); if (!previewPage) previewButton.setEnabled(canFlip); if (previewButton.isEnabled()) defaultButton= previewButton; } Button okButton= getButton(IDialogConstants.OK_ID); if (okButton != null && !okButton.isDisposed()) { okButton.setEnabled(ok); if (ok) defaultButton= okButton; } if (defaultButton != null) { defaultButton.getShell().setDefaultButton(defaultButton); } } /* (non-Javadoc) * Method declared on IWizardContainer. */ public void updateMessage() { if (fStatusContainer == null || fStatusContainer.isDisposed()) return; fStatusContainer.showPage(fMessageBox); fMessageBox.setMessage(fCurrentPage); } /* (non-Javadoc) * Method declared on IWizardContainer. */ public void updateTitleBar() { // we don't have a title bar. } /* (non-Javadoc) * Method declared on IWizardContainer. */ public void updateWindowTitle() { getShell().setText(fWizard.getWindowTitle()); } /* (non-Javadoc) * Method declared on IWizardContainer. */ public IWizardPage getCurrentPage() { return fCurrentPage; } //---- IRunnableContext -------------------------------------------- /* (non-Javadoc) * Method declared on IRunnableContext */ public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable) throws InvocationTargetException, InterruptedException { if (fProgressMonitorPart == null) { ModalContext.run(runnable, false, new NullProgressMonitor(), getShell().getDisplay()); } else { Object state = null; if(fActiveRunningOperations == 0) state = aboutToStart(fork && cancelable); fActiveRunningOperations++; try { ModalContext.run(runnable, fork, fProgressMonitorPart, getShell().getDisplay()); } finally { fActiveRunningOperations--; //Stop if this is the last one if(state!= null) stopped(state); } } } private Object aboutToStart(boolean cancelable) { Map savedState = null; Shell shell= getShell(); if (shell != null) { // Save focus control Control focusControl = getShell().getDisplay().getFocusControl(); if (focusControl != null && focusControl.getShell() != getShell()) focusControl = null; Button cancelButton= getButton(IDialogConstants.CANCEL_ID); // Set the busy cursor to all shells. Display d = getShell().getDisplay(); fWaitCursor = new Cursor(d, SWT.CURSOR_WAIT); setDisplayCursor(d, fWaitCursor); // Set the arrow cursor to the cancel component. fArrowCursor= new Cursor(d, SWT.CURSOR_ARROW); cancelButton.setCursor(fArrowCursor); boolean hasProgressMonitor= fProgressMonitorPart != null; // Deactivate shell savedState= saveUIState(hasProgressMonitor && cancelable); if (focusControl != null) savedState.put("focus", focusControl); //$NON-NLS-1$ if (hasProgressMonitor) { fProgressMonitorPart.attachToCancelComponent(cancelButton); fStatusContainer.showPage(fProgressMonitorPart); } // Update the status container since we are blocking the event loop right now. fStatusContainer.update(); } return savedState; } private Map saveUIState(boolean keepCancelEnabled) { Map savedState= new HashMap(10); saveEnableStateAndSet(getButton(PREVIEW_ID), savedState, "preview", false); //$NON-NLS-1$ saveEnableStateAndSet(getButton(IDialogConstants.OK_ID), savedState, "ok", false); //$NON-NLS-1$ saveEnableStateAndSet(getButton(IDialogConstants.CANCEL_ID), savedState, "cancel", keepCancelEnabled); //$NON-NLS-1$ savedState.put("page", ControlEnableState.disable(fVisiblePage.getControl())); //$NON-NLS-1$ return savedState; } private void saveEnableStateAndSet(Control w, Map h, String key, boolean enabled) { if (w != null) { h.put(key, new Boolean(w.getEnabled())); w.setEnabled(enabled); } } private void setDisplayCursor(Display d, Cursor c) { Shell[] shells= d.getShells(); for (int i= 0; i < shells.length; i++) shells[i].setCursor(c); } private void stopped(Object savedState) { Shell shell= getShell(); if (shell != null) { Button cancelButton= getButton(IDialogConstants.CANCEL_ID); if (fProgressMonitorPart != null) fProgressMonitorPart.removeFromCancelComponent(cancelButton); fStatusContainer.showPage(fMessageBox); Map state = (Map)savedState; restoreUIState(state); setDisplayCursor(shell.getDisplay(), null); cancelButton.setCursor(null); fWaitCursor.dispose(); fWaitCursor = null; fArrowCursor.dispose(); fArrowCursor = null; Control focusControl = (Control)state.get("focus"); //$NON-NLS-1$ if (focusControl != null) focusControl.setFocus(); } } private void restoreUIState(Map state) { restoreEnableState(getButton(PREVIEW_ID), state, "preview");//$NON-NLS-1$ restoreEnableState(getButton(IDialogConstants.OK_ID), state, "ok");//$NON-NLS-1$ restoreEnableState(getButton(IDialogConstants.CANCEL_ID), state, "cancel");//$NON-NLS-1$ ControlEnableState pageState = (ControlEnableState) state.get("page");//$NON-NLS-1$ pageState.restore(); } private void restoreEnableState(Control w, Map h, String key) { if (w != null) { Boolean b = (Boolean) h.get(key); if (b != null) w.setEnabled(b.booleanValue()); } } //---- Dialog ----------------------------------------------------------- public boolean close() { fWizard.dispose(); return super.close(); } protected void cancelPressed() { if (fActiveRunningOperations == 0) { if (fWizard.performCancel()) super.cancelPressed(); } } protected void okPressed() { IWizardPage current= fCurrentPage; if (fWizard.performFinish()) { saveSize(); super.okPressed(); return; } if (fCurrentPage == current) return; Assert.isTrue(ErrorWizardPage.PAGE_NAME.equals(fCurrentPage.getName())); if (showErrorDialog((ErrorWizardPage)fCurrentPage)) { if (fWizard.performFinish()) { super.okPressed(); return; } } fCurrentPage= current; } private boolean isPreviewPageActive() { return IPreviewWizardPage.PAGE_NAME.equals(fCurrentPage.getName()); } private void previewPressed() { IWizardPage current= fCurrentPage; fCurrentPage= fCurrentPage.getNextPage(); if (current == fCurrentPage) return; String pageName= fCurrentPage.getName(); if (ErrorWizardPage.PAGE_NAME.equals(pageName)) { if (showErrorDialog((ErrorWizardPage)fCurrentPage)) { fCurrentPage= fCurrentPage.getNextPage(); pageName= fCurrentPage.getName(); } else { return; } } if (IPreviewWizardPage.PAGE_NAME.equals(pageName)) { fCurrentPage.createControl(fPageContainer); makeVisible(fCurrentPage); updateButtons(); if (((PreviewWizardPage)fCurrentPage).hasChanges()) resize(); else getButton(IDialogConstants.OK_ID).setEnabled(false); } else { fCurrentPage= current; } } private boolean showErrorDialog(ErrorWizardPage page) { RefactoringStatusDialog dialog= new RefactoringStatusDialog(getShell(), page, true); switch (dialog.open()) { case IDialogConstants.OK_ID: return true; case IDialogConstants.BACK_ID: fCurrentPage= fCurrentPage.getPreviousPage(); break; case IDialogConstants.CANCEL_ID: super.cancelPressed(); } return false; } private void resize() { Control control= fPageContainer.getTopPage(); Point size= control.getSize(); int dw= Math.max(0, fPreviewWidth - size.x); int dh= Math.max(0, fPreviewHeight - size.y); int dx = dw / 2; int dy= dh / 2; Shell shell= getShell(); Rectangle rect= shell.getBounds(); Rectangle display= shell.getDisplay().getClientArea(); rect.x= Math.max(0, rect.x - dx); rect.y= Math.max(0, rect.y - dy); rect.width= Math.min(rect.width + dw, display.width); rect.height= Math.min(rect.height + dh, display.height); int xe= rect.x + rect.width; if (xe > display.width) { rect.x-= xe - display.width; } int ye= rect.y + rect.height; if (ye > display.height) { rect.y-= ye - display.height; } shell.setBounds(rect); } //---- UI construction --------------------------------------------------- protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(fWizard.getDefaultPageTitle()); } protected Control createContents(Composite parent) { Composite result= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.verticalSpacing= 0; layout.horizontalSpacing= 0; result.setLayout(layout); result.setLayoutData(new GridData(GridData.FILL_BOTH)); // initialize the dialog units initializeDialogUnits(result); fPageContainer= new PageBook(result, SWT.NONE); GridData gd= new GridData(GridData.FILL_BOTH); fPageContainer.setLayoutData(gd); fCurrentPage= fWizard.getStartingPage(); dialogArea= fPageContainer; if (fCurrentPage instanceof PreviewWizardPage) { gd.widthHint= fPreviewWidth; gd.heightHint= fPreviewHeight; } fStatusContainer= new PageBook(result, SWT.NONE); gd= new GridData(GridData.FILL_HORIZONTAL); gd.widthHint= convertWidthInCharsToPixels(fWizard.getMessageLineWidthInChars()); fStatusContainer.setLayoutData(gd); if (fWizard.needsProgressMonitor()) createProgressMonitorPart(); createMessageBox(); fStatusContainer.showPage(fMessageBox); buttonBar= createButtonBar(result); fCurrentPage.createControl(fPageContainer); makeVisible(fCurrentPage); updateMessage(); updateButtons(); applyDialogFont(result); return result; } private void createProgressMonitorPart() { // Insert a progress monitor GridLayout pmlayout= new GridLayout(); pmlayout.numColumns= 1; pmlayout.marginHeight= 0; fProgressMonitorPart= new ProgressMonitorPart(fStatusContainer, pmlayout); } private void createMessageBox() { fMessageBox= new MessageBox(fStatusContainer, SWT.NONE); } protected void createButtonsForButtonBar(Composite parent) { if (! (fCurrentPage instanceof PreviewWizardPage) && fWizard.internalHasPreviewPage(InternalAPI.INSTANCE)) { Button preview= createButton(parent, PREVIEW_ID, RefactoringUIMessages.getString("RefactoringWizardDialog2.buttons.preview.label"), false); //$NON-NLS-1$ if (fMakeNextButtonDefault) { preview.getShell().setDefaultButton(preview); } preview.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { previewPressed(); } }); } String OK_LABEL= IDialogConstants.OK_LABEL; String CANCEL_LABEL= IDialogConstants.CANCEL_LABEL; if (fWizard.internalIsYesNoStyle(InternalAPI.INSTANCE)) { OK_LABEL= IDialogConstants.YES_LABEL; CANCEL_LABEL= IDialogConstants.NO_LABEL; } createButton( parent, IDialogConstants.OK_ID, OK_LABEL, true); createButton( parent, IDialogConstants.CANCEL_ID, CANCEL_LABEL, false); Button okButton= getButton(IDialogConstants.OK_ID); okButton.setFocus(); } private void makeVisible(IWizardPage page) { if (fVisiblePage == page) return; if (fVisiblePage != null) fVisiblePage.setVisible(false); fVisiblePage= page; fPageContainer.showPage(page.getControl()); fVisiblePage.setVisible(true); } }
38,483
Bug 38483 Delete: buttons on the 'Found Problems' page [refactoring]
20030604 1. make Java file read-only and delete a method in it 2. On the first dialog, press ok, a 'Found Problems' dialog shows up 3. The dialog has two buttons: Back and cancel Back is not too helpfull as you can't change anything on the first dialog Cancel should probably be better 'Ok'
resolved fixed
105f818
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T13:22:54Z
2003-06-05T10:46:40Z
org.eclipse.ltk.ui.refactoring/src/org/eclipse/ltk/ui/refactoring/RefactoringWizard.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.ltk.ui.refactoring; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.Wizard; import org.eclipse.ui.PlatformUI; import org.eclipse.ltk.core.refactoring.Change; import org.eclipse.ltk.core.refactoring.CheckConditionsOperation; import org.eclipse.ltk.core.refactoring.CreateChangeOperation; import org.eclipse.ltk.core.refactoring.PerformChangeOperation; import org.eclipse.ltk.core.refactoring.Refactoring; import org.eclipse.ltk.core.refactoring.RefactoringCore; import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.ltk.internal.ui.refactoring.Assert; import org.eclipse.ltk.internal.ui.refactoring.ChangeExceptionHandler; import org.eclipse.ltk.internal.ui.refactoring.ErrorWizardPage; import org.eclipse.ltk.internal.ui.refactoring.ExceptionHandler; import org.eclipse.ltk.internal.ui.refactoring.FinishResult; import org.eclipse.ltk.internal.ui.refactoring.IPreviewWizardPage; import org.eclipse.ltk.internal.ui.refactoring.InternalAPI; import org.eclipse.ltk.internal.ui.refactoring.PreviewWizardPage; import org.eclipse.ltk.internal.ui.refactoring.RefactoringPluginImages; import org.eclipse.ltk.internal.ui.refactoring.RefactoringUIMessages; import org.eclipse.ltk.internal.ui.refactoring.RefactoringUIPlugin; import org.eclipse.ltk.internal.ui.refactoring.WorkbenchRunnableAdapter; /** * An abstract base implementation of a refactoring wizard. A refactoring * wizard differs from a normal wizard in the following characteristics: * <ul> * <li>only pages of type {@link org.eclipse.ltk.ui.refactoring.RefactoringWizardPage * RefactoringWizardPage} can be added to a refactoring wizard. Trying to * add a different kind of page results in an exception.</li> * <li>a refactoring wizard consists of 0 .. n user input pages, one error page * to present the outcome of the refactoring's condition checking and one * preview page to present a preview of the workspace changes.</li> * </ul> * <p> * A refactoring wizard is best opened using the {@link RefactoringWizardOpenOperation}. * </p> * <p> * Clients may extend this class. * </p> * * @see org.eclipse.ltk.core.refactoring.Refactoring * * @since 3.0 */ public abstract class RefactoringWizard extends Wizard { /** * Flag indicating that no special flags are provided. */ public static final int NONE= 0; /** * Flag indicating that the initial condition checking of the refactoring is done when * the wizard opens. If not specified it is assumed that the initial condition checking * has been done by the client before opening the wizard dialog. */ public static final int CHECK_INITIAL_CONDITIONS_ON_OPEN= 1 << 0; /** * Flag indicating that a normal wizard based user interface consisting * of a back, next, finish and cancel button should be used to present * this refactoring wizard. */ public static final int WIZARD_BASED_USER_INTERFACE= 1 << 1; /** * Flag indicating that a lightweight dialog based user interface should * be used to present this refactoring wizard. This user interface consists * of a preview, finish and cancel button and the initial size of dialog * is based on the first user input page. This flag is only valid if only * one user input page is present. Specifying this flag together with more * than one input page will result in an exception when adding the user input * pages. */ public static final int DIALOG_BASED_UESR_INTERFACE= 1 << 2; /** * Flag indicating that the finish and cancel button should be named * yes and no. The flag is ignored if the flag {@link #WIZARD_BASED_USER_INTERFACE} * is specified. */ public static final int YES_NO_BUTTON_STYLE= 1 << 3; /** * Flag indicating that the wizard should not show a preview page. * The flag is ignored if the flag {@link #WIZARD_BASED_USER_INTERFACE} * is specified. * */ public static final int NO_PREVIEW_PAGE= 1 << 4; /** * Flag indicating that the first change node presented in the * preview page should be fully expanded. */ public static final int PREVIEW_EXPAND_FIRST_NODE= 1 << 5; private static final int LAST= 1 << 6; private int fFlags; private Refactoring fRefactoring; private String fDefaultPageTitle; private Change fChange; private RefactoringStatus fInitialConditionCheckingStatus= new RefactoringStatus(); private RefactoringStatus fConditionCheckingStatus; private int fUserInputPages; private boolean fInAddPages; private boolean fIsChangeCreationCancelable; private boolean fForcePreviewReview; private boolean fPreviewShown; /** * Creates a new refactoring wizard for the given refactoring. * * @param refactoring the refactoring the wizard is presenting * @param flags flags specifying the bahaviour of the wizard. If neither * <code>WIZARD_BASED_USER_INTERFACE</code> nor <code>DIALOG_BASED_UESR_INTERFACE</code> * is specified then <code>WIZARD_BASED_USER_INTERFACE</code> will be * taken as a default. */ public RefactoringWizard(Refactoring refactoring, int flags) { Assert.isNotNull(refactoring); Assert.isTrue(flags < LAST); if ((flags & DIALOG_BASED_UESR_INTERFACE) == 0) flags |= WIZARD_BASED_USER_INTERFACE; Assert.isTrue((flags & DIALOG_BASED_UESR_INTERFACE) != 0 || (flags & WIZARD_BASED_USER_INTERFACE) != 0); fRefactoring= refactoring; fFlags= flags; setNeedsProgressMonitor(true); setChangeCreationCancelable(true); setWindowTitle(RefactoringUIMessages.getString("RefactoringWizard.title")); //$NON-NLS-1$ setDefaultPageImageDescriptor(RefactoringPluginImages.DESC_WIZBAN_REFACTOR); } //---- Setter and Getters ------------------------------------------------------------ /** * Returns the refactoring this wizard is associated with. * * @return the wizard's refactoring */ public final Refactoring getRefactoring(){ return fRefactoring; } /** * Sets the default page title to the given value. This value is used * as a page title for wizard pages which don't provide their own * page title. Setting this value has only an effect as long as the * user interface hasn't been created yet. * * @param defaultPageTitle the default page title. * @see Wizard#setDefaultPageImageDescriptor(org.eclipse.jface.resource.ImageDescriptor) */ public final void setDefaultPageTitle(String defaultPageTitle) { Assert.isNotNull(defaultPageTitle); fDefaultPageTitle= defaultPageTitle; } /** * Returns the default page title used for pages that don't provide their * own page title. * * @return the default page title * * @see #setDefaultPageTitle(String) */ public final String getDefaultPageTitle() { return fDefaultPageTitle; } /** * If set to <code>true</code> the Finish or OK button, respectively will * be disabled until the user has visited the preview page. If set to * <code>false</code> the refactoring can be performed before the preview * page has been visited. * * @param forcePreviewReview if <code>true</code> to user must confirm the * preview */ public final void setForcePreviewReview(boolean forcePreviewReview) { fForcePreviewReview= forcePreviewReview; getContainer().updateButtons(); } /** * Returns the width in characters to be used for the message line embedded into * the refactoring wizard dialog. * <p> * Subclasses may override this method and return a different value. * </p> * * @return the message lines width in characters */ public int getMessageLineWidthInChars() { return 80; } /** * If set to <code>true</code> the change creation is cancelable by the user. * <p> * By default, change creation is cancelable. * </p> * @param isChangeCreationCancelable determines whether the change creation * is cancelable by the user or not. * * @see Refactoring#createChange(IProgressMonitor) */ public final void setChangeCreationCancelable(boolean isChangeCreationCancelable){ fIsChangeCreationCancelable= isChangeCreationCancelable; } /** * Sets the initial condition checking status computed by the refactoring. * Clients should uses this method if the initial condition checking * status has been computed outside of this refactoring wizard. * * @param status the initial condition checking status. * * @see Refactoring#checkInitialConditions(IProgressMonitor) * @see #CHECK_INITIAL_CONDITIONS_ON_OPEN */ public final void setInitialConditionCheckingStatus(RefactoringStatus status) { Assert.isNotNull(status); fInitialConditionCheckingStatus= status; setConditionCheckingStatus(status); } /** * Returns the refactoring's change object or <code>null</code> if no change * object has been created yet. * * @return the refactoring's change object or <code>null</code> * * @see Refactoring#createChange(IProgressMonitor) */ public final Change getChange() { return fChange; } /** * Returns the status of the initial condition checking or <code>null</code> * if the initial condition checking hasn't been performed yet. * * @return the status of the initial condition checking or <code>null</code> * * @see Refactoring#checkInitialConditions(IProgressMonitor) */ /* package */ final RefactoringStatus getInitialConditionCheckingStatus() { return fInitialConditionCheckingStatus; } /** * Returns <code>true</code> if the wizard needs a wizard based user interface. * Otherwise <code>false</code> is returned. * * @return whether the wizard needs a wizard based user interface or not */ /* package */ boolean needsWizardBasedUserInterface() { return (fFlags & WIZARD_BASED_USER_INTERFACE) != 0; } //---- Page management ------------------------------------------------------------ /** * {@inheritDoc} * * This method calls the hook method {@link #addUserInputPages()} to allow * subclasses to add specific user input pages. */ public final void addPages() { Assert.isNotNull(fRefactoring); try { fInAddPages= true; if (checkActivationOnOpen()) { internalCheckCondition(CheckConditionsOperation.INITIAL_CONDITONS); } if (fInitialConditionCheckingStatus.hasFatalError()) { addErrorPage(); // Set the status since we added the error page setConditionCheckingStatus(getConditionCheckingStatus()); } else { Assert.isTrue(getPageCount() == 0); addUserInputPages(); fUserInputPages= getPageCount(); if (fUserInputPages > 0) { IWizardPage[] pages= getPages(); ((UserInputWizardPage)pages[fUserInputPages - 1]).markAsLastUserInputPage(); } if (fUserInputPages > 1) { Assert.isTrue((fFlags & WIZARD_BASED_USER_INTERFACE) != 0); } addErrorPage(); addPreviewPage(); } initializeDefaultPageTitles(); } finally { fInAddPages= false; } } /** * {@inheritDoc} * * This method ensures that the pages added to the refactoring wizard * are instances of type {@link RefactoringWizardPage}. */ public final void addPage(IWizardPage page) { Assert.isTrue(page instanceof RefactoringWizardPage && fInAddPages); super.addPage(page); } /** * Hook method to add user input pages to this refactoring wizard. Pages * added via this call have to be instances of the type {@link UserInputWizardPage}. * Adding pages of a different kind is not permitted and will result * in unexpected behavior. */ protected abstract void addUserInputPages(); private void addErrorPage(){ addPage(new ErrorWizardPage()); } private void addPreviewPage(){ addPage(new PreviewWizardPage()); } private boolean hasUserInput() { return fUserInputPages > 0; } private void initializeDefaultPageTitles() { if (fDefaultPageTitle == null) return; IWizardPage[] pages= getPages(); for (int i= 0; i < pages.length; i++) { IWizardPage page= pages[i]; if (page.getTitle() == null) page.setTitle(fDefaultPageTitle); } } //---- Page computation ----------------------------------------------------------- /** * {@inheritDoc} */ public IWizardPage getStartingPage() { if (hasUserInput()) return super.getStartingPage(); return computeUserInputSuccessorPage(null, PlatformUI.getWorkbench().getActiveWorkbenchWindow()); } /** * {@inheritDoc} */ public IWizardPage getPreviousPage(IWizardPage page) { if (hasUserInput()) return super.getPreviousPage(page); if (! page.getName().equals(ErrorWizardPage.PAGE_NAME)){ if (fConditionCheckingStatus.isOK()) return null; } return super.getPreviousPage(page); } /* package */ IWizardPage computeUserInputSuccessorPage(IWizardPage caller, IRunnableContext context) { Change change= createChange(new CreateChangeOperation( new CheckConditionsOperation(fRefactoring, CheckConditionsOperation.FINAL_CONDITIONS), RefactoringStatus.FATAL), true, context); // Status has been updated since we have passed true RefactoringStatus status= getConditionCheckingStatus(); // Creating the change has been canceled if (change == null && status == null) { internalSetChange(InternalAPI.INSTANCE, change); return caller; } // Set change if we don't have fatal errors. if (!status.hasFatalError()) internalSetChange(InternalAPI.INSTANCE, change); if (status.isOK()) { return getPage(IPreviewWizardPage.PAGE_NAME); } else { return getPage(ErrorWizardPage.PAGE_NAME); } } public boolean canFinish() { if (fForcePreviewReview && !fPreviewShown) return false; return super.canFinish(); } //---- Condition checking ------------------------------------------------------------ /* package */ final RefactoringStatus checkFinalConditions() { return internalCheckCondition(CheckConditionsOperation.FINAL_CONDITIONS); } private RefactoringStatus internalCheckCondition(int style) { CheckConditionsOperation op= new CheckConditionsOperation(fRefactoring, style); Exception exception= null; try { PlatformUI.getWorkbench().getProgressService().busyCursorWhile( new WorkbenchRunnableAdapter(op, ResourcesPlugin.getWorkspace().getRoot())); } catch (InterruptedException e) { exception= e; } catch (InvocationTargetException e) { exception= e; } RefactoringStatus status= null; if (exception != null) { RefactoringUIPlugin.log(exception); status= new RefactoringStatus(); status.addFatalError(RefactoringUIMessages.getString("RefactoringWizard.internal_error_1")); //$NON-NLS-1$ } else { status= op.getStatus(); } setConditionCheckingStatus(status, style); return status; } private void setConditionCheckingStatus(RefactoringStatus status, int style) { if ((style & CheckConditionsOperation.ALL_CONDITIONS) == CheckConditionsOperation.ALL_CONDITIONS) setConditionCheckingStatus(status); else if ((style & CheckConditionsOperation.INITIAL_CONDITONS) == CheckConditionsOperation.INITIAL_CONDITONS) setInitialConditionCheckingStatus(status); else if ((style & CheckConditionsOperation.FINAL_CONDITIONS) == CheckConditionsOperation.FINAL_CONDITIONS) setFinalConditionCheckingStatus(status); } private RefactoringStatus getConditionCheckingStatus() { return fConditionCheckingStatus; } /** * Sets the refactoring status. * * @param status the refactoring status to set. */ /* package */ final void setConditionCheckingStatus(RefactoringStatus status) { ErrorWizardPage page= (ErrorWizardPage)getPage(ErrorWizardPage.PAGE_NAME); if (page != null) page.setStatus(status); fConditionCheckingStatus= status; } /** * Sets the refactoring status returned from final condition checking. Any previously * computed initial status is merged into the given status before it is set to the * error page. * * @param status the final condition checking status to set */ private void setFinalConditionCheckingStatus(RefactoringStatus status) { RefactoringStatus newStatus= new RefactoringStatus(); if (fInitialConditionCheckingStatus != null) newStatus.merge(fInitialConditionCheckingStatus); newStatus.merge(status); setConditionCheckingStatus(newStatus); } //---- Change management ------------------------------------------------------------- /** * Note: This method is for internal use only. Clients are not allowed to call this method. * * @param api internal instance to avoid access from external clients * @param operation the create change operation * @param updateStatus flag indicating if status updating is requested * * @return the created change */ public final Change internalCreateChange(InternalAPI api, CreateChangeOperation operation, boolean updateStatus) { Assert.isNotNull(api); return createChange(operation, updateStatus, getContainer()); } /** * Note: This method is for internal use only. Clients are not allowed to call this method. * * @param api internal instance to avoid access from external clients * @param op the perform change operation * * @return whether the finish ended ok or not */ public final FinishResult internalPerformFinish(InternalAPI api, PerformChangeOperation op) { op.setUndoManager(RefactoringCore.getUndoManager(), fRefactoring.getName()); Shell parent= getContainer().getShell(); try{ getContainer().run(false, false, new WorkbenchRunnableAdapter(op, ResourcesPlugin.getWorkspace().getRoot())); } catch (InvocationTargetException e) { Throwable inner= e.getTargetException(); if (op.changeExecutionFailed()) { ChangeExceptionHandler handler= new ChangeExceptionHandler(parent, fRefactoring); if (inner instanceof RuntimeException) { handler.handle(op.getChange(), (RuntimeException)inner); return FinishResult.createException(); } else if (inner instanceof CoreException) { handler.handle(op.getChange(), (CoreException)inner); return FinishResult.createException(); } } ExceptionHandler.handle(e, parent, RefactoringUIMessages.getString("RefactoringWizard.refactoring"), //$NON-NLS-1$ RefactoringUIMessages.getString("RefactoringWizard.unexpected_exception_1")); //$NON-NLS-1$ return FinishResult.createException(); } catch (InterruptedException e) { return FinishResult.createInterrupted(); } return FinishResult.createOK(); } private Change createChange(CreateChangeOperation operation, boolean updateStatus, IRunnableContext context){ InvocationTargetException exception= null; try { context.run(true, fIsChangeCreationCancelable, new WorkbenchRunnableAdapter( operation, ResourcesPlugin.getWorkspace().getRoot())); } catch (InterruptedException e) { setConditionCheckingStatus(null); return null; } catch (InvocationTargetException e) { exception= e; } if (updateStatus) { RefactoringStatus status= null; if (exception != null) { status= new RefactoringStatus(); String msg= exception.getMessage(); if (msg != null) { status.addFatalError(RefactoringUIMessages.getFormattedString("RefactoringWizard.see_log", msg)); //$NON-NLS-1$ } else { status.addFatalError(RefactoringUIMessages.getString("RefactoringWizard.Internal_error")); //$NON-NLS-1$ } RefactoringUIPlugin.log(exception); } else { status= operation.getConditionCheckingStatus(); } setConditionCheckingStatus(status, operation.getConditionCheckingStyle()); } else { if (exception != null) ExceptionHandler.handle(exception, getContainer().getShell(), RefactoringUIMessages.getString("RefactoringWizard.refactoring"), //$NON-NLS-1$ RefactoringUIMessages.getString("RefactoringWizard.unexpected_exception")); //$NON-NLS-1$ } Change change= operation.getChange(); return change; } //---- Reimplementation of Wizard methods -------------------------------------------- public boolean performFinish() { Assert.isNotNull(fRefactoring); RefactoringWizardPage page= (RefactoringWizardPage)getContainer().getCurrentPage(); return page.performFinish(); } //---- Internal API, but public due to Java constraints ------------------------------ /** * Note: This method is for internal use only. Clients are not allowed to call this method. * * @param api internal instance to avoid access from external clients * * @return whether the wizard has a preview page or not. */ public final boolean internalHasPreviewPage(InternalAPI api) { Assert.isNotNull(api); return (fFlags & NO_PREVIEW_PAGE) == 0; } /** * Note: This method is for internal use only. Clients are not allowed to call this method. * * @param api internal instance to avoid access from external clients * * @return whether yes no button style is requested */ public final boolean internalIsYesNoStyle(InternalAPI api) { Assert.isNotNull(api); return (fFlags & YES_NO_BUTTON_STYLE) != 0; } /** * Note: This method is for internal use only. Clients are not allowed to call this method. * * @param api internal instance to avoid access from external clients * * @return whether the first node of the preview is supposed to be expanded */ public final boolean internalGetExpandFirstNode(InternalAPI api) { Assert.isNotNull(api); return (fFlags & PREVIEW_EXPAND_FIRST_NODE) != 0; } /** * Note: This method is for internal use only. Clients are not allowed to call this method. * * @param api internal instance to avoid access from external clients * @param change the change to set */ public final void internalSetChange(InternalAPI api, Change change){ Assert.isNotNull(api); IPreviewWizardPage page= (IPreviewWizardPage)getPage(IPreviewWizardPage.PAGE_NAME); if (page != null) page.setChange(change); fChange= change; } /** * Note: This method is for internal use only. Clients are not allowed to call this method. * * @param api internal instance to avoid access from external clients * @param shown a boolean indicating if the preview page has been shown or not */ public final void internalSetPreviewShown(InternalAPI api, boolean shown) { Assert.isNotNull(api); fPreviewShown= shown; getContainer().updateButtons(); } //---- Helper methods to check style bits -------------------------------------------- private boolean checkActivationOnOpen() { return (fFlags & CHECK_INITIAL_CONDITIONS_ON_OPEN) != 0; } }
51,345
Bug 51345 double clicking a search result leaves focus on search pane instead of editor
double clicking a search result should set focus to the editor pane as per double clicking a 'problem'. this assists rapid development as the developer can start editing the search result without manually changing focus. changing focus would not limit any user either as the search pane is most commonly used with a mouse.
resolved fixed
49697c9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T13:46:01Z
2004-02-09T01:26:40Z
org.eclipse.jdt.ui/ui
51,345
Bug 51345 double clicking a search result leaves focus on search pane instead of editor
double clicking a search result should set focus to the editor pane as per double clicking a 'problem'. this assists rapid development as the developer can start editing the search result without manually changing focus. changing focus would not limit any user either as the search pane is most commonly used with a mouse.
resolved fixed
49697c9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T13:46:01Z
2004-02-09T01:26:40Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/nls/search/NLSSearchResultPage.java
51,345
Bug 51345 double clicking a search result leaves focus on search pane instead of editor
double clicking a search result should set focus to the editor pane as per double clicking a 'problem'. this assists rapid development as the developer can start editing the search result without manually changing focus. changing focus would not limit any user either as the search pane is most commonly used with a mouse.
resolved fixed
49697c9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T13:46:01Z
2004-02-09T01:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchEditorOpener.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Common Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/cpl-v10.html * * Contributors: IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.search; import org.eclipse.core.resources.IFile; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.InternalClassFileEditorInput; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.search.internal.ui.SearchPlugin; import org.eclipse.search.ui.SearchUI; import org.eclipse.search.ui.text.Match; import org.eclipse.ui.IEditorDescriptor; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IEditorRegistry; import org.eclipse.ui.IReusableEditor; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.part.FileEditorInput; public class JavaSearchEditorOpener { private IEditorPart fEditor; public IEditorPart open(Match match) throws PartInitException, JavaModelException { IWorkbenchPage wbPage= JavaPlugin.getActivePage(); Object element= getElementToOpen(match); if (SearchUI.reuseEditor()) return showWithReuse(element, wbPage); else return showWithoutReuse(element, wbPage); } protected Object getElementToOpen(Match match) { return match.getElement(); } private IEditorPart showWithoutReuse(Object element, IWorkbenchPage wbPage) throws PartInitException, JavaModelException { IEditorPart editor= null; return EditorUtility.openInEditor(element, false); } private IEditorPart showWithReuse(Object element, IWorkbenchPage wbPage) throws JavaModelException { IFile file= getFile(element); if (file != null) { String editorID= getEditorID(file); return showInEditor(wbPage, new FileEditorInput(file), editorID); } else { IClassFile cf= getClassFile(element); if (cf != null) return showInEditor(wbPage, new InternalClassFileEditorInput(cf), JavaUI.ID_CF_EDITOR); } return null; } private IFile getFile(Object element) throws JavaModelException { if (element instanceof IFile) return (IFile) element; if (element instanceof IJavaElement) { IJavaElement jElement= (IJavaElement) element; ICompilationUnit cu= (ICompilationUnit) jElement.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { return (IFile) cu.getCorrespondingResource(); } IClassFile cf= (IClassFile) jElement.getAncestor(IJavaElement.CLASS_FILE); if (cf != null) return (IFile) cf.getCorrespondingResource(); } return null; } private String getEditorID(IFile file) { IEditorDescriptor desc= IDE.getDefaultEditor(file); if (desc == null) return SearchPlugin.getDefault().getWorkbench().getEditorRegistry().findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID).getId(); else return desc.getId(); } private boolean isPinned(IEditorPart editor) { if (editor == null) return false; IEditorReference[] editorRefs= editor.getEditorSite().getPage().getEditorReferences(); int i= 0; while (i < editorRefs.length) { if (editor.equals(editorRefs[i].getEditor(false))) return editorRefs[i].isPinned(); i++; } return false; } private IEditorPart showInEditor(IWorkbenchPage page, IEditorInput input, String editorId) { IEditorPart editor= page.findEditor(input); if (editor != null) page.bringToTop(editor); else { boolean isOpen= false; if (fEditor != null) { IEditorReference[] parts= page.getEditorReferences(); int i= 0; while (!isOpen && i < parts.length) isOpen= fEditor == parts[i++].getEditor(false); } boolean canBeReused= isOpen && !fEditor.isDirty() && !isPinned(fEditor); boolean showsSameInputType= fEditor != null && fEditor.getSite().getId().equals(editorId); if (canBeReused && !showsSameInputType) { page.closeEditor(fEditor, false); fEditor= null; } if (canBeReused && showsSameInputType) { ((IReusableEditor) fEditor).setInput(input); page.bringToTop(fEditor); editor= fEditor; } else { try { editor= page.openEditor(input, editorId, false); if (editor instanceof IReusableEditor) fEditor= editor; else fEditor= null; } catch (PartInitException ex) { MessageDialog.openError(JavaPlugin.getActiveWorkbenchShell(), SearchMessages.getString("Search.Error.openEditor.title"), SearchMessages.getString("Search.Error.openEditor.message")); //$NON-NLS-2$ //$NON-NLS-1$ return null; } } } return editor; } private IClassFile getClassFile(Object element) { if (!(element instanceof IJavaElement)) return null; if (element instanceof IClassFile) return (IClassFile) element; IJavaElement jElement= (IJavaElement) element; if (jElement instanceof IMember) return ((IMember) jElement).getClassFile(); return null; } }
51,345
Bug 51345 double clicking a search result leaves focus on search pane instead of editor
double clicking a search result should set focus to the editor pane as per double clicking a 'problem'. this assists rapid development as the developer can start editing the search result without manually changing focus. changing focus would not limit any user either as the search pane is most commonly used with a mouse.
resolved fixed
49697c9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T13:46:01Z
2004-02-09T01:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchResultPage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.search; import java.text.MessageFormat; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.search.IMatchPresentation; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.viewers.DecoratingLabelProvider; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.search.ui.IContextMenuConstants; import org.eclipse.search.ui.ISearchResult; import org.eclipse.search.ui.ISearchResultViewPart; import org.eclipse.search.ui.NewSearchUI; import org.eclipse.search.ui.SearchUI; import org.eclipse.search.ui.text.AbstractTextSearchResult; import org.eclipse.search.ui.text.AbstractTextSearchViewPage; import org.eclipse.search.ui.text.Match; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Widget; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IMemento; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.part.IPageSite; import org.eclipse.ui.part.IShowInTargetList; import org.eclipse.ui.texteditor.ITextEditor; public class JavaSearchResultPage extends AbstractTextSearchViewPage implements IAdaptable { private static final String KEY_GROUPING= "org.eclipse.jdt.search.resultpage.grouping"; //$NON-NLS-1$ private static final String KEY_SORTING= "org.eclipse.jdt.search.resultpage.sorting"; //$NON-NLS-1$ private static final String KEY_FILTERS= "org.eclipse.jdt.search.resultpage.filters"; //$NON-NLS-1$ private static final String GROUP_GROUPING= "org.eclipse.jdt.search.resultpage.grouping"; //$NON-NLS-1$ private NewSearchViewActionGroup fActionGroup; private JavaSearchContentProvider fContentProvider; private int fCurrentSortOrder; private SortAction fSortByNameAction; private SortAction fSortByParentName; private SortAction fSortByPathAction; private GroupAction fGroupTypeAction; private GroupAction fGroupFileAction; private GroupAction fGroupPackageAction; private GroupAction fGroupProjectAction; private int fCurrentGrouping; private Set fMatchFilters= new HashSet(); private FilterAction[] fFilterActions; private static final String[] SHOW_IN_TARGETS= new String[] { JavaUI.ID_PACKAGES }; private static final IShowInTargetList SHOW_IN_TARGET_LIST= new IShowInTargetList() { public String[] getShowInTargetIds() { return SHOW_IN_TARGETS; } }; private JavaSearchEditorOpener fEditorOpener= new JavaSearchEditorOpener(); public JavaSearchResultPage() { initSortActions(); initGroupingActions(); initFilterActions(); } private void initFilterActions() { MatchFilter[] allFilters= MatchFilter.allFilters(); fFilterActions= new FilterAction[allFilters.length]; for (int i= 0; i < fFilterActions.length; i++) { fFilterActions[i]= new FilterAction(this, allFilters[i]); } } private void initSortActions() { fSortByNameAction= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByName"), this, SortingLabelProvider.SHOW_ELEMENT_CONTAINER); //$NON-NLS-1$ fSortByPathAction= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByPath"), this, SortingLabelProvider.SHOW_PATH); //$NON-NLS-1$ fSortByParentName= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByParentName"), this, SortingLabelProvider.SHOW_CONTAINER_ELEMENT); //$NON-NLS-1$ } private void initGroupingActions() { fGroupProjectAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_project"), SearchMessages.getString("JavaSearchResultPage.groupby_project.tooltip"), this, LevelTreeContentProvider.LEVEL_PROJECT); //$NON-NLS-1$ //$NON-NLS-2$ JavaPluginImages.setLocalImageDescriptors(fGroupProjectAction, "prj_mode.gif"); //$NON-NLS-1$ fGroupPackageAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_package"), SearchMessages.getString("JavaSearchResultPage.groupby_package.tooltip"), this, LevelTreeContentProvider.LEVEL_PACKAGE); //$NON-NLS-1$ //$NON-NLS-2$ JavaPluginImages.setLocalImageDescriptors(fGroupPackageAction, "package_mode.gif"); //$NON-NLS-1$ fGroupFileAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_file"), SearchMessages.getString("JavaSearchResultPage.groupby_file.tooltip"), this, LevelTreeContentProvider.LEVEL_FILE); //$NON-NLS-1$ //$NON-NLS-2$ JavaPluginImages.setLocalImageDescriptors(fGroupFileAction, "file_mode.gif"); //$NON-NLS-1$ fGroupTypeAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_type"), SearchMessages.getString("JavaSearchResultPage.groupby_type.tooltip"), this, LevelTreeContentProvider.LEVEL_TYPE); //$NON-NLS-1$ //$NON-NLS-2$ JavaPluginImages.setLocalImageDescriptors(fGroupTypeAction, "type_mode.gif"); //$NON-NLS-1$ } public void setViewPart(ISearchResultViewPart part) { super.setViewPart(part); fActionGroup= new NewSearchViewActionGroup(part); } public void showMatch(Match match, int offset, int length) throws PartInitException { IEditorPart editor; try { editor= fEditorOpener.open(match); } catch (JavaModelException e) { throw new PartInitException(e.getStatus()); } Object element= match.getElement(); if (editor instanceof ITextEditor) { ITextEditor textEditor= (ITextEditor) editor; textEditor.selectAndReveal(offset, length); } else if (editor != null){ if (element instanceof IFile) { IFile file= (IFile) element; showWithMarker(editor, file, offset, length); } } else { JavaSearchResult result= (JavaSearchResult) getInput(); IMatchPresentation participant= result.getSearchParticpant(element); if (participant != null) participant.showMatch(match, offset, length); } } private void showWithMarker(IEditorPart editor, IFile file, int offset, int length) throws PartInitException { try { IMarker marker= file.createMarker(SearchUI.SEARCH_MARKER); HashMap attributes= new HashMap(4); attributes.put(IMarker.CHAR_START, new Integer(offset)); attributes.put(IMarker.CHAR_END, new Integer(offset + length)); marker.setAttributes(attributes); IDE.gotoMarker(editor, marker); marker.delete(); } catch (CoreException e) { throw new PartInitException(SearchMessages.getString("JavaSearchResultPage.error.marker"), e); //$NON-NLS-1$ } } protected void fillContextMenu(IMenuManager mgr) { super.fillContextMenu(mgr); addSortActions(mgr); fActionGroup.setContext(new ActionContext(getSite().getSelectionProvider().getSelection())); fActionGroup.fillContextMenu(mgr); } private void addFilterActions(IMenuManager viewMenu) { String filteringGroup= "Filtering"; //$NON-NLS-1$ viewMenu.add(new Separator(filteringGroup)); MenuManager mgr= new MenuManager(SearchMessages.getString("JavaSearchResultPage.filter.submenu")); //$NON-NLS-1$ for (int i= 0; i < fFilterActions.length; i++) { mgr.add(fFilterActions[i]); } viewMenu.appendToGroup(filteringGroup, mgr); } private void addSortActions(IMenuManager mgr) { if (getLayout() != FLAG_LAYOUT_FLAT) return; MenuManager sortMenu= new MenuManager(SearchMessages.getString("JavaSearchResultPage.sortBylabel")); //$NON-NLS-1$ sortMenu.add(fSortByNameAction); sortMenu.add(fSortByPathAction); sortMenu.add(fSortByParentName); fSortByNameAction.setChecked(fCurrentSortOrder == fSortByNameAction.getSortOrder()); fSortByPathAction.setChecked(fCurrentSortOrder == fSortByPathAction.getSortOrder()); fSortByParentName.setChecked(fCurrentSortOrder == fSortByParentName.getSortOrder()); mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, sortMenu); } protected void fillToolbar(IToolBarManager tbm) { super.fillToolbar(tbm); if (getLayout() != FLAG_LAYOUT_FLAT) addGroupActions(tbm); } private void addGroupActions(IToolBarManager mgr) { mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, new Separator(GROUP_GROUPING)); mgr.appendToGroup(GROUP_GROUPING, fGroupProjectAction); mgr.appendToGroup(GROUP_GROUPING, fGroupPackageAction); mgr.appendToGroup(GROUP_GROUPING, fGroupFileAction); mgr.appendToGroup(GROUP_GROUPING, fGroupTypeAction); updateGroupingActions(); } private void updateGroupingActions() { fGroupProjectAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_PROJECT); fGroupPackageAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_PACKAGE); fGroupFileAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_FILE); fGroupTypeAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_TYPE); } public void dispose() { fActionGroup.dispose(); super.dispose(); } protected void elementsChanged(Object[] objects) { if (fContentProvider != null) fContentProvider.elementsChanged(objects); } protected void clear() { if (fContentProvider != null) fContentProvider.clear(); } protected void configureTableViewer(TableViewer viewer) { viewer.setUseHashlookup(true); viewer.setLabelProvider(new DecoratingLabelProvider(new SortingLabelProvider(this), PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator())); fContentProvider=new JavaSearchTableContentProvider(this); viewer.setContentProvider(fContentProvider); setSortOrder(fCurrentSortOrder); } protected void configureTreeViewer(TreeViewer viewer) { viewer.setUseHashlookup(true); viewer.setSorter(new ViewerSorter()); viewer.setLabelProvider(new DecoratingLabelProvider(new PostfixLabelProvider(this), PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator())); fContentProvider= new LevelTreeContentProvider(this, fCurrentGrouping); viewer.setContentProvider(fContentProvider); } protected TreeViewer createTreeViewer(Composite parent) { return new ProblemTreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); } class MyProblemTable extends ProblemTableViewer { MyProblemTable(Composite parent, int flags) { super(parent, flags); } protected void internalRefresh(Object element, boolean updateLabels) { if (element == null || equals(element, getRoot())) { // the parent // in the code below, it is important to do all disassociates // before any associates, since a later disassociate can undo an earlier associate // e.g. if (a, b) is replaced by (b, a), the disassociate of b to item 1 could undo // the associate of b to item 0. Object[] children = getSortedChildren(getRoot()); getTable().removeAll(); // add any remaining elements for (int i = 0; i < children.length; ++i) { updateItem(new TableItem(getTable(), SWT.NONE, i), children[i]); } } else { Widget w = findItem(element); if (w != null) { updateItem(w, element); } } } } protected TableViewer createTableViewer(Composite parent) { return new ProblemTableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); } void setSortOrder(int order) { fCurrentSortOrder= order; StructuredViewer viewer= getViewer(); viewer.getControl().setRedraw(false); DecoratingLabelProvider dlp= (DecoratingLabelProvider) viewer.getLabelProvider(); ((SortingLabelProvider)dlp.getLabelProvider()).setOrder(order); if (order == SortingLabelProvider.SHOW_ELEMENT_CONTAINER) { viewer.setSorter(new NameSorter()); } else if (order == SortingLabelProvider.SHOW_PATH) { viewer.setSorter(new PathSorter()); } else viewer.setSorter(new ParentSorter()); viewer.getControl().setRedraw(true); getSettings().put(KEY_SORTING, fCurrentSortOrder); } public void init(IPageSite site) { super.init(site); fActionGroup.fillActionBars(site.getActionBars()); addFilterActions(site.getActionBars().getMenuManager()); } /** * Precondition here: the viewer must be showing a tree with a LevelContentProvider. * @param order */ void setGrouping(int grouping) { fCurrentGrouping= grouping; StructuredViewer viewer= getViewer(); LevelTreeContentProvider cp= (LevelTreeContentProvider) viewer.getContentProvider(); cp.setLevel(grouping); updateGroupingActions(); getSettings().put(KEY_GROUPING, fCurrentGrouping); } protected StructuredViewer getViewer() { // override so that it's visible in the package. return super.getViewer(); } /* (non-Javadoc) * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#restoreState(org.eclipse.ui.IMemento) */ public void restoreState(IMemento memento) { super.restoreState(memento); try { fCurrentSortOrder= getSettings().getInt(KEY_SORTING); } catch (NumberFormatException e) { fCurrentSortOrder= SortingLabelProvider.SHOW_ELEMENT_CONTAINER; } try { fCurrentGrouping= getSettings().getInt(KEY_GROUPING); } catch (NumberFormatException e) { fCurrentGrouping= LevelTreeContentProvider.LEVEL_PACKAGE; } String encodedFilters= getSettings().get(KEY_FILTERS); restoreFilters(encodedFilters); if (memento != null) { Integer value= memento.getInteger(KEY_GROUPING); if (value != null) fCurrentGrouping= value.intValue(); value= memento.getInteger(KEY_SORTING); if (value != null) fCurrentSortOrder= value.intValue(); encodedFilters= memento.getString(KEY_FILTERS); restoreFilters(encodedFilters); } } private void restoreFilters(String encodedFilters) { if (encodedFilters != null) { fMatchFilters.clear(); String[] decodedFilters= decodeFiltersString(encodedFilters); for (int i= 0; i < decodedFilters.length; i++) { MatchFilter filter= findMatchFilter(decodedFilters[i]); if (filter != null) fMatchFilters.add(filter); } } updateFilterActions(); } private MatchFilter findMatchFilter(String id) { MatchFilter[] allFilters= MatchFilter.allFilters(); for (int i= 0; i < allFilters.length; i++) { if (allFilters[i].getID().equals(id)) return allFilters[i]; } return null; } /* (non-Javadoc) * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#saveState(org.eclipse.ui.IMemento) */ public void saveState(IMemento memento) { super.saveState(memento); memento.putInteger(KEY_GROUPING, fCurrentGrouping); memento.putInteger(KEY_SORTING, fCurrentSortOrder); memento.putString(KEY_FILTERS, encodeFilters()); } void addMatchFilter(MatchFilter filter) { fMatchFilters.add(filter); filtersChanged(); } void removeMatchFilter(MatchFilter filter) { fMatchFilters.remove(filter); filtersChanged(); } private void filtersChanged() { StructuredViewer viewer= getViewer(); JavaSearchContentProvider cp= (JavaSearchContentProvider) viewer.getContentProvider(); cp.filtersChanged(getMatchFilters()); updateFilterActions(); getViewPart().updateLabel(); getSettings().put(KEY_FILTERS, encodeFilters()); } private void updateFilterActions() { for (int i= 0; i < fFilterActions.length; i++) { fFilterActions[i].updateCheckState(); } getSite().getActionBars().updateActionBars(); getSite().getActionBars().getMenuManager().updateAll(true); } private String encodeFilters() { StringBuffer buf= new StringBuffer(); MatchFilter[] enabledFilters= getMatchFilters(); buf.append(enabledFilters.length); for (int i= 0; i < enabledFilters.length; i++) { buf.append(';'); buf.append(enabledFilters[i].getID()); } return buf.toString(); } private String[] decodeFiltersString(String encodedString) { StringTokenizer tokenizer= new StringTokenizer(encodedString, ";"); //$NON-NLS-1$ int count= Integer.valueOf(tokenizer.nextToken()).intValue(); String[] ids= new String[count]; for (int i= 0; i < count; i++) { ids[i]= tokenizer.nextToken(); } return ids; } boolean hasMatchFilter(MatchFilter filter) { return fMatchFilters.contains(filter); } MatchFilter[] getMatchFilters() { MatchFilter[] filters= new MatchFilter[fMatchFilters.size()]; return (MatchFilter[]) fMatchFilters.toArray(filters); } public int getDisplayedMatchCount(Object element) { if (getMatchFilters().length == 0) return super.getDisplayedMatchCount(element); Match[] matches= super.getDisplayedMatches(element); int count= 0; for (int i= 0; i < matches.length; i++) { if (!isFiltered(matches[i])) count++; } return count; } public Match[] getDisplayedMatches(Object element) { if (getMatchFilters().length == 0) return super.getDisplayedMatches(element); Match[] matches= super.getDisplayedMatches(element); int count= 0; for (int i= 0; i < matches.length; i++) { if (isFiltered(matches[i])) matches[i]= null; else count++; } Match[] filteredMatches= new Match[count]; int writeIndex= 0; for (int i= 0; i < matches.length; i++) { if (matches[i] != null) filteredMatches[writeIndex++]= matches[i]; } return filteredMatches; } private boolean isFiltered(Match match) { MatchFilter[] filters= getMatchFilters(); for (int j= 0; j < filters.length; j++) { if ((match instanceof JavaElementMatch) && filters[j].filters((JavaElementMatch) match)) return true; } return false; } public void setInput(ISearchResult search, Object viewState) { updateFilterEnablement((JavaSearchResult)search); super.setInput(search, viewState); } private void updateFilterEnablement(JavaSearchResult result) { for (int i= 0; i < fFilterActions.length; i++) { fFilterActions[i].setEnabled(shouldEnable(result, fFilterActions[i])); } } private boolean shouldEnable(JavaSearchResult result, FilterAction filterAction) { if (result == null) { return false; } JavaSearchQuery query= (JavaSearchQuery) result.getQuery(); if (query == null) return false; return filterAction.getFilter().isApplicable(query); } private boolean isQueryRunning() { AbstractTextSearchResult result= getInput(); if (result != null) { return NewSearchUI.isQueryRunning(result.getQuery()); } return false; } public String getLabel() { String label= super.getLabel(); int matchFilterCount= getMatchFiltersCount(); if (matchFilterCount > 0) { if (isQueryRunning()) { String message= SearchMessages.getString("JavaSearchResultPage.filtered.message"); //$NON-NLS-1$ return MessageFormat.format(message, new Object[] { label }); } else { String message= SearchMessages.getString("JavaSearchResultPage.filteredWithCount.message"); //$NON-NLS-1$ return MessageFormat.format(message, new Object[] { label, new Integer(getFilteredMatchCount()) }); } } return label; } private int getMatchFiltersCount() { MatchFilter[] filters= getMatchFilters(); AbstractTextSearchResult result= getInput(); if (result == null) return 0; int filterCount= 0; for (int i= 0; i < filters.length; i++) { if (filters[i].isApplicable((JavaSearchQuery) result.getQuery())) filterCount++; } return filterCount; } private int getFilteredMatchCount() { AbstractTextSearchResult result= getInput(); if (result == null) return 0; Object[] elements= result.getElements(); int count= 0; for (int i= 0; i < elements.length; i++) { count+= getDisplayedMatchCount(elements[i]); } return count; } /* (non-Javadoc) * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) */ public Object getAdapter(Class adapter) { if (IShowInTargetList.class.equals(adapter)) { return SHOW_IN_TARGET_LIST; } return null; } }
51,345
Bug 51345 double clicking a search result leaves focus on search pane instead of editor
double clicking a search result should set focus to the editor pane as per double clicking a 'problem'. this assists rapid development as the developer can start editing the search result without manually changing focus. changing focus would not limit any user either as the search pane is most commonly used with a mouse.
resolved fixed
49697c9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T13:46:01Z
2004-02-09T01:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/OccurrencesSearchResultPage.java
/******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.search; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.search.ui.text.AbstractTextSearchViewPage; import org.eclipse.search.ui.text.Match; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.texteditor.ITextEditor; public class OccurrencesSearchResultPage extends AbstractTextSearchViewPage { private TextSearchTableContentProvider fContentProvider; public OccurrencesSearchResultPage() { super(AbstractTextSearchViewPage.FLAG_LAYOUT_FLAT); } /* * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#showMatch(org.eclipse.search.ui.text.Match, int, int) */ protected void showMatch(Match match, int currentOffset, int currentLength) throws PartInitException { IEditorPart editor= null; JavaElementLine element= (JavaElementLine) match.getElement(); IJavaElement javaElement= element.getJavaElement(); try { editor= EditorUtility.openInEditor(javaElement, false); } catch (PartInitException e1) { return; } catch (JavaModelException e1) { return; } if (editor instanceof ITextEditor) { ITextEditor textEditor= (ITextEditor) editor; textEditor.selectAndReveal(currentOffset, currentLength); } } /* * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#elementsChanged(java.lang.Object[]) */ protected void elementsChanged(Object[] objects) { if (fContentProvider != null) fContentProvider.elementsChanged(objects); } /* * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#clear() */ protected void clear() { if (fContentProvider != null) fContentProvider.clear(); } /* * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#configureTreeViewer(org.eclipse.jface.viewers.TreeViewer) */ protected void configureTreeViewer(TreeViewer viewer) { throw new IllegalStateException("Doesn't support tree mode."); //$NON-NLS-1$ } /* * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#configureTableViewer(org.eclipse.jface.viewers.TableViewer) */ protected void configureTableViewer(TableViewer viewer) { viewer.setSorter(new JavaElementLineSorter()); viewer.setLabelProvider(new OccurrencesSearchLabelProvider(this)); fContentProvider= new TextSearchTableContentProvider(); viewer.setContentProvider(fContentProvider); } }
51,345
Bug 51345 double clicking a search result leaves focus on search pane instead of editor
double clicking a search result should set focus to the editor pane as per double clicking a 'problem'. this assists rapid development as the developer can start editing the search result without manually changing focus. changing focus would not limit any user either as the search pane is most commonly used with a mouse.
resolved fixed
49697c9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T13:46:01Z
2004-02-09T01:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/search/IMatchPresentation.java
/******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui.search; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.search.ui.text.Match; import org.eclipse.ui.PartInitException; /** * This interface serves to display elements that a search participant has contributed to a search * result. * <p> * Each <code>IMatchPresentation</code> is associated with a particular <code>IQueryParticipant</code>. The IMatchPresentation * will only be asked to handle elements and matches which its <code>IQueryParticipant</code> contributed to the * search result. If two search participants report matches against the same element, one of them will * be chosen to handle the element. * </p> * <p> * Clients may implement this interface. * </p> * @since 3.0 */ public interface IMatchPresentation { /** * Creates a new instance of a label provider for elments that have been contributed * to a search result by the corresponding query participant. The search view * will call this method when it needs to render elements and will dipose the * label providers when it is done with them. This method may therefore be called * multiple times. * @return A label provider for elements found by the corresponding query participant. */ ILabelProvider createLabelProvider(); /** * Opens an editor on the given element and selects the given range of text. * The location of matches are automatically updated when a file is edited * through the file buffer infrastructure (see {@link org.eclipse.core.filebuffers.ITextFileBufferManager}). * When a file buffer is saved, the current positions are written back to the * match. * * @param match * The match to show * @param currentOffset * The current start offset of the match * @param currentLength * The current length of the selection * @throws PartInitException * If an editor can't be opened. */ void showMatch(Match match, int currentOffset, int currentLength) throws PartInitException; }
44,204
Bug 44204 Promote individual methods to interface.
Methods should be able to be promoted to an implemented interface. IE interface SomeThing { public DoDad getDoDad(); } class MyThing implements Something { private DoDad doDad=new DoDad(); public DoDad getDoDad() { return doDad; } public void setDoDad(DoDad dad) { this.doDad=dad; } ^^^^^^^^ } Ctrl-1 on the ^'d should produce 'Declare in interface 'Something''. if more than on interface, multiple options should be given, much like what import does. This enhancement would save time copying, pasting and trimming. Regards, Andy
resolved fixed
37ef19b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T15:52:53Z
2003-10-05T16:06:40Z
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/AssistQuickFixTest.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Sebastian Davids <sdavids@gmx.de> - testInvertEquals1-23 *******************************************************************************/ package org.eclipse.jdt.ui.tests.quickfix; import java.util.Hashtable; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.core.runtime.Preferences; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.tests.core.ProjectTestSetup; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.correction.AssignToVariableAssistProposal; import org.eclipse.jdt.internal.ui.text.correction.AssistContext; import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal; import org.eclipse.jdt.internal.ui.text.correction.LinkedNamesAssistProposal; public class AssistQuickFixTest extends QuickFixTest { private static final Class THIS= AssistQuickFixTest.class; private IJavaProject fJProject1; private IPackageFragmentRoot fSourceFolder; public AssistQuickFixTest(String name) { super(name); } public static Test allTests() { return new ProjectTestSetup(new TestSuite(THIS)); } public static Test suite() { if (true) { return allTests(); } else { TestSuite suite= new TestSuite(); suite.addTest(new AssistQuickFixTest("testAddTypeToArrayInitializer")); return new ProjectTestSetup(suite); } } protected void setUp() throws Exception { Hashtable options= JavaCore.getDefaultOptions(); options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE); options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4"); JavaCore.setOptions(options); IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false); store.setValue(PreferenceConstants.CODEGEN_KEYWORD_THIS, false); Preferences corePrefs= JavaCore.getPlugin().getPluginPreferences(); corePrefs.setValue(JavaCore.CODEASSIST_FIELD_PREFIXES, ""); corePrefs.setValue(JavaCore.CODEASSIST_STATIC_FIELD_PREFIXES, ""); corePrefs.setValue(JavaCore.CODEASSIST_FIELD_SUFFIXES, ""); corePrefs.setValue(JavaCore.CODEASSIST_STATIC_FIELD_SUFFIXES, ""); fJProject1= ProjectTestSetup.getProject(); fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); } protected void tearDown() throws Exception { JavaProjectHelper.clear(fJProject1, ProjectTestSetup.getDefaultClasspath()); } public void testAssignToLocal() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" getClass();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); int offset= buf.toString().indexOf("getClass()"); AssistContext context= getCorrectionContext(cu, offset, 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private Class class1;\n"); buf.append("\n"); buf.append(" public void foo() {\n"); buf.append(" class1 = getClass();\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" Class class1 = getClass();\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testAssignToLocal2() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Vector;\n"); buf.append("public class E {\n"); buf.append(" public Vector goo() {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" goo().iterator();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); int offset= buf.toString().indexOf("goo().iterator()"); AssistContext context= getCorrectionContext(cu, offset, 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Iterator;\n"); buf.append("import java.util.Vector;\n"); buf.append("public class E {\n"); buf.append(" private Iterator iterator;\n"); buf.append(" public Vector goo() {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" iterator = goo().iterator();\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Iterator;\n"); buf.append("import java.util.Vector;\n"); buf.append("public class E {\n"); buf.append(" public Vector goo() {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" Iterator iterator = goo().iterator();\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testAssignToLocal3() throws Exception { // test prefixes and this qualification IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(PreferenceConstants.CODEGEN_KEYWORD_THIS, true); Preferences corePrefs= JavaCore.getPlugin().getPluginPreferences(); corePrefs.setValue(JavaCore.CODEASSIST_FIELD_PREFIXES, "f"); corePrefs.setValue(JavaCore.CODEASSIST_LOCAL_PREFIXES, "_"); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append("\n"); buf.append(" private int fCount;\n"); buf.append("\n"); buf.append(" public void foo() {\n"); buf.append(" System.getSecurityManager();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); int offset= buf.toString().indexOf("System"); AssistContext context= getCorrectionContext(cu, offset, 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append("\n"); buf.append(" private int fCount;\n"); buf.append(" private SecurityManager fManager;\n"); buf.append("\n"); buf.append(" public void foo() {\n"); buf.append(" this.fManager = System.getSecurityManager();\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append("\n"); buf.append(" private int fCount;\n"); buf.append("\n"); buf.append(" public void foo() {\n"); buf.append(" SecurityManager _manager = System.getSecurityManager();\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testAssignToLocal4() throws Exception { // test name conflict IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append("\n"); buf.append(" private int f;\n"); buf.append("\n"); buf.append(" public void foo() {\n"); buf.append(" Math.min(1.0f, 2.0f);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); int offset= buf.toString().indexOf("Math"); AssistContext context= getCorrectionContext(cu, offset, 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append("\n"); buf.append(" private int f;\n"); buf.append(" private float g;\n"); buf.append("\n"); buf.append(" public void foo() {\n"); buf.append(" g = Math.min(1.0f, 2.0f);\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append("\n"); buf.append(" private int f;\n"); buf.append("\n"); buf.append(" public void foo() {\n"); buf.append(" float g = Math.min(1.0f, 2.0f);\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testAssignToLocal5() throws Exception { // test prefixes and this qualification on static method IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(PreferenceConstants.CODEGEN_KEYWORD_THIS, true); Preferences corePrefs= JavaCore.getPlugin().getPluginPreferences(); corePrefs.setValue(JavaCore.CODEASSIST_FIELD_PREFIXES, "f"); corePrefs.setValue(JavaCore.CODEASSIST_STATIC_FIELD_PREFIXES, "fg"); corePrefs.setValue(JavaCore.CODEASSIST_LOCAL_PREFIXES, "_"); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append("\n"); buf.append(" private int fCount;\n"); buf.append("\n"); buf.append(" public static void foo() {\n"); buf.append(" System.getSecurityManager();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); int offset= buf.toString().indexOf("System"); AssistContext context= getCorrectionContext(cu, offset, 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append("\n"); buf.append(" private int fCount;\n"); buf.append(" private static SecurityManager fgManager;\n"); buf.append("\n"); buf.append(" public static void foo() {\n"); buf.append(" E.fgManager = System.getSecurityManager();\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append("\n"); buf.append(" private int fCount;\n"); buf.append("\n"); buf.append(" public static void foo() {\n"); buf.append(" SecurityManager _manager = System.getSecurityManager();\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testAssignToLocal6() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" static {\n"); buf.append(" getClass(); // comment\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); int offset= buf.toString().indexOf("getClass()"); AssistContext context= getCorrectionContext(cu, offset, 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private static Class class1;\n"); buf.append("\n"); buf.append(" static {\n"); buf.append(" class1 = getClass(); // comment\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" static {\n"); buf.append(" Class class1 = getClass(); // comment\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testAssignParamToField() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public E(int count) {\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); int offset= buf.toString().indexOf("count"); AssistContext context= getCorrectionContext(cu, offset, 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private final int count;\n"); buf.append("\n"); buf.append(" public E(int count) {\n"); buf.append(" this.count = count;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testAssignParamToField2() throws Exception { Preferences corePrefs= JavaCore.getPlugin().getPluginPreferences(); corePrefs.setValue(JavaCore.CODEASSIST_FIELD_PREFIXES, "f"); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Vector;\n"); buf.append("public class E {\n"); buf.append(" public E(int count, Vector vec[]) {\n"); buf.append(" super();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); int offset= buf.toString().indexOf("vec"); AssistContext context= getCorrectionContext(cu, offset, 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Vector;\n"); buf.append("public class E {\n"); buf.append(" private final Vector[] fVec;\n"); buf.append("\n"); buf.append(" public E(int count, Vector vec[]) {\n"); buf.append(" super();\n"); buf.append(" fVec = vec;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testAssignParamToField3() throws Exception { Preferences corePrefs= JavaCore.getPlugin().getPluginPreferences(); corePrefs.setValue(JavaCore.CODEASSIST_STATIC_FIELD_PREFIXES, "fg"); IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(PreferenceConstants.CODEGEN_KEYWORD_THIS, true); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Vector;\n"); buf.append("public class E {\n"); buf.append(" private int fgVec;\n"); buf.append("\n"); buf.append(" public static void foo(int count, Vector vec[]) {\n"); buf.append(" count++;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); int offset= buf.toString().indexOf("vec[]"); AssistContext context= getCorrectionContext(cu, offset, 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Vector;\n"); buf.append("public class E {\n"); buf.append(" private int fgVec;\n"); buf.append(" private static Vector[] fgVec2;\n"); buf.append("\n"); buf.append(" public static void foo(int count, Vector vec[]) {\n"); buf.append(" E.fgVec2 = vec;\n"); buf.append(" count++;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testAssignParamToField4() throws Exception { IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(PreferenceConstants.CODEGEN_KEYWORD_THIS, true); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private long count;\n"); buf.append("\n"); buf.append(" public void foo(int count) {\n"); buf.append(" count++;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); int offset= buf.toString().indexOf("int count"); AssistContext context= getCorrectionContext(cu, offset, 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private long count;\n"); buf.append(" private int count2;\n"); buf.append("\n"); buf.append(" public void foo(int count) {\n"); buf.append(" this.count2 = count;\n"); buf.append(" count++;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testAssignParamToField5() throws Exception { IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(PreferenceConstants.CODEGEN_KEYWORD_THIS, true); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private int p1;\n"); buf.append("\n"); buf.append(" public void foo(int p1, int p2) {\n"); buf.append(" this.p1 = p1;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); int offset= buf.toString().indexOf("int p2"); AssistContext context= getCorrectionContext(cu, offset, 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private int p1;\n"); buf.append(" private int p2;\n"); buf.append("\n"); buf.append(" public void foo(int p1, int p2) {\n"); buf.append(" this.p1 = p1;\n"); buf.append(" this.p2 = p2;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testAssignToLocal2CursorAtEnd() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Vector;\n"); buf.append("public class E {\n"); buf.append(" public Vector goo() {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" goo().toArray();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "goo().toArray();"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str) + str.length(), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Vector;\n"); buf.append("public class E {\n"); buf.append(" private Object[] objects;\n"); buf.append(" public Vector goo() {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" objects = goo().toArray();\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Vector;\n"); buf.append("public class E {\n"); buf.append(" public Vector goo() {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" Object[] objects = goo().toArray();\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testReplaceCatchClauseWithThrowsWithFinally() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" } finally {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "(IOException e)"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void foo() throws IOException {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } finally {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } finally {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testReplaceSingleCatchClauseWithThrows() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "(IOException e)"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str) + str.length(), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 3); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void foo() throws IOException {\n"); buf.append(" goo();\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" goo();\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(2); String preview3= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" } finally {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected3= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 }); } public void testUnwrapForLoop() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" for (int i= 0; i < 3; i++) {\n"); buf.append(" goo();\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "for"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str) + str.length(), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" goo();\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnwrapDoStatement() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" do {\n"); buf.append(" goo();\n"); buf.append(" goo();\n"); buf.append(" goo();\n"); buf.append(" } while (true);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "do"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str) + str.length(), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" goo();\n"); buf.append(" goo();\n"); buf.append(" goo();\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnwrapWhileLoop2Statements() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" while (true) {\n"); buf.append(" goo();\n"); buf.append(" System.out.println();\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "while"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str) + str.length(), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" goo();\n"); buf.append(" System.out.println();\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnwrapIfStatement() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" if (1+ 3 == 6) {\n"); buf.append(" StringBuffer buf= new StringBuffer();\n"); buf.append(" buf.append(1);\n"); buf.append(" buf.append(2);\n"); buf.append(" buf.append(3);\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "if"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str) + str.length(), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" StringBuffer buf= new StringBuffer();\n"); buf.append(" buf.append(1);\n"); buf.append(" buf.append(2);\n"); buf.append(" buf.append(3);\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" if (1+ 3 == 6) {\n"); buf.append(" StringBuffer buf= new StringBuffer();\n"); buf.append(" buf.append(1);\n"); buf.append(" buf.append(2);\n"); buf.append(" buf.append(3);\n"); buf.append(" } else {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testUnwrapTryStatement() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" StringBuffer buf= new StringBuffer();\n"); buf.append(" buf.append(1);\n"); buf.append(" buf.append(2);\n"); buf.append(" buf.append(3);\n"); buf.append(" } finally {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "try"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str) + str.length(), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" StringBuffer buf= new StringBuffer();\n"); buf.append(" buf.append(1);\n"); buf.append(" buf.append(2);\n"); buf.append(" buf.append(3);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnwrapAnonymous() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" Runnable run= new Runnable() {\n"); buf.append(" public void run() { \n"); buf.append(" throw new NullPointerException();\n"); buf.append(" }\n"); buf.append(" };\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "};"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" throw new NullPointerException();\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnwrapBlock() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" {\n"); buf.append(" { \n"); buf.append(" throw new NullPointerException();\n"); buf.append(" }//comment\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "}//comment"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" {\n"); buf.append(" throw new NullPointerException();\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnwrapParanthesis() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public int foo() {\n"); buf.append(" return (9+ 8);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "(9+ 8)"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public int foo() {\n"); buf.append(" return 9+ 8;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnwrapMethodInvocation() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public int foo() {\n"); buf.append(" return Math.abs(9+ 8);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "Math.abs(9+ 8)"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str) + str.length(), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public int foo() {\n"); buf.append(" return 9+ 8;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testSplitDeclaration1() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" int i = 9;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "9"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" int i;\n"); buf.append(" i = 9;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testSplitDeclaration2() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" for (int i = 0; i < 9; i++) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "0"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" int i;\n"); buf.append(" for (i = 0; i < 9; i++) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testSplitDeclaration3() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" final int i[] = null;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "i[]"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" int i[];\n"); buf.append(" i = null;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testJoinDeclaration1() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" int var[];\n"); buf.append(" var = null;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "var"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" int var[] = null;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testJoinDeclaration2() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" int var;\n"); buf.append(" for (var = 0; var < 9; var++) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "var"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" int var = 0;\n"); buf.append(" for (; var < 9; var++) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } private static final Class[] FILTER_EQ= { LinkedNamesAssistProposal.class, AssignToVariableAssistProposal.class }; public void testInvertEquals() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" \"a\".equals(\"b\");\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" \"b\".equals(\"a\");\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); cu= pack1.createCompilationUnit("E.java", buf.toString(), true, null); context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); proposal= (CUCorrectionProposal) proposals.get(0); preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" \"a\".equals(\"b\");\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvertEquals2() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" String s= \"a\";\n"); buf.append(" s.equals(\"a\");\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" String s= \"a\";\n"); buf.append(" \"a\".equals(s);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); cu= pack1.createCompilationUnit("E.java", buf.toString(), true, null); context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); proposal= (CUCorrectionProposal) proposals.get(0); preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" String s= \"a\";\n"); buf.append(" s.equals(\"a\");\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvertEquals3() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private String a= \"a\";\n"); buf.append(" private String b= \"b\";\n"); buf.append(" public void foo() {\n"); buf.append(" a.equals(b);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private String a= \"a\";\n"); buf.append(" private String b= \"b\";\n"); buf.append(" public void foo() {\n"); buf.append(" b.equals(a);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); cu= pack1.createCompilationUnit("E.java", buf.toString(), true, null); context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); proposal= (CUCorrectionProposal) proposals.get(0); preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private String a= \"a\";\n"); buf.append(" private String b= \"b\";\n"); buf.append(" public void foo() {\n"); buf.append(" a.equals(b);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvertEquals4() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("class S {\n"); buf.append(" protected String sup= \"a\";\n"); buf.append("}\n"); buf.append("public class E extends S {\n"); buf.append(" private String a= \"a\";\n"); buf.append(" public void foo() {\n"); buf.append(" sup.equals(this.a);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("class S {\n"); buf.append(" protected String sup= \"a\";\n"); buf.append("}\n"); buf.append("public class E extends S {\n"); buf.append(" private String a= \"a\";\n"); buf.append(" public void foo() {\n"); buf.append(" this.a.equals(sup);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); cu= pack1.createCompilationUnit("E.java", buf.toString(), true, null); context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); proposal= (CUCorrectionProposal) proposals.get(0); preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("class S {\n"); buf.append(" protected String sup= \"a\";\n"); buf.append("}\n"); buf.append("public class E extends S {\n"); buf.append(" private String a= \"a\";\n"); buf.append(" public void foo() {\n"); buf.append(" sup.equals(this.a);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvertEquals5() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("class A {\n"); buf.append(" static String A= \"a\";\n"); buf.append("}\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" \"a\".equals(A.A);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("class A {\n"); buf.append(" static String A= \"a\";\n"); buf.append("}\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" A.A.equals(\"a\");\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); cu= pack1.createCompilationUnit("E.java", buf.toString(), true, null); context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); proposal= (CUCorrectionProposal) proposals.get(0); preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("class A {\n"); buf.append(" static String A= \"a\";\n"); buf.append("}\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" \"a\".equals(A.A);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvertEquals6() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("class A {\n"); buf.append(" static String get() {\n"); buf.append(" return \"a\";\n"); buf.append(" }\n"); buf.append("}\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" \"a\".equals(A.get());\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); cu= pack1.createCompilationUnit("E.java", buf.toString(), true, null); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("class A {\n"); buf.append(" static String get() {\n"); buf.append(" return \"a\";\n"); buf.append(" }\n"); buf.append("}\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" A.get().equals(\"a\");\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); cu= pack1.createCompilationUnit("E.java", buf.toString(), true, null); context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); proposal= (CUCorrectionProposal) proposals.get(0); preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("class A {\n"); buf.append(" static String get() {\n"); buf.append(" return \"a\";\n"); buf.append(" }\n"); buf.append("}\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" \"a\".equals(A.get());\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvertEquals7() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" \"a\".getClass().equals(String.class);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" String.class.equals(\"a\".getClass());\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); cu= pack1.createCompilationUnit("E.java", buf.toString(), true, null); context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); proposal= (CUCorrectionProposal) proposals.get(0); preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" \"a\".getClass().equals(String.class);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvertEquals8() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" boolean x = false && \"a\".equals(get());\n"); buf.append(" }\n"); buf.append(" String get() {\n"); buf.append(" return \"a\";\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" boolean x = false && get().equals(\"a\");\n"); buf.append(" }\n"); buf.append(" String get() {\n"); buf.append(" return \"a\";\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); cu= pack1.createCompilationUnit("E.java", buf.toString(), true, null); context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); proposal= (CUCorrectionProposal) proposals.get(0); preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" boolean x = false && \"a\".equals(get());\n"); buf.append(" }\n"); buf.append(" String get() {\n"); buf.append(" return \"a\";\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvertEquals9() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" equals(new E());\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" new E().equals(this);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); cu= pack1.createCompilationUnit("E.java", buf.toString(), true, null); context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); proposal= (CUCorrectionProposal) proposals.get(0); preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" equals(new E());\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvertEquals10() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" \"a\".equals(null);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 0); assertCorrectLabels(proposals); } public void testInvertEquals11() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" boolean equals(Object o, boolean a) {\n"); buf.append(" return false;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" new E().equals(\"a\", false);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 0); assertCorrectLabels(proposals); context= getCorrectionContext(cu, buf.toString().lastIndexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 0); assertCorrectLabels(proposals); } public void testInvertEquals12() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" boolean equals(boolean b) {\n"); buf.append(" return false;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" new E().equals(false);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 0); assertCorrectLabels(proposals); context= getCorrectionContext(cu, buf.toString().lastIndexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 0); assertCorrectLabels(proposals); } public void testInvertEquals13() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" boolean equals(boolean b) {\n"); buf.append(" return false;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" new E().equals(true ? true : false);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 0); assertCorrectLabels(proposals); context= getCorrectionContext(cu, buf.toString().lastIndexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 0); assertCorrectLabels(proposals); } public void testInvertEquals14() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("class Super {\n"); buf.append(" protected boolean sBool= false;\n"); buf.append("}\n"); buf.append("public class E extends Super {\n"); buf.append(" boolean equals(boolean b) {\n"); buf.append(" return false;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" new E().equals(sBool);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 0); assertCorrectLabels(proposals); context= getCorrectionContext(cu, buf.toString().lastIndexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 0); assertCorrectLabels(proposals); } public void testInvertEquals15() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" boolean equals(int i) {\n"); buf.append(" return false;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" new E().equals(1 + 1);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 0); assertCorrectLabels(proposals); context= getCorrectionContext(cu, buf.toString().lastIndexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 0); assertCorrectLabels(proposals); } public void testInvertEquals16() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" boolean equals(int i) {\n"); buf.append(" return false;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" int i= 1;\n"); buf.append(" new E().equals(i + i);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 0); assertCorrectLabels(proposals); context= getCorrectionContext(cu, buf.toString().lastIndexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 0); assertCorrectLabels(proposals); } public void testInvertEquals17() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" \"a\".equals(null);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 0); assertCorrectLabels(proposals); } public void testInvertEquals18() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public boolean equals(Object o) {\n"); buf.append(" return super.equals(o);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 0); assertCorrectLabels(proposals); context= getCorrectionContext(cu, buf.toString().lastIndexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 0); assertCorrectLabels(proposals); } public void testInvertEquals19() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private String a= \"a\";\n"); buf.append(" public void foo() {\n"); buf.append(" a.equals((Object) \"a\");\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private String a= \"a\";\n"); buf.append(" public void foo() {\n"); buf.append(" ((Object) \"a\").equals(a);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); cu= pack1.createCompilationUnit("E.java", buf.toString(), true, null); context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); proposal= (CUCorrectionProposal) proposals.get(0); preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private String a= \"a\";\n"); buf.append(" public void foo() {\n"); buf.append(" a.equals((Object) \"a\");\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvertEquals20() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" String s= null;\n"); buf.append(" \"a\".equals(s = \"a\");\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" String s= null;\n"); buf.append(" (s = \"a\").equals(\"a\");\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); cu= pack1.createCompilationUnit("E.java", buf.toString(), true, null); context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); proposal= (CUCorrectionProposal) proposals.get(0); preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" String s= null;\n"); buf.append(" \"a\".equals(s = \"a\");\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvertEquals21() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" \"aaa\".equals(\"a\" + \"a\" + \"a\");\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" (\"a\" + \"a\" + \"a\").equals(\"aaa\");\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); cu= pack1.createCompilationUnit("E.java", buf.toString(), true, null); context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); proposal= (CUCorrectionProposal) proposals.get(0); preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" \"aaa\".equals(\"a\" + \"a\" + \"a\");\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvertEquals22() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" \"a\".equals(true ? \"a\" : \"b\");\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" (true ? \"a\" : \"b\").equals(\"a\");\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); cu= pack1.createCompilationUnit("E.java", buf.toString(), true, null); context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); proposal= (CUCorrectionProposal) proposals.get(0); preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" \"a\".equals(true ? \"a\" : \"b\");\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInvertEquals23() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" \"a\".equals((\"a\"));\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "equals"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); List proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" (\"a\").equals(\"a\");\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); cu= pack1.createCompilationUnit("E.java", buf.toString(), true, null); context= getCorrectionContext(cu, buf.toString().indexOf(str), 0); proposals= collectAssists(context, FILTER_EQ); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); proposal= (CUCorrectionProposal) proposals.get(0); preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" \"a\".equals(\"a\");\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testAddTypeToArrayInitializer() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" int[][] numbers= {{ 1, 2 }, { 3, 4 }, { 4, 5 }};\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); String str= "{{"; AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str) + str.length(), 0); List proposals= collectAssists(context, false); assertNumberOfProposals(proposals, 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= getPreviewContent(proposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" int[][] numbers= new int[][]{{ 1, 2 }, { 3, 4 }, { 4, 5 }};\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } }
44,204
Bug 44204 Promote individual methods to interface.
Methods should be able to be promoted to an implemented interface. IE interface SomeThing { public DoDad getDoDad(); } class MyThing implements Something { private DoDad doDad=new DoDad(); public DoDad getDoDad() { return doDad; } public void setDoDad(DoDad dad) { this.doDad=dad; } ^^^^^^^^ } Ctrl-1 on the ^'d should produce 'Declare in interface 'Something''. if more than on interface, multiple options should be given, much like what import does. This enhancement would save time copying, pasting and trimming. Regards, Andy
resolved fixed
37ef19b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T15:52:53Z
2003-10-05T16:06:40Z
org.eclipse.jdt.ui/core
44,204
Bug 44204 Promote individual methods to interface.
Methods should be able to be promoted to an implemented interface. IE interface SomeThing { public DoDad getDoDad(); } class MyThing implements Something { private DoDad doDad=new DoDad(); public DoDad getDoDad() { return doDad; } public void setDoDad(DoDad dad) { this.doDad=dad; } ^^^^^^^^ } Ctrl-1 on the ^'d should produce 'Declare in interface 'Something''. if more than on interface, multiple options should be given, much like what import does. This enhancement would save time copying, pasting and trimming. Regards, Andy
resolved fixed
37ef19b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T15:52:53Z
2003-10-05T16:06:40Z
extension/org/eclipse/jdt/internal/corext/dom/Bindings.java
44,204
Bug 44204 Promote individual methods to interface.
Methods should be able to be promoted to an implemented interface. IE interface SomeThing { public DoDad getDoDad(); } class MyThing implements Something { private DoDad doDad=new DoDad(); public DoDad getDoDad() { return doDad; } public void setDoDad(DoDad dad) { this.doDad=dad; } ^^^^^^^^ } Ctrl-1 on the ^'d should produce 'Declare in interface 'Something''. if more than on interface, multiple options should be given, much like what import does. This enhancement would save time copying, pasting and trimming. Regards, Andy
resolved fixed
37ef19b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T15:52:53Z
2003-10-05T16:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/AbstractMethodCompletionProposal.java
44,204
Bug 44204 Promote individual methods to interface.
Methods should be able to be promoted to an implemented interface. IE interface SomeThing { public DoDad getDoDad(); } class MyThing implements Something { private DoDad doDad=new DoDad(); public DoDad getDoDad() { return doDad; } public void setDoDad(DoDad dad) { this.doDad=dad; } ^^^^^^^^ } Ctrl-1 on the ^'d should produce 'Declare in interface 'Something''. if more than on interface, multiple options should be given, much like what import does. This enhancement would save time copying, pasting and trimming. Regards, Andy
resolved fixed
37ef19b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T15:52:53Z
2003-10-05T16:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NewDefiningMethodProposal.java
44,204
Bug 44204 Promote individual methods to interface.
Methods should be able to be promoted to an implemented interface. IE interface SomeThing { public DoDad getDoDad(); } class MyThing implements Something { private DoDad doDad=new DoDad(); public DoDad getDoDad() { return doDad; } public void setDoDad(DoDad dad) { this.doDad=dad; } ^^^^^^^^ } Ctrl-1 on the ^'d should produce 'Declare in interface 'Something''. if more than on interface, multiple options should be given, much like what import does. This enhancement would save time copying, pasting and trimming. Regards, Andy
resolved fixed
37ef19b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T15:52:53Z
2003-10-05T16:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NewMethodCompletionProposal.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.NamingConventions; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.core.dom.rewrite.ListRewrite; import org.eclipse.jdt.ui.CodeGeneration; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; public class NewMethodCompletionProposal extends LinkedCorrectionProposal { private static final String KEY_NAME= "name"; //$NON-NLS-1$ private static final String KEY_TYPE= "type"; //$NON-NLS-1$ private ASTNode fNode; // MethodInvocation, ConstructorInvocation, SuperConstructorInvocation, ClassInstanceCreation, SuperMethodInvocation private List fArguments; private ITypeBinding fSenderBinding; public NewMethodCompletionProposal(String label, ICompilationUnit targetCU, ASTNode invocationNode, List arguments, ITypeBinding binding, int relevance, Image image) { super(label, targetCU, null, relevance, image); fNode= invocationNode; fArguments= arguments; fSenderBinding= binding; } protected ASTRewrite getRewrite() throws CoreException { CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fNode); ASTNode typeDecl= astRoot.findDeclaringNode(fSenderBinding); ASTNode newTypeDecl= null; boolean isInDifferentCU; if (typeDecl != null) { isInDifferentCU= false; newTypeDecl= typeDecl; } else { isInDifferentCU= true; ASTParser astParser= ASTParser.newParser(AST.JLS2); astParser.setSource(getCompilationUnit()); astParser.setResolveBindings(true); astRoot= (CompilationUnit) astParser.createAST(null); newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey()); } if (newTypeDecl != null) { ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST()); ChildListPropertyDescriptor property= fSenderBinding.isAnonymous() ? AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY : TypeDeclaration.BODY_DECLARATIONS_PROPERTY; List members= (List) newTypeDecl.getStructuralProperty(property); MethodDeclaration newStub= getStub(rewrite, newTypeDecl); int insertIndex; if (isConstructor()) { insertIndex= findConstructorInsertIndex(members); } else if (!isInDifferentCU) { insertIndex= findMethodInsertIndex(members, fNode.getStartPosition()); } else { insertIndex= members.size(); } ListRewrite listRewriter= rewrite.getListRewrite(newTypeDecl, property); listRewriter.insertAt(newStub, insertIndex, null); if (!isInDifferentCU) { Name invocationName= getInvocationName(); if (invocationName != null) { addLinkedPosition(rewrite.track(invocationName), true, KEY_NAME); } } addLinkedPosition(rewrite.track(newStub.getName()), false, KEY_NAME); if (!newStub.isConstructor()) { addLinkedPosition(rewrite.track(newStub.getReturnType()), false, KEY_TYPE); } return rewrite; } return null; } private boolean isConstructor() { return fNode.getNodeType() != ASTNode.METHOD_INVOCATION && fNode.getNodeType() != ASTNode.SUPER_METHOD_INVOCATION; } private MethodDeclaration getStub(ASTRewrite rewrite, ASTNode targetTypeDecl) throws CoreException { AST ast= targetTypeDecl.getAST(); MethodDeclaration decl= ast.newMethodDeclaration(); decl.setConstructor(isConstructor()); decl.setModifiers(evaluateModifiers(targetTypeDecl)); decl.setName(ast.newSimpleName(getMethodName())); List arguments= fArguments; List params= decl.parameters(); int nArguments= arguments.size(); ArrayList takenNames= new ArrayList(nArguments); IVariableBinding[] declaredFields= fSenderBinding.getDeclaredFields(); for (int i= 0; i < declaredFields.length; i++) { // avoid to take parameter names that are equal to field names takenNames.add(declaredFields[i].getName()); } for (int i= 0; i < arguments.size(); i++) { Expression elem= (Expression) arguments.get(i); SingleVariableDeclaration param= ast.newSingleVariableDeclaration(); // argument type String argTypeKey= "arg_type_" + i; //$NON-NLS-1$ Type type= evaluateParameterTypes(ast, elem, argTypeKey); param.setType(type); // argument name String argNameKey= "arg_name_" + i; //$NON-NLS-1$ String name= evaluateParameterNames(takenNames, elem, type, argNameKey); param.setName(ast.newSimpleName(name)); params.add(param); addLinkedPosition(rewrite.track(param.getType()), false, argTypeKey); addLinkedPosition(rewrite.track(param.getName()), false, argNameKey); } Block body= null; String bodyStatement= ""; //$NON-NLS-1$ if (!isConstructor()) { Type returnType= evaluateMethodType(ast); if (returnType == null) { decl.setReturnType(ast.newPrimitiveType(PrimitiveType.VOID)); } else { decl.setReturnType(returnType); } if (!fSenderBinding.isInterface() && returnType != null) { ReturnStatement returnStatement= ast.newReturnStatement(); returnStatement.setExpression(ASTNodeFactory.newDefaultExpression(ast, returnType, 0)); bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n')); } } if (!fSenderBinding.isInterface()) { body= ast.newBlock(); String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), fSenderBinding.getName(), getMethodName(), isConstructor(), bodyStatement, String.valueOf('\n')); if (placeHolder != null) { ASTNode todoNode= rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT); body.statements().add(todoNode); } } decl.setBody(body); CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); if (settings.createComments && !fSenderBinding.isAnonymous()) { String string= CodeGeneration.getMethodComment(getCompilationUnit(), fSenderBinding.getName(), decl, null, String.valueOf('\n')); if (string != null) { Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC); decl.setJavadoc(javadoc); } } return decl; } private int findMethodInsertIndex(List decls, int currPos) { int nDecls= decls.size(); for (int i= 0; i < nDecls; i++) { ASTNode curr= (ASTNode) decls.get(i); if (curr instanceof MethodDeclaration && currPos < curr.getStartPosition() + curr.getLength()) { return i + 1; } } return nDecls; } private int findConstructorInsertIndex(List decls) { int nDecls= decls.size(); int lastMethod= 0; for (int i= nDecls - 1; i >= 0; i--) { ASTNode curr= (ASTNode) decls.get(i); if (curr instanceof MethodDeclaration) { if (((MethodDeclaration) curr).isConstructor()) { return i + 1; } lastMethod= i; } } return lastMethod; } private Name getInvocationName() { if (fNode instanceof MethodInvocation) { return ((MethodInvocation)fNode).getName(); } else if (fNode instanceof SuperMethodInvocation) { return ((SuperMethodInvocation)fNode).getName(); } else if (fNode instanceof ClassInstanceCreation) { return ((ClassInstanceCreation)fNode).getName(); } return null; } private String getMethodName() { if (fNode instanceof MethodInvocation) { return ((MethodInvocation)fNode).getName().getIdentifier(); } else if (fNode instanceof SuperMethodInvocation) { return ((SuperMethodInvocation)fNode).getName().getIdentifier(); } else { return fSenderBinding.getName(); // name of the class } } private int evaluateModifiers(ASTNode targetTypeDecl) { if (fSenderBinding.isInterface()) { // for interface members copy the modifiers from an existing field MethodDeclaration[] methodDecls= ((TypeDeclaration) targetTypeDecl).getMethods(); if (methodDecls.length > 0) { return methodDecls[0].getModifiers(); } return 0; } if (fNode instanceof MethodInvocation) { int modifiers= 0; Expression expression= ((MethodInvocation)fNode).getExpression(); if (expression != null) { if (expression instanceof Name && ((Name) expression).resolveBinding().getKind() == IBinding.TYPE) { modifiers |= Modifier.STATIC; } } else if (ASTResolving.isInStaticContext(fNode)) { modifiers |= Modifier.STATIC; } ASTNode node= ASTResolving.findParentType(fNode); if (targetTypeDecl.equals(node)) { modifiers |= Modifier.PRIVATE; } else if (node instanceof AnonymousClassDeclaration && ASTNodes.isParent(node, targetTypeDecl)) { modifiers |= Modifier.PROTECTED; } else { modifiers |= Modifier.PUBLIC; } return modifiers; } return Modifier.PUBLIC; } private Type evaluateMethodType(AST ast) throws CoreException { ITypeBinding binding= ASTResolving.guessBindingForReference(fNode); if (binding != null) { String typeName= getImportRewrite().addImport(binding); return ASTNodeFactory.newType(ast, typeName); } else { ASTNode parent= fNode.getParent(); if (parent instanceof ExpressionStatement) { return null; } Type type= ASTResolving.guessTypeForReference(ast, fNode); if (type != null) { return type; } return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ } } private Type evaluateParameterTypes(AST ast, Expression elem, String key) throws CoreException { ITypeBinding binding= Bindings.normalizeTypeBinding(elem.resolveTypeBinding()); if (binding != null) { ITypeBinding[] typeProposals= ASTResolving.getRelaxingTypes(ast, binding); for (int i= 0; i < typeProposals.length; i++) { addLinkedPositionProposal(key, typeProposals[i]); } String typeName= getImportRewrite().addImport(binding); return ASTNodeFactory.newType(ast, typeName); } return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ } private String evaluateParameterNames(ArrayList takenNames, Expression argNode, Type type, String key) { IJavaProject project= getCompilationUnit().getJavaProject(); String[] excludedNames= (String[]) takenNames.toArray(new String[takenNames.size()]); String favourite= null; if (argNode instanceof SimpleName) { SimpleName name= (SimpleName) argNode; favourite= StubUtility.suggestArgumentName(project, name.getIdentifier(), excludedNames); } int dim= 0; if (type.isArrayType()) { ArrayType arrayType= (ArrayType) type; dim= arrayType.getDimensions(); type= arrayType.getElementType(); } String typeName= ASTNodes.asString(type); String packName= Signature.getQualifier(typeName); String[] names= NamingConventions.suggestArgumentNames(project, packName, typeName, dim, excludedNames); if (favourite == null) { favourite= names[0]; } for (int i= 0; i < names.length; i++) { addLinkedPositionProposal(key, names[i], null); } takenNames.add(favourite); return favourite; } }
44,204
Bug 44204 Promote individual methods to interface.
Methods should be able to be promoted to an implemented interface. IE interface SomeThing { public DoDad getDoDad(); } class MyThing implements Something { private DoDad doDad=new DoDad(); public DoDad getDoDad() { return doDad; } public void setDoDad(DoDad dad) { this.doDad=dad; } ^^^^^^^^ } Ctrl-1 on the ^'d should produce 'Declare in interface 'Something''. if more than on interface, multiple options should be given, much like what import does. This enhancement would save time copying, pasting and trimming. Regards, Andy
resolved fixed
37ef19b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T15:52:53Z
2003-10-05T16:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessor.java
/******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Sebastian Davids <sdavids@gmx.de> - Bug 37432 getInvertEqualsProposal *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.core.dom.rewrite.ListRewrite; import org.eclipse.jdt.ui.text.java.IInvocationContext; import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal; import org.eclipse.jdt.ui.text.java.IProblemLocation; import org.eclipse.jdt.ui.text.java.IQuickAssistProcessor; import org.eclipse.jdt.internal.corext.codemanipulation.ImportRewrite; import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder; import org.eclipse.jdt.internal.corext.dom.NodeFinder; import org.eclipse.jdt.internal.ui.JavaPluginImages; /** */ public class QuickAssistProcessor implements IQuickAssistProcessor { public QuickAssistProcessor() { super(); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.text.correction.IAssistProcessor#hasAssists(org.eclipse.jdt.internal.ui.text.correction.IAssistContext) */ public boolean hasAssists(IInvocationContext context) throws CoreException { ASTNode coveringNode= getCoveringNode(context); if (coveringNode != null) { return getCatchClauseToThrowsProposals(context, coveringNode, null) || getRenameLocalProposals(context, coveringNode, null, null) || getAssignToVariableProposals(context, coveringNode, null) || getUnWrapProposals(context, coveringNode, null) || getAssignParamToFieldProposals(context, coveringNode, null) || getJoinVariableProposals(context, coveringNode, null) || getAddFinallyProposals(context, coveringNode, null) || getAddElseProposals(context, coveringNode, null) || getSplitVariableProposals(context, coveringNode, null) || getAddBlockProposals(context, coveringNode, null) || getArrayInitializerToArrayCreation(context, coveringNode, null) || getInvertEqualsProposal(context, coveringNode, null); } return false; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.text.correction.IAssistProcessor#getAssists(org.eclipse.jdt.internal.ui.text.correction.IAssistContext, org.eclipse.jdt.internal.ui.text.correction.IProblemLocation[]) */ public IJavaCompletionProposal[] getAssists(IInvocationContext context, IProblemLocation[] locations) throws CoreException { ASTNode coveringNode= getCoveringNode(context); if (coveringNode != null) { ArrayList resultingCollections= new ArrayList(); // quick assists that show up also if there is an error/warning getRenameLocalProposals(context, coveringNode, locations, resultingCollections); if (noErrorsAtLocation(locations)) { getCatchClauseToThrowsProposals(context, coveringNode, resultingCollections); getAssignToVariableProposals(context, coveringNode, resultingCollections); getAssignParamToFieldProposals(context, coveringNode, resultingCollections); getUnWrapProposals(context, coveringNode, resultingCollections); getSplitVariableProposals(context, coveringNode, resultingCollections); getJoinVariableProposals(context, coveringNode, resultingCollections); getAddFinallyProposals(context, coveringNode, resultingCollections); getAddElseProposals(context, coveringNode, resultingCollections); getAddBlockProposals(context, coveringNode, resultingCollections); getInvertEqualsProposal(context, coveringNode, resultingCollections); getArrayInitializerToArrayCreation(context, coveringNode, resultingCollections); } return (IJavaCompletionProposal[]) resultingCollections.toArray(new IJavaCompletionProposal[resultingCollections.size()]); } return null; } private boolean noErrorsAtLocation(IProblemLocation[] locations) { if (locations != null) { for (int i= 0; i < locations.length; i++) { if (locations[i].isError()) { return false; } } } return true; } private boolean getJoinVariableProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) { ASTNode parent= node.getParent(); if (!(parent instanceof VariableDeclarationFragment)) { return false; } VariableDeclarationFragment fragment= (VariableDeclarationFragment) parent; IVariableBinding binding= fragment.resolveBinding(); if (fragment.getInitializer() != null || binding == null || binding.isField()) { return false; } if (!(fragment.getParent() instanceof VariableDeclarationStatement)) { return false; } VariableDeclarationStatement statement= (VariableDeclarationStatement) fragment.getParent(); SimpleName[] names= LinkedNodeFinder.findByBinding(statement.getParent(), binding); if (names.length <= 1 || names[0] != fragment.getName()) { return false; } SimpleName firstAccess= names[1]; if (!(firstAccess.getParent() instanceof Assignment)) { return false; } Assignment assignment= (Assignment) firstAccess.getParent(); if (assignment.getLeftHandSide() != firstAccess) { return false; } ASTNode assignParent= assignment.getParent(); if (!(assignParent instanceof ExpressionStatement || assignParent instanceof ForStatement && ((ForStatement) assignParent).initializers().contains(assignment))) { return false; } if (resultingCollections == null) { return true; } AST ast= statement.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); String label= CorrectionMessages.getString("QuickAssistProcessor.joindeclaration.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image); Expression placeholder= (Expression) rewrite.createMoveTarget(assignment.getRightHandSide()); rewrite.set(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, placeholder, null); if (assignParent instanceof ExpressionStatement) { int statementParent= assignParent.getParent().getNodeType(); if (statementParent == ASTNode.IF_STATEMENT || statementParent == ASTNode.WHILE_STATEMENT || statementParent == ASTNode.DO_STATEMENT || statementParent == ASTNode.FOR_STATEMENT) { Block block= ast.newBlock(); rewrite.replace(assignParent, block, null); } else { rewrite.remove(assignParent, null); } } else { rewrite.remove(assignment, null); } proposal.setEndPosition(rewrite.track(fragment.getName())); resultingCollections.add(proposal); return true; } private boolean getSplitVariableProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) { ASTNode parent= node.getParent(); if (!(parent instanceof VariableDeclarationFragment)) { return false; } VariableDeclarationFragment fragment= (VariableDeclarationFragment) parent; if (fragment.getInitializer() == null) { return false; } Statement statement; ASTNode fragParent= fragment.getParent(); if (fragParent instanceof VariableDeclarationStatement) { statement= (VariableDeclarationStatement) fragParent; } else if (fragParent instanceof VariableDeclarationExpression) { statement= (Statement) fragParent.getParent(); } else { return false; } // statement is ForStatement or VariableDeclarationStatement ASTNode statementParent= statement.getParent(); StructuralPropertyDescriptor property= statement.getLocationInParent(); if (!property.isChildListProperty()) { return false; } List list= (List) statementParent.getStructuralProperty(property); if (resultingCollections == null) { return true; } AST ast= statement.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); String label= CorrectionMessages.getString("QuickAssistProcessor.splitdeclaration.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image); Statement newStatement; int insertIndex= list.indexOf(statement); Expression placeholder= (Expression) rewrite.createMoveTarget(fragment.getInitializer()); Assignment assignment= ast.newAssignment(); assignment.setRightHandSide(placeholder); assignment.setLeftHandSide(ast.newSimpleName(fragment.getName().getIdentifier())); if (statement instanceof VariableDeclarationStatement) { newStatement= ast.newExpressionStatement(assignment); insertIndex+= 1; // add after declaration int modifiers= ((VariableDeclarationStatement) statement).getModifiers(); if (Modifier.isFinal(modifiers)) { rewrite.set(statement, VariableDeclarationStatement.MODIFIERS_PROPERTY, new Integer(modifiers & ~Modifier.FINAL), null); } } else { rewrite.replace(fragment.getParent(), assignment, null); VariableDeclarationFragment newFrag= ast.newVariableDeclarationFragment(); newFrag.setName(ast.newSimpleName(fragment.getName().getIdentifier())); newFrag.setExtraDimensions(fragment.getExtraDimensions()); VariableDeclarationExpression oldVarDecl= (VariableDeclarationExpression) fragParent; VariableDeclarationStatement newVarDec= ast.newVariableDeclarationStatement(newFrag); newVarDec.setType((Type) ASTNode.copySubtree(ast, oldVarDecl.getType())); newVarDec.setModifiers(oldVarDecl.getModifiers() & ~Modifier.FINAL); newStatement= newVarDec; } ListRewrite listRewriter= rewrite.getListRewrite(statementParent, (ChildListPropertyDescriptor) property); listRewriter.insertAt(newStatement, insertIndex, null); resultingCollections.add(proposal); return true; } private ASTNode getCoveringNode(IInvocationContext context) { NodeFinder finder= new NodeFinder(context.getSelectionOffset(), context.getSelectionLength()); context.getASTRoot().accept(finder); return finder.getCoveringNode(); } private boolean getAssignToVariableProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) { Statement statement= ASTResolving.findParentStatement(node); if (!(statement instanceof ExpressionStatement)) { return false; } ExpressionStatement expressionStatement= (ExpressionStatement) statement; Expression expression= expressionStatement.getExpression(); if (expression.getNodeType() == ASTNode.ASSIGNMENT) { return false; // too confusing and not helpful } ITypeBinding typeBinding= expression.resolveTypeBinding(); typeBinding= Bindings.normalizeTypeBinding(typeBinding); if (typeBinding == null) { return false; } if (resultingCollections == null) { return true; } ICompilationUnit cu= context.getCompilationUnit(); AssignToVariableAssistProposal localProposal= new AssignToVariableAssistProposal(cu, AssignToVariableAssistProposal.LOCAL, expressionStatement, typeBinding, 2); resultingCollections.add(localProposal); ASTNode type= ASTResolving.findParentType(expression); if (type != null) { AssignToVariableAssistProposal fieldProposal= new AssignToVariableAssistProposal(cu, AssignToVariableAssistProposal.FIELD, expressionStatement, typeBinding, 1); resultingCollections.add(fieldProposal); } return false; } private boolean getAssignParamToFieldProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) { ASTNode parent= node.getParent(); if (!(parent instanceof SingleVariableDeclaration) || !(parent.getParent() instanceof MethodDeclaration)) { return false; } SingleVariableDeclaration paramDecl= (SingleVariableDeclaration) parent; IVariableBinding binding= paramDecl.resolveBinding(); MethodDeclaration methodDecl= (MethodDeclaration) parent.getParent(); if (binding == null || methodDecl.getBody() == null) { return false; } ITypeBinding typeBinding= binding.getType(); if (typeBinding == null) { return false; } if (resultingCollections != null) { AssignToVariableAssistProposal fieldProposal= new AssignToVariableAssistProposal(context.getCompilationUnit(), paramDecl, typeBinding, 1); resultingCollections.add(fieldProposal); } return true; } private boolean getAddFinallyProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) { TryStatement tryStatement= ASTResolving.findParentTryStatement(node); if (tryStatement == null || tryStatement.getFinally() != null) { return false; } Statement statement= ASTResolving.findParentStatement(node); if (tryStatement != statement && tryStatement.getBody() != statement) { return false; // an node inside a catch or finally block } if (resultingCollections == null) { return true; } AST ast= tryStatement.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); Block finallyBody= ast.newBlock(); rewrite.set(tryStatement, TryStatement.FINALLY_PROPERTY, finallyBody, null); String label= CorrectionMessages.getString("QuickAssistProcessor.addfinallyblock.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image); resultingCollections.add(proposal); return true; } private boolean getAddElseProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) { Statement statement= ASTResolving.findParentStatement(node); if (!(statement instanceof IfStatement)) { return false; } IfStatement ifStatement= (IfStatement) statement; if (ifStatement.getElseStatement() != null) { return false; } if (resultingCollections == null) { return true; } AST ast= statement.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); Block body= ast.newBlock(); rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, body, null); String label= CorrectionMessages.getString("QuickAssistProcessor.addelseblock.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image); resultingCollections.add(proposal); return true; } public static boolean getCatchClauseToThrowsProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) { CatchClause catchClause= (CatchClause) ASTResolving.findAncestor(node, ASTNode.CATCH_CLAUSE); if (catchClause == null) { return false; } Statement statement= ASTResolving.findParentStatement(node); if (statement != catchClause.getParent() && statement != catchClause.getBody()) { return false; // selection is in a statement inside the body } Type type= catchClause.getException().getType(); if (!type.isSimpleType()) { return false; } BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(catchClause); if (!(bodyDeclaration instanceof MethodDeclaration)) { return false; } if (resultingCollections == null) { return true; } AST ast= bodyDeclaration.getAST(); MethodDeclaration methodDeclaration= (MethodDeclaration) bodyDeclaration; { ASTRewrite rewrite= ASTRewrite.create(ast); removeCatchBlock(rewrite, methodDeclaration, catchClause); ITypeBinding binding= type.resolveBinding(); if (binding == null || isNotYetThrown(binding, methodDeclaration.thrownExceptions())) { Name name= ((SimpleType) type).getName(); Name newName= (Name) ASTNode.copySubtree(ast, name); ListRewrite listRewriter= rewrite.getListRewrite(methodDeclaration, MethodDeclaration.THROWN_EXCEPTIONS_PROPERTY); listRewriter.insertLast(newName, null); } String label= CorrectionMessages.getString("QuickAssistProcessor.catchclausetothrows.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 4, image); resultingCollections.add(proposal); } { ASTRewrite rewrite= ASTRewrite.create(ast); removeCatchBlock(rewrite, methodDeclaration, catchClause); String label= CorrectionMessages.getString("QuickAssistProcessor.removecatchclause.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image); resultingCollections.add(proposal); } return true; } private static void removeCatchBlock(ASTRewrite rewrite, MethodDeclaration methodDeclaration, CatchClause catchClause) { TryStatement tryStatement= (TryStatement) catchClause.getParent(); if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null) { rewrite.remove(catchClause, null); } else { Block block= tryStatement.getBody(); List statements= block.statements(); if (statements.size() > 0) { ListRewrite listRewrite= rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY); ASTNode first= (ASTNode) statements.get(0); ASTNode last= (ASTNode) statements.get(statements.size() - 1); ASTNode placeholder= listRewrite.createCopyTarget(first, last); rewrite.replace(tryStatement, placeholder, null); } else { rewrite.remove(tryStatement, null); } } } private static boolean isNotYetThrown(ITypeBinding binding, List thrownExcpetions) { for (int i= 0; i < thrownExcpetions.size(); i++) { Name name= (Name) thrownExcpetions.get(i); ITypeBinding elem= (ITypeBinding) name.resolveBinding(); if (elem != null) { if (Bindings.isSuperType(elem, binding)) { // existing exception is base class of new return false; } } } return true; } private boolean getRenameLocalProposals(IInvocationContext context, ASTNode node, IProblemLocation[] locations, Collection resultingCollections) { if (!(node instanceof SimpleName)) { return false; } SimpleName name= (SimpleName) node; IBinding binding= name.resolveBinding(); if (binding != null && binding.getKind() == IBinding.PACKAGE) { return false; } if (locations != null) { for (int i= 0; i < locations.length; i++) { switch (locations[i].getProblemId()) { case IProblem.LocalVariableHidingLocalVariable: case IProblem.LocalVariableHidingField: case IProblem.FieldHidingLocalVariable: case IProblem.FieldHidingField: case IProblem.ArgumentHidingLocalVariable: case IProblem.ArgumentHidingField: return false; } } } if (resultingCollections == null) { return true; } LinkedNamesAssistProposal proposal= new LinkedNamesAssistProposal(context.getCompilationUnit(), name); resultingCollections.add(proposal); return true; } private ASTNode getCopyOfInner(ASTRewrite rewrite, ASTNode statement) { if (statement.getNodeType() == ASTNode.BLOCK) { Block block= (Block) statement; List innerStatements= block.statements(); int nStatements= innerStatements.size(); if (nStatements == 1) { return rewrite.createCopyTarget(((ASTNode) innerStatements.get(0))); } else if (nStatements > 1) { ListRewrite listRewrite= rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY); ASTNode first= (ASTNode) innerStatements.get(0); ASTNode last= (ASTNode) innerStatements.get(nStatements - 1); return listRewrite.createCopyTarget(first, last); } return null; } else { return rewrite.createCopyTarget(statement); } } private boolean getUnWrapProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) { ASTNode outer= node; Block block= null; if (outer.getNodeType() == ASTNode.BLOCK) { block= (Block) outer; outer= block.getParent(); } ASTNode body= null; String label= null; if (outer instanceof IfStatement) { IfStatement ifStatement= (IfStatement) outer; Statement elseBlock= ifStatement.getElseStatement(); if (elseBlock == null || ((elseBlock instanceof Block) && ((Block) elseBlock).statements().isEmpty())) { body= ifStatement.getThenStatement(); } label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.ifstatement"); //$NON-NLS-1$ } else if (outer instanceof WhileStatement) { body=((WhileStatement) outer).getBody(); label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.whilestatement"); //$NON-NLS-1$ } else if (outer instanceof ForStatement) { body=((ForStatement) outer).getBody(); label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.forstatement"); //$NON-NLS-1$ } else if (outer instanceof DoStatement) { body=((DoStatement) outer).getBody(); label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.dostatement"); //$NON-NLS-1$ } else if (outer instanceof TryStatement) { TryStatement tryStatement= (TryStatement) outer; if (tryStatement.catchClauses().isEmpty()) { body= tryStatement.getBody(); } label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.trystatement"); //$NON-NLS-1$ } else if (outer instanceof AnonymousClassDeclaration) { List decls= ((AnonymousClassDeclaration) outer).bodyDeclarations(); for (int i= 0; i < decls.size(); i++) { ASTNode elem= (ASTNode) decls.get(i); if (elem instanceof MethodDeclaration) { Block curr= ((MethodDeclaration) elem).getBody(); if (curr != null && !curr.statements().isEmpty()) { if (body != null) { return false; } body= curr; } } else if (elem instanceof TypeDeclaration) { return false; } } label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.anonymous"); //$NON-NLS-1$ outer= ASTResolving.findParentStatement(outer); if (outer == null) { return false; // private Object o= new Object() { ... }; } } else if (outer instanceof Block) { // -> a block in a block body= block; outer= block; label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.block"); //$NON-NLS-1$ } else if (outer instanceof ParenthesizedExpression) { ParenthesizedExpression expression= (ParenthesizedExpression) outer; body= expression.getExpression(); label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.parenthesis"); //$NON-NLS-1$ } else if (outer instanceof MethodInvocation) { MethodInvocation invocation= (MethodInvocation) outer; if (invocation.arguments().size() == 1) { body= (ASTNode) invocation.arguments().get(0); if (invocation.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) { int kind= body.getNodeType(); if (kind != ASTNode.ASSIGNMENT && kind != ASTNode.PREFIX_EXPRESSION && kind != ASTNode.POSTFIX_EXPRESSION && kind != ASTNode.METHOD_INVOCATION && kind != ASTNode.SUPER_METHOD_INVOCATION) { body= null; } } label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.methodinvocation"); //$NON-NLS-1$ } } if (body == null) { return false; } ASTRewrite rewrite= ASTRewrite.create(outer.getAST()); ASTNode inner= getCopyOfInner(rewrite, body); if (inner == null) { return false; } if (resultingCollections == null) { return true; } rewrite.replace(outer, inner, null); Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image); resultingCollections.add(proposal); return true; } private static boolean isControlStatementWithBlock(ASTNode node) { switch (node.getNodeType()) { case ASTNode.IF_STATEMENT: case ASTNode.WHILE_STATEMENT: case ASTNode.FOR_STATEMENT: case ASTNode.DO_STATEMENT: return true; default: return false; } } private boolean getAddBlockProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) { Statement statement= ASTResolving.findParentStatement(node); if (statement == null) { return false; } if (!isControlStatementWithBlock(statement)) { if (!isControlStatementWithBlock(statement.getParent())) { return false; } int statementStart= statement.getStartPosition(); int statementEnd= statementStart + statement.getLength(); int offset= context.getSelectionOffset(); int length= context.getSelectionLength(); if (length == 0) { if (offset != statementEnd) { // cursor at end return false; } } else { if (offset > statementStart || offset + length < statementEnd) { // statement selected return false; } } statement= (Statement) statement.getParent(); } StructuralPropertyDescriptor childProperty= null; ASTNode child= null; switch (statement.getNodeType()) { case ASTNode.IF_STATEMENT: int selectionStart= context.getSelectionOffset(); int selectionEnd= context.getSelectionOffset() + context.getSelectionLength(); ASTNode then= ((IfStatement) statement).getThenStatement(); if (selectionEnd <= then.getStartPosition() + then.getLength()) { if (!(then instanceof Block)) { childProperty= IfStatement.THEN_STATEMENT_PROPERTY; child= then; } } else if (selectionStart >= then.getStartPosition() + then.getLength()) { ASTNode elseStatement= ((IfStatement) statement).getElseStatement(); if (!(elseStatement instanceof Block)) { childProperty= IfStatement.ELSE_STATEMENT_PROPERTY; child= elseStatement; } } break; case ASTNode.WHILE_STATEMENT: ASTNode whileBody= ((WhileStatement) statement).getBody(); if (!(whileBody instanceof Block)) { childProperty= WhileStatement.BODY_PROPERTY; child= whileBody; } break; case ASTNode.FOR_STATEMENT: ASTNode forBody= ((ForStatement) statement).getBody(); if (!(forBody instanceof Block)) { childProperty= ForStatement.BODY_PROPERTY; child= forBody; } break; case ASTNode.DO_STATEMENT: ASTNode doBody= ((DoStatement) statement).getBody(); if (!(doBody instanceof Block)) { childProperty= DoStatement.BODY_PROPERTY; child= doBody; } break; default: } if (child == null) { return false; } if (resultingCollections == null) { return true; } AST ast= statement.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); ASTNode childPlaceholder= rewrite.createMoveTarget(child); Block replacingBody= ast.newBlock(); replacingBody.statements().add(childPlaceholder); rewrite.set(statement, childProperty, replacingBody, null); String label; if (childProperty == IfStatement.THEN_STATEMENT_PROPERTY) { label = CorrectionMessages.getString("QuickAssistProcessor.replacethenwithblock.description");//$NON-NLS-1$ } else if (childProperty == IfStatement.ELSE_STATEMENT_PROPERTY) { label = CorrectionMessages.getString("QuickAssistProcessor.replaceelsewithblock.description");//$NON-NLS-1$ } else { label = CorrectionMessages.getString("QuickAssistProcessor.replacebodywithblock.description");//$NON-NLS-1$ } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, 10, image); proposal.setEndPosition(rewrite.track(child)); resultingCollections.add(proposal); return true; } private boolean getInvertEqualsProposal(IInvocationContext context, ASTNode node, Collection resultingCollections) { ASTNode parent= node.getParent(); if (!(parent instanceof MethodInvocation)) { return false; } MethodInvocation method= (MethodInvocation) parent; if (!"equals".equals(method.getName().getIdentifier())) { //$NON-NLS-1$ return false; } List arguments= method.arguments(); if (arguments.size() != 1) { //overloaded equals w/ more than 1 arg return false; } Expression right= (Expression) arguments.get(0); ITypeBinding binding = right.resolveTypeBinding(); if (!(binding.isClass() || binding.isInterface())) { //overloaded equals w/ non-class/interface arg or null return false; } if (resultingCollections == null) { return true; } Expression left= method.getExpression(); AST ast= method.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); if (left == null) { // equals(x) -> x.equals(this) MethodInvocation replacement= ast.newMethodInvocation(); replacement.setName((SimpleName) rewrite.createCopyTarget(method.getName())); replacement.arguments().add(ast.newThisExpression()); replacement.setExpression((Expression) rewrite.createCopyTarget(right)); rewrite.replace(method, replacement, null); } else if (right instanceof ThisExpression) { // x.equals(this) -> equals(x) MethodInvocation replacement= ast.newMethodInvocation(); replacement.setName((SimpleName) rewrite.createCopyTarget(method.getName())); replacement.arguments().add(rewrite.createCopyTarget(left)); rewrite.replace(method, replacement, null); } else { ASTNode leftExpression= left; while (leftExpression instanceof ParenthesizedExpression) { leftExpression= ((ParenthesizedExpression) left).getExpression(); } rewrite.replace(right, rewrite.createCopyTarget(leftExpression), null); if ((right instanceof CastExpression) || (right instanceof Assignment) || (right instanceof ConditionalExpression) || (right instanceof InfixExpression)) { ParenthesizedExpression paren= ast.newParenthesizedExpression(); paren.setExpression((Expression) rewrite.createCopyTarget(right)); rewrite.replace(left, paren, null); } else { rewrite.replace(left, rewrite.createCopyTarget(right), null); } } String label= CorrectionMessages.getString("QuickAssistProcessor.invertequals.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image); resultingCollections.add(proposal); return true; } private boolean getArrayInitializerToArrayCreation(IInvocationContext context, ASTNode node, Collection resultingCollections) throws CoreException { if (!(node instanceof ArrayInitializer)) { return false; } ArrayInitializer initializer= (ArrayInitializer) node; ASTNode parent= initializer.getParent(); while (parent instanceof ArrayInitializer) { initializer= (ArrayInitializer) parent; parent= parent.getParent(); } ITypeBinding typeBinding= initializer.resolveTypeBinding(); if (!(parent instanceof VariableDeclaration) || typeBinding == null || !typeBinding.isArray()) { return false; } if (resultingCollections == null) { return true; } AST ast= node.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); ImportRewrite imports= new ImportRewrite(context.getCompilationUnit()); String typeName= imports.addImport(typeBinding); ArrayCreation creation= ast.newArrayCreation(); creation.setInitializer((ArrayInitializer) rewrite.createMoveTarget(initializer)); creation.setType((ArrayType) ASTNodeFactory.newType(ast, typeName)); rewrite.replace(initializer, creation, null); String label= CorrectionMessages.getString("QuickAssistProcessor.typetoarrayInitializer.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image); resultingCollections.add(proposal); return true; } }
44,204
Bug 44204 Promote individual methods to interface.
Methods should be able to be promoted to an implemented interface. IE interface SomeThing { public DoDad getDoDad(); } class MyThing implements Something { private DoDad doDad=new DoDad(); public DoDad getDoDad() { return doDad; } public void setDoDad(DoDad dad) { this.doDad=dad; } ^^^^^^^^ } Ctrl-1 on the ^'d should produce 'Declare in interface 'Something''. if more than on interface, multiple options should be given, much like what import does. This enhancement would save time copying, pasting and trimming. Regards, Andy
resolved fixed
37ef19b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T15:52:53Z
2003-10-05T16:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/TypeMismatchSubProcessor.java
/******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.Collection; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.Assignment; import org.eclipse.jdt.core.dom.BodyDeclaration; import org.eclipse.jdt.core.dom.CastExpression; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.FieldAccess; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.ParenthesizedExpression; import org.eclipse.jdt.core.dom.PrimitiveType; import org.eclipse.jdt.core.dom.SuperFieldAccess; import org.eclipse.jdt.core.dom.SuperMethodInvocation; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import org.eclipse.jdt.core.dom.PrimitiveType.Code; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.ui.text.java.IInvocationContext; import org.eclipse.jdt.ui.text.java.IProblemLocation; import org.eclipse.jdt.internal.corext.codemanipulation.ImportRewrite; import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.dom.TypeRules; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.ChangeDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.InsertDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.RemoveDescription; public class TypeMismatchSubProcessor { private TypeMismatchSubProcessor() { } public static void addTypeMismatchProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { String[] args= problem.getProblemArguments(); if (args.length != 2) { return; } ICompilationUnit cu= context.getCompilationUnit(); String castTypeName= args[1]; CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveredNode(astRoot); if (!(selectedNode instanceof Expression)) { return; } Expression nodeToCast= (Expression) selectedNode; Name receiverNode= null; ITypeBinding castTypeBinding= null; int parentNodeType= selectedNode.getParent().getNodeType(); if (parentNodeType == ASTNode.ASSIGNMENT) { Assignment assign= (Assignment) selectedNode.getParent(); Expression leftHandSide= assign.getLeftHandSide(); if (selectedNode.equals(leftHandSide)) { nodeToCast= assign.getRightHandSide(); } castTypeBinding= assign.getLeftHandSide().resolveTypeBinding(); if (leftHandSide instanceof Name) { receiverNode= (Name) leftHandSide; } } else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) { VariableDeclarationFragment frag= (VariableDeclarationFragment) selectedNode.getParent(); if (selectedNode.equals(frag.getName())) { nodeToCast= frag.getInitializer(); IVariableBinding varBinding= frag.resolveBinding(); if (varBinding != null) { castTypeBinding= varBinding.getType(); } receiverNode= frag.getName(); } } else { // try to find the binding corresponding to 'castTypeName' ITypeBinding guessedCastTypeBinding= ASTResolving.guessBindingForReference(nodeToCast); if (guessedCastTypeBinding != null && castTypeName.equals(guessedCastTypeBinding.getQualifiedName())) { castTypeBinding= guessedCastTypeBinding; } } ITypeBinding binding= nodeToCast.resolveTypeBinding(); if (binding == null || canCast(castTypeName, castTypeBinding, binding)) { proposals.add(createCastProposal(context, castTypeName, nodeToCast, 5)); } ITypeBinding currBinding= nodeToCast.resolveTypeBinding(); if (currBinding == null || "void".equals(currBinding.getName())) { //$NON-NLS-1$ return; } // change method return statement to actual type if (parentNodeType == ASTNode.RETURN_STATEMENT) { BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); if (decl instanceof MethodDeclaration) { MethodDeclaration methodDeclaration= (MethodDeclaration) decl; currBinding= Bindings.normalizeTypeBinding(currBinding); if (currBinding == null) { currBinding= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } ASTRewrite rewrite= ASTRewrite.create(methodDeclaration.getAST()); ImportRewrite imports= new ImportRewrite(cu); String returnTypeName= imports.addImport(currBinding); Type newReturnType= ASTNodeFactory.newType(astRoot.getAST(), returnTypeName); rewrite.replace(methodDeclaration.getReturnType(), newReturnType, null); String label= CorrectionMessages.getFormattedString("TypeMismatchSubProcessor.changereturntype.description", currBinding.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image); proposal.setImportRewrite(imports); String returnKey= "return"; //$NON-NLS-1$ proposal.addLinkedPosition(rewrite.track(newReturnType), true, returnKey); ITypeBinding[] typeSuggestions= ASTResolving.getRelaxingTypes(astRoot.getAST(), currBinding); for (int i= 0; i < typeSuggestions.length; i++) { proposal.addLinkedPositionProposal(returnKey, typeSuggestions[i]); } proposals.add(proposal); } } if (receiverNode != null) { currBinding= Bindings.normalizeTypeBinding(currBinding); if (currBinding == null) { currBinding= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } addChangeSenderTypeProposals(context, receiverNode, currBinding, true, 4, proposals); } if (castTypeBinding != null) { addChangeSenderTypeProposals(context, nodeToCast, castTypeBinding, false, 5, proposals); } } public static void addChangeSenderTypeProposals(IInvocationContext context, Expression nodeToCast, ITypeBinding castTypeBinding, boolean isAssingedNode, int relevance, Collection proposals) throws JavaModelException { IBinding callerBinding= null; switch (nodeToCast.getNodeType()) { case ASTNode.METHOD_INVOCATION: callerBinding= ((MethodInvocation) nodeToCast).resolveMethodBinding(); break; case ASTNode.SUPER_METHOD_INVOCATION: callerBinding= ((SuperMethodInvocation) nodeToCast).resolveMethodBinding(); break; case ASTNode.FIELD_ACCESS: callerBinding= ((FieldAccess) nodeToCast).resolveFieldBinding(); break; case ASTNode.SUPER_FIELD_ACCESS: callerBinding= ((SuperFieldAccess) nodeToCast).resolveFieldBinding(); break; case ASTNode.SIMPLE_NAME: case ASTNode.QUALIFIED_NAME: callerBinding= ((Name) nodeToCast).resolveBinding(); break; } ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ICompilationUnit targetCu= null; ITypeBinding declaringType= null; if (callerBinding instanceof IVariableBinding) { IVariableBinding variableBinding= (IVariableBinding) callerBinding; if (!variableBinding.isField()) { targetCu= cu; } else { declaringType= variableBinding.getDeclaringClass(); } } else if (callerBinding instanceof IMethodBinding) { IMethodBinding methodBinding= (IMethodBinding) callerBinding; if (!methodBinding.isConstructor()) { declaringType= methodBinding.getDeclaringClass(); } } if (declaringType != null && declaringType.isFromSource()) { targetCu= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); } if (targetCu != null) { proposals.add(new TypeChangeCompletionProposal(targetCu, callerBinding, astRoot, castTypeBinding, isAssingedNode, relevance)); } // add interface to resulting type if (!isAssingedNode) { ITypeBinding nodeType= nodeToCast.resolveTypeBinding(); if (castTypeBinding.isInterface() && nodeType != null && nodeType.isClass() && !nodeType.isAnonymous() && nodeType.isFromSource()) { ICompilationUnit nodeCu= ASTResolving.findCompilationUnitForBinding(cu, astRoot, nodeType); if (nodeCu != null) { proposals.add(new ImplementInterfaceProposal(nodeCu, nodeType, astRoot, castTypeBinding, relevance - 1)); } } } } private static boolean canCast(String castTarget, ITypeBinding castTypeBinding, ITypeBinding bindingToCast) { if (castTypeBinding != null) { return TypeRules.canCast(castTypeBinding, bindingToCast); } bindingToCast= Bindings.normalizeTypeBinding(bindingToCast); if (bindingToCast == null) { return false; } int arrStart= castTarget.indexOf('['); if (arrStart != -1) { if (!bindingToCast.isArray()) { return "java.lang.Object".equals(bindingToCast.getQualifiedName()); //$NON-NLS-1$ } castTarget= castTarget.substring(0, arrStart); bindingToCast= bindingToCast.getElementType(); if (bindingToCast.isPrimitive() && !castTarget.equals(bindingToCast.getName())) { return false; // can't cast arrays of primitive types into each other } } Code targetCode= PrimitiveType.toCode(castTarget); if (bindingToCast.isPrimitive()) { Code castCode= PrimitiveType.toCode(bindingToCast.getName()); if (castCode == targetCode) { return true; } return (targetCode != null && targetCode != PrimitiveType.BOOLEAN && castCode != PrimitiveType.BOOLEAN); } else { return targetCode == null; // can not check } } public static ASTRewriteCorrectionProposal createCastProposal(IInvocationContext context, String castType, Expression nodeToCast, int relevance) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTRewrite rewrite= ASTRewrite.create(nodeToCast.getAST()); ImportRewrite imports= new ImportRewrite(cu); String label; String simpleCastType= imports.addImport(castType); if (nodeToCast.getNodeType() == ASTNode.CAST_EXPRESSION) { label= CorrectionMessages.getFormattedString("TypeMismatchSubProcessor.changecast.description", castType); //$NON-NLS-1$ CastExpression expression= (CastExpression) nodeToCast; rewrite.replace(expression.getType(), rewrite.createStringPlaceholder(simpleCastType, ASTNode.SIMPLE_TYPE), null); } else { label= CorrectionMessages.getFormattedString("TypeMismatchSubProcessor.addcast.description", castType); //$NON-NLS-1$ Expression expressionCopy= (Expression) rewrite.createCopyTarget(nodeToCast); int nodeType= nodeToCast.getNodeType(); if (nodeType == ASTNode.INFIX_EXPRESSION || nodeType == ASTNode.CONDITIONAL_EXPRESSION || nodeType == ASTNode.ASSIGNMENT || nodeType == ASTNode.INSTANCEOF_EXPRESSION) { // nodes have weaker precedence than cast ParenthesizedExpression parenthesizedExpression= astRoot.getAST().newParenthesizedExpression(); parenthesizedExpression.setExpression(expressionCopy); expressionCopy= parenthesizedExpression; } Type typeCopy= (Type) rewrite.createStringPlaceholder(simpleCastType, ASTNode.SIMPLE_TYPE); CastExpression castExpression= astRoot.getAST().newCastExpression(); castExpression.setExpression(expressionCopy); castExpression.setType(typeCopy); rewrite.replace(nodeToCast, castExpression, null); } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, relevance, image); //$NON-NLS-1$ proposal.setImportRewrite(imports); return proposal; } public static void addIncompatibleReturnTypeProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws JavaModelException { CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (!(selectedNode instanceof MethodDeclaration)) { return; } MethodDeclaration decl= (MethodDeclaration) selectedNode; IMethodBinding binding= decl.resolveBinding(); if (binding == null) { return; } IMethodBinding overridden= Bindings.findMethodDefininition(binding); if (overridden == null || overridden.getReturnType() == binding.getReturnType()) { return; } ITypeBinding declaringType= overridden.getDeclaringClass(); ICompilationUnit cu= context.getCompilationUnit(); proposals.add(new TypeChangeCompletionProposal(cu, binding, astRoot, overridden.getReturnType(), false, 8)); ICompilationUnit targetCu= cu; if (declaringType != null && declaringType.isFromSource()) { targetCu= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); } if (targetCu != null) { proposals.add(new TypeChangeCompletionProposal(targetCu, overridden, astRoot, binding.getReturnType(), false, 7)); } } public static void addIncompatibleThrowsProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws JavaModelException { CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (!(selectedNode instanceof MethodDeclaration)) { return; } MethodDeclaration decl= (MethodDeclaration) selectedNode; IMethodBinding binding= decl.resolveBinding(); if (binding == null) { return; } IMethodBinding overridden= Bindings.findMethodDefininition(binding); if (overridden == null) { return; } ICompilationUnit cu= context.getCompilationUnit(); ITypeBinding[] methodExceptions= binding.getExceptionTypes(); ITypeBinding[] definedExceptions= overridden.getExceptionTypes(); ArrayList undeclaredExceptions= new ArrayList(); { ChangeDescription[] changes= new ChangeDescription[methodExceptions.length]; for (int i= 0; i < methodExceptions.length; i++) { if (!isDeclaredException(methodExceptions[i], definedExceptions)) { changes[i]= new RemoveDescription(); undeclaredExceptions.add(methodExceptions[i]); } } String label= CorrectionMessages.getFormattedString("TypeMismatchSubProcessor.removeexceptions.description", binding.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE); proposals.add(new ChangeMethodSignatureProposal(label, cu, astRoot, binding, null, changes, 8, image)); } ITypeBinding declaringType= overridden.getDeclaringClass(); ICompilationUnit targetCu= cu; if (declaringType != null && declaringType.isFromSource()) { targetCu= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); } if (targetCu != null) { ChangeDescription[] changes= new ChangeDescription[definedExceptions.length + undeclaredExceptions.size()]; for (int i= 0; i < undeclaredExceptions.size(); i++) { changes[i + definedExceptions.length]= new InsertDescription((ITypeBinding) undeclaredExceptions.get(i), ""); //$NON-NLS-1$ } String[] args= { declaringType.getName(), overridden.getName() }; String label= CorrectionMessages.getFormattedString("TypeMismatchSubProcessor.addexceptions.description", args); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD); proposals.add(new ChangeMethodSignatureProposal(label, targetCu, astRoot, overridden, null, changes, 7, image)); } } private static boolean isDeclaredException(ITypeBinding curr, ITypeBinding[] declared) { for (int i= 0; i < declared.length; i++) { if (Bindings.isSuperType(declared[i], curr)) { return true; } } return false; } }
44,204
Bug 44204 Promote individual methods to interface.
Methods should be able to be promoted to an implemented interface. IE interface SomeThing { public DoDad getDoDad(); } class MyThing implements Something { private DoDad doDad=new DoDad(); public DoDad getDoDad() { return doDad; } public void setDoDad(DoDad dad) { this.doDad=dad; } ^^^^^^^^ } Ctrl-1 on the ^'d should produce 'Declare in interface 'Something''. if more than on interface, multiple options should be given, much like what import does. This enhancement would save time copying, pasting and trimming. Regards, Andy
resolved fixed
37ef19b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T15:52:53Z
2003-10-05T16:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Renaud Waldura &lt;renaud+eclipse@waldura.com&gt; - New class/interface with wizard *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.ui.ISharedImages; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.ui.text.java.IInvocationContext; import org.eclipse.jdt.ui.text.java.IProblemLocation; import org.eclipse.jdt.internal.corext.codemanipulation.ImportRewrite; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer; import org.eclipse.jdt.internal.corext.dom.TypeRules; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Strings; import org.eclipse.jdt.internal.corext.util.TypeFilter; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.ChangeDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.EditDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.InsertDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.RemoveDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.SwapDescription; public class UnresolvedElementsSubProcessor { public static void getVariableProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveredNode(astRoot); if (selectedNode == null) { return; } // type that defines the variable ITypeBinding binding= null; ITypeBinding declaringTypeBinding= Bindings.getBindingOfParentType(selectedNode); if (declaringTypeBinding == null) { return; } // possible type kind of the node boolean suggestVariableProposals= true; int typeKind= 0; while (selectedNode instanceof ParenthesizedExpression) { selectedNode= ((ParenthesizedExpression) selectedNode).getExpression(); } Name node= null; switch (selectedNode.getNodeType()) { case ASTNode.SIMPLE_NAME: node= (SimpleName) selectedNode; ASTNode parent= node.getParent(); if (parent instanceof MethodInvocation && node.equals(((MethodInvocation)parent).getExpression())) { typeKind= SimilarElementsRequestor.CLASSES; } else if (parent instanceof SimpleType) { suggestVariableProposals= false; typeKind= SimilarElementsRequestor.REF_TYPES; } else if (parent instanceof QualifiedName) { Name qualifier= ((QualifiedName) parent).getQualifier(); if (qualifier != node) { binding= qualifier.resolveTypeBinding(); } else { typeKind= SimilarElementsRequestor.REF_TYPES; } ASTNode outerParent= parent.getParent(); while (outerParent instanceof QualifiedName) { outerParent= outerParent.getParent(); } if (outerParent instanceof SimpleType) { typeKind= SimilarElementsRequestor.REF_TYPES; suggestVariableProposals= false; } } break; case ASTNode.QUALIFIED_NAME: QualifiedName qualifierName= (QualifiedName) selectedNode; ITypeBinding qualifierBinding= qualifierName.getQualifier().resolveTypeBinding(); if (qualifierBinding != null) { node= qualifierName.getName(); binding= qualifierBinding; } else { node= qualifierName.getQualifier(); typeKind= SimilarElementsRequestor.REF_TYPES; suggestVariableProposals= node.isSimpleName(); } if (selectedNode.getParent() instanceof SimpleType) { typeKind= SimilarElementsRequestor.REF_TYPES; suggestVariableProposals= false; } break; case ASTNode.FIELD_ACCESS: FieldAccess access= (FieldAccess) selectedNode; Expression expression= access.getExpression(); if (expression != null) { binding= expression.resolveTypeBinding(); if (binding != null) { node= access.getName(); } } break; case ASTNode.SUPER_FIELD_ACCESS: binding= declaringTypeBinding.getSuperclass(); node= ((SuperFieldAccess) selectedNode).getName(); break; default: } if (node == null) { return; } // add type proposals if (typeKind != 0) { int relevance= Character.isUpperCase(ASTResolving.getSimpleName(node).charAt(0)) ? 3 : 0; addSimilarTypeProposals(typeKind, cu, node, relevance + 1, proposals); addNewTypeProposals(cu, node, SimilarElementsRequestor.REF_TYPES, relevance, proposals); } if (!suggestVariableProposals) { return; } SimpleName simpleName= node.isSimpleName() ? (SimpleName) node : ((QualifiedName) node).getName(); boolean isWriteAccess= ASTResolving.isWriteAccess(node); // similar variables addSimilarVariableProposals(cu, astRoot, binding, simpleName, isWriteAccess, proposals); // new fields addNewFieldProposals(cu, astRoot, binding, declaringTypeBinding, simpleName, isWriteAccess, proposals); // new parameters and local variables if (binding == null) { addNewVariableProposals(cu, node, simpleName, proposals); } } private static void addNewVariableProposals(ICompilationUnit cu, Name node, SimpleName simpleName, Collection proposals) { String name= simpleName.getIdentifier(); BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(node); int type= bodyDeclaration.getNodeType(); if (type == ASTNode.METHOD_DECLARATION) { int relevance= StubUtility.hasParameterName(cu.getJavaProject(), name) ? 8 : 5; String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createparameter.description", simpleName.getIdentifier()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.PARAM, simpleName, null, relevance, image)); } if (type == ASTNode.METHOD_DECLARATION || type == ASTNode.INITIALIZER) { int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7; String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createlocal.description", simpleName.getIdentifier()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.LOCAL, simpleName, null, relevance, image)); } if (node.getParent().getNodeType() == ASTNode.ASSIGNMENT) { Assignment assignment= (Assignment) node.getParent(); if (assignment.getLeftHandSide() == node && assignment.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) { ASTNode statement= assignment.getParent(); ASTRewrite rewrite= ASTRewrite.create(statement.getAST()); rewrite.remove(statement, null); String label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.removestatement.description"); //$NON-NLS-1$ Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 4, image); proposals.add(proposal); } } } private static void addNewFieldProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, ITypeBinding declaringTypeBinding, SimpleName simpleName, boolean isWriteAccess, Collection proposals) throws JavaModelException { // new variables ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding); ITypeBinding senderBinding= binding != null ? binding : declaringTypeBinding; if (!senderBinding.isFromSource() || targetCU == null || !JavaModelUtil.isEditable(targetCU)) { return; } ITypeBinding outsideAnonymous= null; if (binding == null && senderBinding.isAnonymous()) { ASTNode anonymDecl= astRoot.findDeclaringNode(senderBinding); if (anonymDecl != null) { ITypeBinding bind= Bindings.getBindingOfParentType(anonymDecl.getParent()); if (!bind.isAnonymous()) { outsideAnonymous= bind; } } } String name= simpleName.getIdentifier(); int relevance= StubUtility.hasFieldName(cu.getJavaProject(), name) ? 9 : 6; String label; Image image; if (binding == null) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.description", name); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE); } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { name, binding.getName() } ); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC); } proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, relevance, image)); // create field in outer class (if inside anonymous) if (outsideAnonymous != null) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { name, outsideAnonymous.getName() } ); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC); proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, outsideAnonymous, relevance + 1, image)); } // create constant if (!isWriteAccess) { relevance= StubUtility.hasConstantName(name) ? 9 : 4; ITypeBinding target= (outsideAnonymous != null) ? outsideAnonymous : senderBinding; if (binding == null) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconst.description", name); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE); } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconst.other.description", new Object[] { name, binding.getName() } ); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC); } proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.CONST_FIELD, simpleName, target, relevance, image)); } } private static void addSimilarVariableProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, SimpleName node, boolean isWriteAccess, Collection proposals) { IBinding[] varsInScope= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(node, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY); if (varsInScope.length > 0) { // avoid corrections like int i= i; String otherNameInAssign= null; ASTNode parent= node.getParent(); if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) { // node must be initializer otherNameInAssign= ((VariableDeclarationFragment) parent).getName().getIdentifier(); } else if (parent.getNodeType() == ASTNode.ASSIGNMENT) { Assignment assignment= (Assignment) parent; if (isWriteAccess && assignment.getRightHandSide() instanceof SimpleName) { otherNameInAssign= ((SimpleName) assignment.getRightHandSide()).getIdentifier(); } else if (!isWriteAccess && assignment.getLeftHandSide() instanceof SimpleName) { otherNameInAssign= ((SimpleName) assignment.getLeftHandSide()).getIdentifier(); } } ITypeBinding guessedType= ASTResolving.guessBindingForReference(node); if (astRoot.getAST().resolveWellKnownType("java.lang.Object") == guessedType) { //$NON-NLS-1$ guessedType= null; // too many suggestions } String identifier= node.getIdentifier(); for (int i= 0; i < varsInScope.length; i++) { IVariableBinding curr= (IVariableBinding) varsInScope[i]; String currName= curr.getName(); boolean isFinal= Modifier.isFinal(curr.getModifiers()); if (!currName.equals(otherNameInAssign) && !(isFinal && curr.isField() && isWriteAccess)) { int relevance= 0; if (NameMatcher.isSimilarName(currName, identifier)) { relevance += 3; // variable with a similar name than the unresolved variable } if (currName.equalsIgnoreCase(identifier)) { relevance+= 5; } ITypeBinding varType= curr.getType(); if (guessedType != null && varType != null) { if (!isWriteAccess && TypeRules.canAssign(varType, guessedType) || isWriteAccess && TypeRules.canAssign(guessedType, varType)) { relevance += 2; // unresolved variable can be assign to this variable } } if (relevance > 0) { String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changevariable.description", currName); //$NON-NLS-1$ proposals.add(new RenameNodeCompletionProposal(label, cu, node.getStartPosition(), node.getLength(), currName, relevance)); } } } } if (binding != null && binding.isArray()) { String idLength= "length"; //$NON-NLS-1$ String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changevariable.description", idLength); //$NON-NLS-1$ proposals.add(new RenameNodeCompletionProposal(label, cu, node.getStartPosition(), node.getLength(), idLength, 8)); //$NON-NLS-1$ } } public static void getTypeProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (selectedNode == null) { return; } int kind= SimilarElementsRequestor.ALL_TYPES; ASTNode parent= selectedNode.getParent(); while (parent.getLength() == selectedNode.getLength()) { // get parent of type or variable fragment parent= parent.getParent(); } switch (parent.getNodeType()) { case ASTNode.TYPE_DECLARATION: TypeDeclaration typeDeclaration=(TypeDeclaration) parent; if (typeDeclaration.superInterfaces().contains(selectedNode)) { kind= SimilarElementsRequestor.INTERFACES; } else if (selectedNode.equals(typeDeclaration.getSuperclass())) { kind= SimilarElementsRequestor.CLASSES; } break; case ASTNode.METHOD_DECLARATION: MethodDeclaration methodDeclaration= (MethodDeclaration) parent; if (methodDeclaration.thrownExceptions().contains(selectedNode)) { kind= SimilarElementsRequestor.CLASSES; } else if (selectedNode.equals(methodDeclaration.getReturnType())) { kind= SimilarElementsRequestor.ALL_TYPES | SimilarElementsRequestor.VOIDTYPE; } break; case ASTNode.INSTANCEOF_EXPRESSION: kind= SimilarElementsRequestor.REF_TYPES; break; case ASTNode.THROW_STATEMENT: kind= SimilarElementsRequestor.REF_TYPES; break; case ASTNode.CLASS_INSTANCE_CREATION: if (((ClassInstanceCreation) parent).getAnonymousClassDeclaration() == null) { kind= SimilarElementsRequestor.CLASSES; } else { kind= SimilarElementsRequestor.REF_TYPES; } break; case ASTNode.SINGLE_VARIABLE_DECLARATION: int superParent= parent.getParent().getNodeType(); if (superParent == ASTNode.CATCH_CLAUSE) { kind= SimilarElementsRequestor.CLASSES; } break; case ASTNode.TAG_ELEMENT: kind= SimilarElementsRequestor.REF_TYPES; break; default: } Name node= null; if (selectedNode instanceof SimpleType) { node= ((SimpleType) selectedNode).getName(); } else if (selectedNode instanceof ArrayType) { Type elementType= ((ArrayType) selectedNode).getElementType(); if (elementType.isSimpleType()) { node= ((SimpleType) elementType).getName(); } } else if (selectedNode instanceof Name) { node= (Name) selectedNode; } else { return; } // change to similar type proposals addSimilarTypeProposals(kind, cu, node, 3, proposals); // add type addNewTypeProposals(cu, node, kind, 0, proposals); } private static void addSimilarTypeProposals(int kind, ICompilationUnit cu, Name node, int relevance, Collection proposals) throws CoreException { SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, node, kind); // try to resolve type in context -> highest severity String resolvedTypeName= null; ITypeBinding binding= ASTResolving.guessBindingForTypeReference(node); if (binding != null) { if (binding.isArray()) { binding= binding.getElementType(); } resolvedTypeName= binding.getQualifiedName(); proposals.add(createTypeRefChangeProposal(cu, resolvedTypeName, node, relevance + 2)); } // add all similar elements for (int i= 0; i < elements.length; i++) { SimilarElement elem= elements[i]; if ((elem.getKind() & SimilarElementsRequestor.ALL_TYPES) != 0) { String fullName= elem.getName(); if (!fullName.equals(resolvedTypeName)) { proposals.add(createTypeRefChangeProposal(cu, fullName, node, relevance)); } } } } private static CUCorrectionProposal createTypeRefChangeProposal(ICompilationUnit cu, String fullName, Name node, int relevance) throws CoreException { ImportRewrite importRewrite= new ImportRewrite(cu); importRewrite.setFindAmbiguosImports(true); String simpleName= importRewrite.addImport(fullName); String packName= Signature.getQualifier(fullName); String[] arg= { simpleName, packName }; CUCorrectionProposal proposal; if (node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) { // import only // import only String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importtype.description", arg); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL); proposal= new CUCorrectionProposal(label, cu, relevance + 100, image); } else { String label; if (packName.length() == 0) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.nopack.description", simpleName); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.description", arg); //$NON-NLS-1$ } proposal= new RenameNodeCompletionProposal(label, cu, node.getStartPosition(), node.getLength(), simpleName, relevance); //$NON-NLS-1$ } proposal.setImportRewrite(importRewrite); return proposal; } private static void addNewTypeProposals(ICompilationUnit cu, Name refNode, int kind, int relevance, Collection proposals) throws JavaModelException { Name node= refNode; do { String typeName= ASTResolving.getSimpleName(node); Name qualifier= null; // only propose to create types for qualifiers when the name starts with upper case boolean isPossibleName= Character.isUpperCase(typeName.charAt(0)) || (node == refNode); if (isPossibleName) { IPackageFragment enclosingPackage= null; IType enclosingType= null; if (node.isSimpleName()) { enclosingPackage= (IPackageFragment) cu.getParent(); // don't suggest member type, user can select it in wizard } else { Name qualifierName= ((QualifiedName) node).getQualifier(); // 24347 // IBinding binding= qualifierName.resolveBinding(); // if (binding instanceof ITypeBinding) { // enclosingType= Binding2JavaModel.find((ITypeBinding) binding, cu.getJavaProject()); IJavaElement[] res= cu.codeSelect(qualifierName.getStartPosition(), qualifierName.getLength()); if (res!= null && res.length > 0 && res[0] instanceof IType) { enclosingType= (IType) res[0]; } else { qualifier= qualifierName; enclosingPackage= JavaModelUtil.getPackageFragmentRoot(cu).getPackageFragment(ASTResolving.getFullName(qualifierName)); } } // new top level type if (enclosingPackage != null && !enclosingPackage.getCompilationUnit(typeName + ".java").exists()) { //$NON-NLS-1$ if ((kind & SimilarElementsRequestor.CLASSES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingPackage, relevance)); } if ((kind & SimilarElementsRequestor.INTERFACES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingPackage, relevance)); } } // new member type if (enclosingType != null && !enclosingType.isReadOnly() && !enclosingType.getType(typeName).exists()) { if ((kind & SimilarElementsRequestor.CLASSES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingType, relevance)); } if ((kind & SimilarElementsRequestor.INTERFACES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingType, relevance)); } } } node= qualifier; } while (node != null); } public static void getMethodProposals(IInvocationContext context, IProblemLocation problem, boolean needsNewName, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (!(selectedNode instanceof SimpleName)) { return; } SimpleName nameNode= (SimpleName) selectedNode; List arguments; Expression sender; boolean isSuperInvocation; ASTNode invocationNode= nameNode.getParent(); if (invocationNode instanceof MethodInvocation) { MethodInvocation methodImpl= (MethodInvocation) invocationNode; arguments= methodImpl.arguments(); sender= methodImpl.getExpression(); isSuperInvocation= false; } else if (invocationNode instanceof SuperMethodInvocation) { SuperMethodInvocation methodImpl= (SuperMethodInvocation) invocationNode; arguments= methodImpl.arguments(); sender= methodImpl.getQualifier(); isSuperInvocation= true; } else { return; } String methodName= nameNode.getIdentifier(); int nArguments= arguments.size(); // corrections IBinding[] bindings= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(nameNode, ScopeAnalyzer.METHODS); ArrayList parameterMismatchs= new ArrayList(); for (int i= 0; i < bindings.length; i++) { IMethodBinding binding= (IMethodBinding) bindings[i]; String curr= binding.getName(); if (curr.equals(methodName) && needsNewName) { parameterMismatchs.add(binding); } else if (binding.getParameterTypes().length == nArguments && NameMatcher.isSimilarName(methodName, curr)) { String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changemethod.description", curr); //$NON-NLS-1$ proposals.add(new RenameNodeCompletionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), curr, 6)); } } addParameterMissmatchProposals(context, problem, parameterMismatchs, invocationNode, arguments, proposals); // new method ITypeBinding binding= null; if (sender != null) { binding= sender.resolveTypeBinding(); } else { binding= Bindings.getBindingOfParentType(invocationNode); if (isSuperInvocation && binding != null) { binding= binding.getSuperclass(); } } if (binding != null && binding.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding); if (targetCU != null) { String label; Image image; String sig= getMethodSignature(methodName, arguments); if (cu.equals(targetCU)) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.description", sig); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE); } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", new Object[] { sig, targetCU.getElementName() } ); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); } proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 5, image)); if (binding.isAnonymous() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(binding, methodName, null) == null) { // no covering method ASTNode anonymDecl= astRoot.findDeclaringNode(binding); if (anonymDecl != null) { binding= Bindings.getBindingOfParentType(anonymDecl.getParent()); if (!binding.isAnonymous()) { String[] args= new String[] { sig, binding.getName() }; label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", args); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED); proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 5, image)); } } } } } if (!isSuperInvocation) { ASTNode parent= invocationNode.getParent(); while (parent instanceof Expression && parent.getNodeType() != ASTNode.CAST_EXPRESSION) { parent= parent.getParent(); } if (!isSuperInvocation && parent instanceof CastExpression) { addMissingCastParentsProposal(cu, (CastExpression) parent, sender, nameNode, getArgumentTypes(arguments), proposals); } } } private static void addMissingCastParentsProposal(ICompilationUnit cu, CastExpression expression, Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes, Collection proposals) { ITypeBinding castType= expression.getType().resolveBinding(); if (castType == null) { return; } if (paramTypes != null) { if (Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes) == null) { return; } } else if (Bindings.findFieldInHierarchy(castType, accessSelector.getIdentifier()) == null) { return; } ITypeBinding bindingToCast= accessExpression.resolveTypeBinding(); if (bindingToCast != null && !TypeRules.canCast(castType, bindingToCast)) { return; } IMethodBinding res= Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes); if (res != null) { AST ast= expression.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); CastExpression newCast= ast.newCastExpression(); newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType())); newCast.setExpression((Expression) rewrite.createCopyTarget(accessExpression)); ParenthesizedExpression parents= ast.newParenthesizedExpression(); parents.setExpression(newCast); ASTNode node= rewrite.createCopyTarget(expression.getExpression()); rewrite.replace(expression, node, null); rewrite.replace(accessExpression, parents, null); String label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.missingcastbrackets.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 8, image); proposals.add(proposal); } } private static void addParameterMissmatchProposals(IInvocationContext context, IProblemLocation problem, List similarElements, ASTNode invocationNode, List arguments, Collection proposals) throws CoreException { int nSimilarElements= similarElements.size(); ITypeBinding[] argTypes= getArgumentTypes(arguments); if (argTypes == null || nSimilarElements == 0) { return; } for (int i= 0; i < nSimilarElements; i++) { IMethodBinding elem = (IMethodBinding) similarElements.get(i); int diff= elem.getParameterTypes().length - argTypes.length; if (diff == 0) { int nProposals= proposals.size(); doEqualNumberOfParameters(context, invocationNode, problem, arguments, argTypes, elem, proposals); if (nProposals != proposals.size()) { return; // only suggest for one method (avoid duplicated proposals) } } else if (diff > 0) { doMoreParameters(context, problem, invocationNode, arguments, argTypes, elem, proposals); } else { doMoreArguments(context, problem, invocationNode, arguments, argTypes, elem, proposals); } } } private static void doMoreParameters(IInvocationContext context, IProblemLocation problem, ASTNode invocationNode, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException { ITypeBinding[] paramTypes= methodBinding.getParameterTypes(); int k= 0, nSkipped= 0; int diff= paramTypes.length - argTypes.length; int[] indexSkipped= new int[diff]; for (int i= 0; i < paramTypes.length; i++) { if (k < argTypes.length && TypeRules.canAssign(argTypes[k], paramTypes[i])) { k++; // match } else { if (nSkipped >= diff) { return; // too different } indexSkipped[nSkipped++]= i; } } ITypeBinding declaringType= methodBinding.getDeclaringClass(); ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); // add arguments { String[] arg= new String[] { getMethodSignature(methodBinding, false) }; String label; if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargument.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addarguments.description", arg); //$NON-NLS-1$ } AddArgumentCorrectionProposal proposal= new AddArgumentCorrectionProposal(label, context.getCompilationUnit(), invocationNode, indexSkipped, paramTypes, 8); proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD)); proposals.add(proposal); } // remove parameters if (!declaringType.isFromSource()) { return; } ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); if (targetCU != null) { ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length]; ITypeBinding[] changedTypes= new ITypeBinding[diff]; for (int i= diff - 1; i >= 0; i--) { int idx= indexSkipped[i]; changeDesc[idx]= new RemoveDescription(); changedTypes[i]= paramTypes[idx]; } String[] arg= new String[] { getMethodSignature(methodBinding, !cu.equals(targetCU)), getTypeNames(changedTypes) }; String label; if (methodBinding.isConstructor()) { if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparam.constr.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparams.constr.description", arg); //$NON-NLS-1$ } } else { if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparam.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparams.description", arg); //$NON-NLS-1$ } } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE); ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, null, 5, image); proposals.add(proposal); } } private static String getTypeNames(ITypeBinding[] types) { StringBuffer buf= new StringBuffer(); for (int i= 0; i < types.length; i++) { if (i > 0) { buf.append(", "); //$NON-NLS-1$ } buf.append(types[i].getName()); } return buf.toString(); } private static String getArgumentName(ICompilationUnit cu, List arguments, int index) { String def= String.valueOf(index + 1); ASTNode expr= (ASTNode) arguments.get(index); if (expr.getLength() > 18) { return def; } try { String str= cu.getBuffer().getText(expr.getStartPosition(), expr.getLength()); for (int i= 0; i < str.length(); i++) { if (Strings.isLineDelimiterChar(str.charAt(i))) { return def; } } ASTMatcher matcher= new ASTMatcher(); for (int i= 0; i < arguments.size(); i++) { if (i != index && matcher.safeSubtreeMatch(expr, arguments.get(i))) { return def; } } return '\'' + str + '\''; } catch (JavaModelException e) { JavaPlugin.log(e); } return def; } private static void doMoreArguments(IInvocationContext context, IProblemLocation problem, ASTNode invocationNode, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException { ITypeBinding[] paramTypes= methodBinding.getParameterTypes(); int k= 0, nSkipped= 0; int diff= argTypes.length - paramTypes.length; int[] indexSkipped= new int[diff]; for (int i= 0; i < argTypes.length; i++) { if (k < paramTypes.length && TypeRules.canAssign(argTypes[i], paramTypes[k])) { k++; // match } else { if (nSkipped >= diff) { return; // too different } indexSkipped[nSkipped++]= i; } } ITypeBinding declaringType= methodBinding.getDeclaringClass(); ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); // remove arguments { ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST()); for (int i= diff - 1; i >= 0; i--) { rewrite.remove((Expression) arguments.get(indexSkipped[i]), null); } String[] arg= new String[] { getMethodSignature(methodBinding, false) }; String label; if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeargument.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removearguments.description", arg); //$NON-NLS-1$ } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image); proposals.add(proposal); } // add parameters if (!declaringType.isFromSource()) { return; } ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); if (targetCU != null) { boolean isDifferentCU= !cu.equals(targetCU); if (isImplicitConstructor(methodBinding, targetCU)) { return; } ChangeDescription[] changeDesc= new ChangeDescription[argTypes.length]; ITypeBinding[] changeTypes= new ITypeBinding[diff]; for (int i= diff - 1; i >= 0; i--) { int idx= indexSkipped[i]; Expression arg= (Expression) arguments.get(idx); String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null; ITypeBinding newType= Bindings.normalizeTypeBinding(argTypes[idx]); if (newType == null) { newType= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } changeDesc[idx]= new InsertDescription(newType, name); changeTypes[i]= newType; } String[] arg= new String[] { getMethodSignature(methodBinding, isDifferentCU), getTypeNames(changeTypes) }; String label; if (methodBinding.isConstructor()) { if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparam.constr.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparams.constr.description", arg); //$NON-NLS-1$ } } else { if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparam.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparams.description", arg); //$NON-NLS-1$ } } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD); ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, null, 5, image); proposals.add(proposal); } } private static boolean isImplicitConstructor(IMethodBinding meth, ICompilationUnit targetCU) { if (meth.isConstructor() && meth.getParameterTypes().length == 0) { IMethodBinding[] bindings= meth.getDeclaringClass().getDeclaredMethods(); // implicit constructors must be the only constructor for (int i= 0; i < bindings.length; i++) { IMethodBinding curr= bindings[i]; if (curr.isConstructor() && curr != meth) { return false; } } ASTParser parser= ASTParser.newParser(AST.JLS2); parser.setSource(targetCU); parser.setFocalPosition(0); parser.setResolveBindings(true); CompilationUnit unit= (CompilationUnit) parser.createAST(null); return unit.findDeclaringNode(meth.getKey()) == null; } return false; } private static String getMethodSignature(IMethodBinding binding, boolean inOtherCU) { StringBuffer buf= new StringBuffer(); if (inOtherCU && !binding.isConstructor()) { buf.append(binding.getDeclaringClass().getName()).append('.'); } buf.append(binding.getName()); return getMethodSignature(buf.toString(), binding.getParameterTypes()); } private static String getMethodSignature(String name, List args) { ITypeBinding[] params= new ITypeBinding[args.size()]; for (int i= 0; i < args.size(); i++) { Expression expr= (Expression) args.get(i); ITypeBinding curr= Bindings.normalizeTypeBinding(expr.resolveTypeBinding()); if (curr == null) { curr= expr.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } params[i]= curr; } return getMethodSignature(name, params); } private static String getMethodSignature(String name, ITypeBinding[] params) { StringBuffer buf= new StringBuffer(); buf.append(name).append('('); for (int i= 0; i < params.length; i++) { if (i > 0) { buf.append(", "); //$NON-NLS-1$ } buf.append(params[i].getName()); } buf.append(')'); return buf.toString(); } private static void doEqualNumberOfParameters(IInvocationContext context, ASTNode invocationNode, IProblemLocation problem, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException { ITypeBinding[] paramTypes= methodBinding.getParameterTypes(); int[] indexOfDiff= new int[paramTypes.length]; int nDiffs= 0; for (int n= 0; n < argTypes.length; n++) { if (!TypeRules.canAssign(argTypes[n], paramTypes[n])) { indexOfDiff[nDiffs++]= n; } } ITypeBinding declaringType= methodBinding.getDeclaringClass(); ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode nameNode= problem.getCoveringNode(astRoot); if (nameNode == null) { return; } if (nDiffs == 0) { if (nameNode.getParent() instanceof MethodInvocation) { MethodInvocation inv= (MethodInvocation) nameNode.getParent(); if (inv.getExpression() == null) { addQualifierToOuterProposal(context, inv, methodBinding, proposals); } } return; } if (nDiffs == 1) { // one argument mismatching: try to fix int idx= indexOfDiff[0]; Expression nodeToCast= (Expression) arguments.get(idx); ITypeBinding castType= paramTypes[idx]; ITypeBinding binding= nodeToCast.resolveTypeBinding(); if (binding == null || TypeRules.canCast(castType, binding)) { String castTypeName= castType.getQualifiedName(); ASTRewriteCorrectionProposal proposal= TypeMismatchSubProcessor.createCastProposal(context, castTypeName, nodeToCast, 6); String[] arg= new String[] { getArgumentName(cu, arguments, idx), castTypeName}; proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargumentcast.description", arg)); //$NON-NLS-1$ proposals.add(proposal); } TypeMismatchSubProcessor.addChangeSenderTypeProposals(context, nodeToCast, castType, false, 5, proposals); } if (nDiffs == 2) { // try to swap int idx1= indexOfDiff[0]; int idx2= indexOfDiff[1]; boolean canSwap= TypeRules.canAssign(argTypes[idx1], paramTypes[idx2]) && TypeRules.canAssign(argTypes[idx2], paramTypes[idx1]); if (canSwap) { Expression arg1= (Expression) arguments.get(idx1); Expression arg2= (Expression) arguments.get(idx2); ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST()); rewrite.replace(arg1, rewrite.createCopyTarget(arg2), null); rewrite.replace(arg2, rewrite.createCopyTarget(arg1), null); { String[] arg= new String[] { getArgumentName(cu, arguments, idx1), getArgumentName(cu, arguments, idx2) }; String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swaparguments.description", arg); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image); proposals.add(proposal); } if (declaringType.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); if (targetCU != null) { ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length]; for (int i= 0; i < nDiffs; i++) { changeDesc[idx1]= new SwapDescription(idx2); } ITypeBinding[] swappedTypes= new ITypeBinding[] { paramTypes[idx1], paramTypes[idx2] }; String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getTypeNames(swappedTypes) }; String label; if (methodBinding.isConstructor()) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swapparams.constr.description", args); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swapparams.description", args); //$NON-NLS-1$ } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, null, 5, image); proposals.add(proposal); } } return; } } if (declaringType.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); if (targetCU != null) { ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length]; for (int i= 0; i < nDiffs; i++) { int diffIndex= indexOfDiff[i]; Expression arg= (Expression) arguments.get(diffIndex); String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null; changeDesc[diffIndex]= new EditDescription(argTypes[diffIndex], name); } String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getMethodSignature(methodBinding.getName(), arguments) }; String label; if (methodBinding.isConstructor()) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changeparamsignature.constr.description", args); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changeparamsignature.description", args); //$NON-NLS-1$ } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, null, 7, image); proposals.add(proposal); } } } private static ITypeBinding[] getArgumentTypes(List arguments) { ITypeBinding[] res= new ITypeBinding[arguments.size()]; for (int i= 0; i < res.length; i++) { Expression expression= (Expression) arguments.get(i); ITypeBinding curr= expression.resolveTypeBinding(); if (curr == null) { return null; } curr= Bindings.normalizeTypeBinding(curr); if (curr == null) { curr= expression.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } res[i]= curr; } return res; } private static void addQualifierToOuterProposal(IInvocationContext context, MethodInvocation invocationNode, IMethodBinding binding, Collection proposals) throws CoreException { ITypeBinding declaringType= binding.getDeclaringClass(); ITypeBinding parentType= Bindings.getBindingOfParentType(invocationNode); ITypeBinding currType= parentType; boolean isInstanceMethod= !Modifier.isStatic(binding.getModifiers()); while (currType != null && !Bindings.isSuperType(declaringType, currType)) { if (isInstanceMethod && Modifier.isStatic(currType.getModifiers())) { return; } currType= currType.getDeclaringClass(); } if (currType == null || currType == parentType) { return; } ASTRewrite rewrite= ASTRewrite.create(invocationNode.getAST()); ImportRewrite imports= new ImportRewrite(context.getCompilationUnit()); AST ast= invocationNode.getAST(); String qualifier= imports.addImport(currType); Name name= ASTNodeFactory.newName(ast, qualifier); Expression newExpression; if (isInstanceMethod) { ThisExpression expr= ast.newThisExpression(); expr.setQualifier(name); newExpression= expr; } else { newExpression= name; } rewrite.set(invocationNode, MethodInvocation.EXPRESSION_PROPERTY, newExpression, null); String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetoouter.description", currType.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image); proposal.setImportRewrite(imports); proposals.add(proposal); } public static void getConstructorProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (selectedNode == null) { return; } ITypeBinding targetBinding= null; List arguments= null; IMethodBinding recursiveConstructor= null; int type= selectedNode.getNodeType(); if (type == ASTNode.CLASS_INSTANCE_CREATION) { ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode; IBinding binding= creation.getName().resolveBinding(); if (binding instanceof ITypeBinding) { targetBinding= (ITypeBinding) binding; arguments= creation.arguments(); } } else if (type == ASTNode.SUPER_CONSTRUCTOR_INVOCATION) { ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode); if (typeBinding != null && !typeBinding.isAnonymous()) { targetBinding= typeBinding.getSuperclass(); arguments= ((SuperConstructorInvocation) selectedNode).arguments(); } } else if (type == ASTNode.CONSTRUCTOR_INVOCATION) { ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode); if (typeBinding != null && !typeBinding.isAnonymous()) { targetBinding= typeBinding; arguments= ((ConstructorInvocation) selectedNode).arguments(); recursiveConstructor= ASTResolving.findParentMethodDeclaration(selectedNode).resolveBinding(); } } if (targetBinding == null) { return; } IMethodBinding[] methods= targetBinding.getDeclaredMethods(); ArrayList similarElements= new ArrayList(); for (int i= 0; i < methods.length; i++) { IMethodBinding curr= methods[i]; if (curr.isConstructor() && recursiveConstructor != curr) { similarElements.add(curr); // similar elements can contain a implicit default constructor } } addParameterMissmatchProposals(context, problem, similarElements, selectedNode, arguments, proposals); if (targetBinding.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, targetBinding); if (targetCU != null) { String[] args= new String[] { getMethodSignature( targetBinding.getName(), arguments) }; String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconstructor.description", args); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); proposals.add(new NewMethodCompletionProposal(label, targetCU, selectedNode, arguments, targetBinding, 5, image)); } } } public static void getAmbiguosTypeReferenceProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { final ICompilationUnit cu= context.getCompilationUnit(); int offset= problem.getOffset(); int len= problem.getLength(); IJavaElement[] elements= cu.codeSelect(offset, len); for (int i= 0; i < elements.length; i++) { IJavaElement curr= elements[i]; if (curr instanceof IType && !TypeFilter.isFiltered((IType) curr)) { String qualifiedTypeName= JavaModelUtil.getFullyQualifiedName((IType) curr); ImportRewrite imports= new ImportRewrite(cu); imports.setFindAmbiguosImports(true); imports.addImport(qualifiedTypeName); String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importexplicit.description", qualifiedTypeName); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL); CUCorrectionProposal proposal= new CUCorrectionProposal(label, cu, 5, image); proposal.setImportRewrite(imports); proposals.add(proposal); } } } public static void getArrayAccessProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { CompilationUnit root= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(root); if (!(selectedNode instanceof MethodInvocation)) { return; } MethodInvocation decl= (MethodInvocation) selectedNode; SimpleName nameNode= decl.getName(); String methodName= nameNode.getIdentifier(); IBinding[] bindings= (new ScopeAnalyzer(root)).getDeclarationsInScope(nameNode, ScopeAnalyzer.METHODS); for (int i= 0; i < bindings.length; i++) { String currName= bindings[i].getName(); if (NameMatcher.isSimilarName(methodName, currName)) { String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.arraychangetomethod.description", currName); //$NON-NLS-1$ proposals.add(new RenameNodeCompletionProposal(label, context.getCompilationUnit(), nameNode.getStartPosition(), nameNode.getLength(), currName, 6)); } } // always suggest 'length' String lengthId= "length"; //$NON-NLS-1$ String label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.arraychangetolength.description"); //$NON-NLS-1$ int offset= nameNode.getStartPosition(); int length= decl.getStartPosition() + decl.getLength() - offset; proposals.add(new RenameNodeCompletionProposal(label, context.getCompilationUnit(), offset, length, lengthId, 7)); } }
44,204
Bug 44204 Promote individual methods to interface.
Methods should be able to be promoted to an implemented interface. IE interface SomeThing { public DoDad getDoDad(); } class MyThing implements Something { private DoDad doDad=new DoDad(); public DoDad getDoDad() { return doDad; } public void setDoDad(DoDad dad) { this.doDad=dad; } ^^^^^^^^ } Ctrl-1 on the ^'d should produce 'Declare in interface 'Something''. if more than on interface, multiple options should be given, much like what import does. This enhancement would save time copying, pasting and trimming. Regards, Andy
resolved fixed
37ef19b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T15:52:53Z
2003-10-05T16:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementImageProvider.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.viewsupport; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.util.Assert; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.model.IWorkbenchAdapter; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaElementImageDescriptor; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.JavaUIMessages; /** * Default strategy of the Java plugin for the construction of Java element icons. */ public class JavaElementImageProvider { /** * Flags for the JavaImageLabelProvider: * Generate images with overlays. */ public final static int OVERLAY_ICONS= 0x1; /** * Generate small sized images. */ public final static int SMALL_ICONS= 0x2; /** * Use the 'light' style for rendering types. */ public final static int LIGHT_TYPE_ICONS= 0x4; public static final Point SMALL_SIZE= new Point(16, 16); public static final Point BIG_SIZE= new Point(22, 16); private static ImageDescriptor DESC_OBJ_PROJECT_CLOSED; private static ImageDescriptor DESC_OBJ_PROJECT; { ISharedImages images= JavaPlugin.getDefault().getWorkbench().getSharedImages(); DESC_OBJ_PROJECT_CLOSED= images.getImageDescriptor(IDE.SharedImages.IMG_OBJ_PROJECT_CLOSED); DESC_OBJ_PROJECT= images.getImageDescriptor(IDE.SharedImages.IMG_OBJ_PROJECT); } private ImageDescriptorRegistry fRegistry; public JavaElementImageProvider() { fRegistry= null; // lazy initialization } /** * Returns the icon for a given element. The icon depends on the element type * and element properties. If configured, overlay icons are constructed for * <code>ISourceReference</code>s. * @param flags Flags as defined by the JavaImageLabelProvider */ public Image getImageLabel(Object element, int flags) { return getImageLabel(computeDescriptor(element, flags)); } private Image getImageLabel(ImageDescriptor descriptor){ if (descriptor == null) return null; return getRegistry().get(descriptor); } private ImageDescriptorRegistry getRegistry() { if (fRegistry == null) { fRegistry= JavaPlugin.getImageDescriptorRegistry(); } return fRegistry; } private ImageDescriptor computeDescriptor(Object element, int flags){ if (element instanceof IJavaElement) { return getJavaImageDescriptor((IJavaElement) element, flags); } else if (element instanceof IFile) { IFile file= (IFile) element; if ("java".equals(file.getFileExtension())) { //$NON-NLS-1$ return getCUResourceImageDescriptor(file, flags); // image for a CU not on the build path } return getWorkbenchImageDescriptor(file, flags); } else if (element instanceof IAdaptable) { return getWorkbenchImageDescriptor((IAdaptable) element, flags); } return null; } private static boolean showOverlayIcons(int flags) { return (flags & OVERLAY_ICONS) != 0; } private static boolean useSmallSize(int flags) { return (flags & SMALL_ICONS) != 0; } private static boolean useLightIcons(int flags) { return (flags & LIGHT_TYPE_ICONS) != 0; } /** * Returns an image descriptor for a compilation unit not on the class path. * The descriptor includes overlays, if specified. */ public ImageDescriptor getCUResourceImageDescriptor(IFile file, int flags) { Point size= useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; return new JavaElementImageDescriptor(JavaPluginImages.DESC_OBJS_CUNIT_RESOURCE, 0, size); } /** * Returns an image descriptor for a java element. The descriptor includes overlays, if specified. */ public ImageDescriptor getJavaImageDescriptor(IJavaElement element, int flags) { int adornmentFlags= computeJavaAdornmentFlags(element, flags); Point size= useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; return new JavaElementImageDescriptor(getBaseImageDescriptor(element, flags), adornmentFlags, size); } /** * Returns an image descriptor for a IAdaptable. The descriptor includes overlays, if specified (only error ticks apply). * Returns <code>null</code> if no image could be found. */ public ImageDescriptor getWorkbenchImageDescriptor(IAdaptable adaptable, int flags) { IWorkbenchAdapter wbAdapter= (IWorkbenchAdapter) adaptable.getAdapter(IWorkbenchAdapter.class); if (wbAdapter == null) { return null; } ImageDescriptor descriptor= wbAdapter.getImageDescriptor(adaptable); if (descriptor == null) { return null; } Point size= useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; return new JavaElementImageDescriptor(descriptor, 0, size); } // ---- Computation of base image key ------------------------------------------------- /** * Returns an image descriptor for a java element. This is the base image, no overlays. */ public ImageDescriptor getBaseImageDescriptor(IJavaElement element, int renderFlags) { try { switch (element.getElementType()) { case IJavaElement.INITIALIZER: return JavaPluginImages.DESC_MISC_PRIVATE; // 23479 case IJavaElement.METHOD: IMember member= (IMember) element; return getMethodImageDescriptor(member.getDeclaringType().isInterface(), member.getFlags()); case IJavaElement.FIELD: IField field= (IField) element; return getFieldImageDescriptor(field.getDeclaringType().isInterface(), field.getFlags()); case IJavaElement.LOCAL_VARIABLE: return JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE; case IJavaElement.PACKAGE_DECLARATION: return JavaPluginImages.DESC_OBJS_PACKDECL; case IJavaElement.IMPORT_DECLARATION: return JavaPluginImages.DESC_OBJS_IMPDECL; case IJavaElement.IMPORT_CONTAINER: return JavaPluginImages.DESC_OBJS_IMPCONT; case IJavaElement.TYPE: { IType type= (IType) element; boolean isInterface= type.isInterface(); if (useLightIcons(renderFlags)) { return isInterface ? JavaPluginImages.DESC_OBJS_INTERFACEALT : JavaPluginImages.DESC_OBJS_CLASSALT; } boolean isInner= type.getDeclaringType() != null; boolean isInInterface= isInner && type.getDeclaringType().isInterface(); return getTypeImageDescriptor(isInterface, isInner, isInInterface, type.getFlags()); } case IJavaElement.PACKAGE_FRAGMENT_ROOT: { IPackageFragmentRoot root= (IPackageFragmentRoot) element; if (root.isArchive()) { IPath attach= root.getSourceAttachmentPath(); if (root.isExternal()) { if (attach == null) { return JavaPluginImages.DESC_OBJS_EXTJAR; } else { return JavaPluginImages.DESC_OBJS_EXTJAR_WSRC; } } else { if (attach == null) { return JavaPluginImages.DESC_OBJS_JAR; } else { return JavaPluginImages.DESC_OBJS_JAR_WSRC; } } } else { return JavaPluginImages.DESC_OBJS_PACKFRAG_ROOT; } } case IJavaElement.PACKAGE_FRAGMENT: return getPackageFragmentIcon(element, renderFlags); case IJavaElement.COMPILATION_UNIT: return JavaPluginImages.DESC_OBJS_CUNIT; case IJavaElement.CLASS_FILE: /* this is too expensive for large packages try { IClassFile cfile= (IClassFile)element; if (cfile.isClass()) return JavaPluginImages.IMG_OBJS_CFILECLASS; return JavaPluginImages.IMG_OBJS_CFILEINT; } catch(JavaModelException e) { // fall through; }*/ return JavaPluginImages.DESC_OBJS_CFILE; case IJavaElement.JAVA_PROJECT: IJavaProject jp= (IJavaProject)element; if (jp.getProject().isOpen()) { IProject project= jp.getProject(); IWorkbenchAdapter adapter= (IWorkbenchAdapter)project.getAdapter(IWorkbenchAdapter.class); if (adapter != null) { ImageDescriptor result= adapter.getImageDescriptor(project); if (result != null) return result; } return DESC_OBJ_PROJECT; } return DESC_OBJ_PROJECT_CLOSED; case IJavaElement.JAVA_MODEL: return JavaPluginImages.DESC_OBJS_JAVA_MODEL; } Assert.isTrue(false, JavaUIMessages.getString("JavaImageLabelprovider.assert.wrongImage")); //$NON-NLS-1$ return null; //$NON-NLS-1$ } catch (JavaModelException e) { if (e.isDoesNotExist()) return JavaPluginImages.DESC_OBJS_UNKNOWN; JavaPlugin.log(e); return JavaPluginImages.DESC_OBJS_GHOST; } } protected ImageDescriptor getPackageFragmentIcon(IJavaElement element, int renderFlags) throws JavaModelException { IPackageFragment fragment= (IPackageFragment)element; boolean containsJavaElements= false; try { containsJavaElements= fragment.hasChildren(); } catch(JavaModelException e) { // assuming no children; } if(!containsJavaElements && (fragment.getNonJavaResources().length > 0)) return JavaPluginImages.DESC_OBJS_EMPTY_PACKAGE_RESOURCES; else if (!containsJavaElements) return JavaPluginImages.DESC_OBJS_EMPTY_PACKAGE; return JavaPluginImages.DESC_OBJS_PACKAGE; } public void dispose() { } // ---- Methods to compute the adornments flags --------------------------------- private int computeJavaAdornmentFlags(IJavaElement element, int renderFlags) { int flags= 0; if (showOverlayIcons(renderFlags) && element instanceof IMember) { try { IMember member= (IMember) element; if (element.getElementType() == IJavaElement.METHOD && ((IMethod)element).isConstructor()) flags |= JavaElementImageDescriptor.CONSTRUCTOR; int modifiers= member.getFlags(); if (Flags.isAbstract(modifiers) && confirmAbstract(member)) flags |= JavaElementImageDescriptor.ABSTRACT; if (Flags.isFinal(modifiers) || isInterfaceField(member)) flags |= JavaElementImageDescriptor.FINAL; if (Flags.isSynchronized(modifiers) && confirmSynchronized(member)) flags |= JavaElementImageDescriptor.SYNCHRONIZED; if (Flags.isStatic(modifiers) || isInterfaceField(member)) flags |= JavaElementImageDescriptor.STATIC; if (Flags.isDeprecated(modifiers)) flags |= JavaElementImageDescriptor.DEPRECATED; if (member.getElementType() == IJavaElement.TYPE) { if (JavaModelUtil.hasMainMethod((IType) member)) { flags |= JavaElementImageDescriptor.RUNNABLE; } } } catch (JavaModelException e) { // do nothing. Can't compute runnable adornment or get flags } } return flags; } private static boolean confirmAbstract(IMember element) throws JavaModelException { // never show the abstract symbol on interfaces or members in interfaces if (element.getElementType() == IJavaElement.TYPE) { return ((IType) element).isClass(); } return element.getDeclaringType().isClass(); } private static boolean isInterfaceField(IMember element) throws JavaModelException { // always show the final && static symbol on interface fields if (element.getElementType() == IJavaElement.FIELD) { return element.getDeclaringType().isInterface(); } return false; } private static boolean confirmSynchronized(IJavaElement member) { // Synchronized types are allowed but meaningless. return member.getElementType() != IJavaElement.TYPE; } public static ImageDescriptor getMethodImageDescriptor(boolean isInInterface, int flags) { if (Flags.isPublic(flags) || isInInterface) return JavaPluginImages.DESC_MISC_PUBLIC; if (Flags.isProtected(flags)) return JavaPluginImages.DESC_MISC_PROTECTED; if (Flags.isPrivate(flags)) return JavaPluginImages.DESC_MISC_PRIVATE; return JavaPluginImages.DESC_MISC_DEFAULT; } public static ImageDescriptor getFieldImageDescriptor(boolean isInInterface, int flags) { if (Flags.isPublic(flags) || isInInterface) return JavaPluginImages.DESC_FIELD_PUBLIC; if (Flags.isProtected(flags)) return JavaPluginImages.DESC_FIELD_PROTECTED; if (Flags.isPrivate(flags)) return JavaPluginImages.DESC_FIELD_PRIVATE; return JavaPluginImages.DESC_FIELD_DEFAULT; } public static ImageDescriptor getTypeImageDescriptor(boolean isInterface, boolean isInner, boolean isInInterface, int flags) { if (isInner) { if (isInterface) { return getInnerInterfaceImageDescriptor(isInInterface, flags); } else { return getInnerClassImageDescriptor(isInInterface, flags); } } else { if (isInterface) { return getInterfaceImageDescriptor(flags); } else { return getClassImageDescriptor(flags); } } } private static ImageDescriptor getClassImageDescriptor(int flags) { if (Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags)) return JavaPluginImages.DESC_OBJS_CLASS; else return JavaPluginImages.DESC_OBJS_CLASS_DEFAULT; } private static ImageDescriptor getInnerClassImageDescriptor(boolean isInInterface, int flags) { if (Flags.isPublic(flags) || isInInterface) return JavaPluginImages.DESC_OBJS_INNER_CLASS_PUBLIC; else if (Flags.isPrivate(flags)) return JavaPluginImages.DESC_OBJS_INNER_CLASS_PRIVATE; else if (Flags.isProtected(flags)) return JavaPluginImages.DESC_OBJS_INNER_CLASS_PROTECTED; else return JavaPluginImages.DESC_OBJS_INNER_CLASS_DEFAULT; } private static ImageDescriptor getInterfaceImageDescriptor(int flags) { if (Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags)) return JavaPluginImages.DESC_OBJS_INTERFACE; else return JavaPluginImages.DESC_OBJS_INTERFACE_DEFAULT; } private static ImageDescriptor getInnerInterfaceImageDescriptor(boolean isInInterface, int flags) { if (Flags.isPublic(flags) || isInInterface) return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PUBLIC; else if (Flags.isPrivate(flags)) return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PRIVATE; else if (Flags.isProtected(flags)) return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PROTECTED; else return JavaPluginImages.DESC_OBJS_INTERFACE_DEFAULT; } }
49,099
Bug 49099 Reduced Search menu does too much [search]
I200312180010 The reduced search menu preference (work in progress) does too much and therefore I cannot use it: Exmples: - select an interface (in outline or any other view where you already know it is an interface. Try to search for implementors ==> not possible. - same applies for fields: it is no longer possible to search for read/write access.
resolved fixed
cfdbbb3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T16:41:28Z
2003-12-18T09:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaBasePreferencePage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ // AW package org.eclipse.jdt.internal.ui.preferences; import java.util.ArrayList; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.refactoring.RefactoringSavePreferences; import org.eclipse.jdt.ui.PreferenceConstants; /* * The page for setting general java plugin preferences. * See PreferenceConstants to access or change these values through public API. */ public class JavaBasePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private static final String OPEN_TYPE_HIERARCHY= PreferenceConstants.OPEN_TYPE_HIERARCHY; private static final String OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE= PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE; private static final String OPEN_TYPE_HIERARCHY_IN_VIEW_PART= PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_VIEW_PART; private static final String DOUBLE_CLICK= PreferenceConstants.DOUBLE_CLICK; private static final String DOUBLE_CLICK_GOES_INTO= PreferenceConstants.DOUBLE_CLICK_GOES_INTO; private static final String DOUBLE_CLICK_EXPANDS= PreferenceConstants.DOUBLE_CLICK_EXPANDS; private ArrayList fCheckBoxes; private ArrayList fRadioButtons; private ArrayList fTextControls; public JavaBasePreferencePage() { super(); setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); setDescription(PreferencesMessages.getString("JavaBasePreferencePage.description")); //$NON-NLS-1$ fRadioButtons= new ArrayList(); fCheckBoxes= new ArrayList(); fTextControls= new ArrayList(); } /* * @see IWorkbenchPreferencePage#init(IWorkbench) */ public void init(IWorkbench workbench) { } /* * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.JAVA_BASE_PREFERENCE_PAGE); } private Button addRadioButton(Composite parent, String label, String key, String value) { GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); Button button= new Button(parent, SWT.RADIO); button.setText(label); button.setData(new String[] { key, value }); button.setLayoutData(gd); button.setSelection(value.equals(getPreferenceStore().getString(key))); fRadioButtons.add(button); return button; } private Button addCheckBox(Composite parent, String label, String key) { GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); Button button= new Button(parent, SWT.CHECK); button.setText(label); button.setData(key); button.setLayoutData(gd); button.setSelection(getPreferenceStore().getBoolean(key)); fCheckBoxes.add(button); return button; } protected Control createContents(Composite parent) { initializeDialogUnits(parent); Composite result= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); layout.marginWidth= 0; layout.verticalSpacing= convertVerticalDLUsToPixels(10); layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); result.setLayout(layout); // new Label(composite, SWT.NONE); // spacer // Group linkSettings= new Group(result, SWT.NONE); // linkSettings.setLayout(new GridLayout()); // linkSettings.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // linkSettings.setText(PreferencesMessages.getString("JavaBasePreferencePage.linkSettings.text")); //$NON-NLS-1$ //addCheckBox(linkSettings, PreferencesMessages.getString("JavaBasePreferencePage.linkJavaBrowsingViewsCheckbox.text"), LINK_BROWSING_VIEW_TO_EDITOR); //$NON-NLS-1$ //addCheckBox(linkSettings, PreferencesMessages.getString("JavaBasePreferencePage.linkPackageView"), LINK_PACKAGES_TO_EDITOR); //$NON-NLS-1$ //addCheckBox(linkSettings, PreferencesMessages.getString("JavaBasePreferencePage.linkTypeHierarchy"), LINK_TYPEHIERARCHY_TO_EDITOR); //$NON-NLS-1$ // new Label(result, SWT.NONE); // spacer Group doubleClickGroup= new Group(result, SWT.NONE); doubleClickGroup.setLayout(new GridLayout()); doubleClickGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); doubleClickGroup.setText(PreferencesMessages.getString("JavaBasePreferencePage.doubleclick.action")); //$NON-NLS-1$ addRadioButton(doubleClickGroup, PreferencesMessages.getString("JavaBasePreferencePage.doubleclick.gointo"), DOUBLE_CLICK, DOUBLE_CLICK_GOES_INTO); //$NON-NLS-1$ addRadioButton(doubleClickGroup, PreferencesMessages.getString("JavaBasePreferencePage.doubleclick.expand"), DOUBLE_CLICK, DOUBLE_CLICK_EXPANDS); //$NON-NLS-1$ // new Label(result, SWT.NONE); // spacer Group typeHierarchyGroup= new Group(result, SWT.NONE); typeHierarchyGroup.setLayout(new GridLayout()); typeHierarchyGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); typeHierarchyGroup.setText(PreferencesMessages.getString("JavaBasePreferencePage.openTypeHierarchy")); //$NON-NLS-1$ addRadioButton(typeHierarchyGroup, PreferencesMessages.getString("JavaBasePreferencePage.inPerspective"), OPEN_TYPE_HIERARCHY, OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE); //$NON-NLS-1$ addRadioButton(typeHierarchyGroup, PreferencesMessages.getString("JavaBasePreferencePage.inView"), OPEN_TYPE_HIERARCHY, OPEN_TYPE_HIERARCHY_IN_VIEW_PART); //$NON-NLS-1$ Group refactoringGroup= new Group(result, SWT.NONE); refactoringGroup.setLayout(new GridLayout()); refactoringGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); refactoringGroup.setText(PreferencesMessages.getString("JavaBasePreferencePage.refactoring.title")); //$NON-NLS-1$ addCheckBox(refactoringGroup, PreferencesMessages.getString("JavaBasePreferencePage.refactoring.auto_save"), //$NON-NLS-1$ RefactoringSavePreferences.PREF_SAVE_ALL_EDITORS); Dialog.applyDialogFont(result); return result; } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { IPreferenceStore store= getPreferenceStore(); for (int i= 0; i < fCheckBoxes.size(); i++) { Button button= (Button) fCheckBoxes.get(i); String key= (String) button.getData(); button.setSelection(store.getDefaultBoolean(key)); } for (int i= 0; i < fRadioButtons.size(); i++) { Button button= (Button) fRadioButtons.get(i); String[] info= (String[]) button.getData(); button.setSelection(info[1].equals(store.getDefaultString(info[0]))); } for (int i= 0; i < fTextControls.size(); i++) { Text text= (Text) fTextControls.get(i); String key= (String) text.getData(); text.setText(store.getDefaultString(key)); } super.performDefaults(); } /* * @see IPreferencePage#performOk() */ public boolean performOk() { IPreferenceStore store= getPreferenceStore(); for (int i= 0; i < fCheckBoxes.size(); i++) { Button button= (Button) fCheckBoxes.get(i); String key= (String) button.getData(); store.setValue(key, button.getSelection()); } for (int i= 0; i < fRadioButtons.size(); i++) { Button button= (Button) fRadioButtons.get(i); if (button.getSelection()) { String[] info= (String[]) button.getData(); store.setValue(info[0], info[1]); } } for (int i= 0; i < fTextControls.size(); i++) { Text text= (Text) fTextControls.get(i); String key= (String) text.getData(); store.setValue(key, text.getText()); } JavaPlugin.getDefault().savePluginPreferences(); return super.performOk(); } }
49,099
Bug 49099 Reduced Search menu does too much [search]
I200312180010 The reduced search menu preference (work in progress) does too much and therefore I cannot use it: Exmples: - select an interface (in outline or any other view where you already know it is an interface. Try to search for implementors ==> not possible. - same applies for fields: it is no longer possible to search for read/write access.
resolved fixed
cfdbbb3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T16:41:28Z
2003-12-18T09:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/WorkInProgressPreferencePage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; /** * Preference page for work in progress. */ public class WorkInProgressPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { public static final String PREF_FORMATTER= "use_new_formatter"; //$NON-NLS-1$ public static final String PREF_SEARCH_MENU= "small_search_menu"; //$NON-NLS-1$ private static final String PREF_BROWSER_WIDGET_IN_JAVADOC_VIEW= "org.eclipse.jdt.ui.browserWidgetInJavadocView"; //$NON-NLS-1$ // PreferenceConstants.APPEARANCE_BROWSER_WIDGET_IN_JAVADOC_VIEW; private List fCheckBoxes; private List fRadioButtons; private List fTextControls; /** * creates a new preference page. */ public WorkInProgressPreferencePage() { setPreferenceStore(getPreferenceStore()); fRadioButtons= new ArrayList(); fCheckBoxes= new ArrayList(); fTextControls= new ArrayList(); } private Button addCheckBox(Composite parent, String label, String key) { GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); Button button= new Button(parent, SWT.CHECK); button.setText(label); button.setData(key); button.setLayoutData(gd); button.setSelection(getPreferenceStore().getBoolean(key)); fCheckBoxes.add(button); return button; } /* * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), "WORK_IN_PROGRESS_PREFERENCE_PAGE"); //$NON-NLS-1$ } protected Control createContents(Composite parent) { initializeDialogUnits(parent); Composite result= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); layout.marginWidth= 0; layout.verticalSpacing= convertVerticalDLUsToPixels(10); layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); result.setLayout(layout); addCheckBox(result, PreferencesMessages.getString("WorkInProgress.browserWidgetInJavadocView"), PREF_BROWSER_WIDGET_IN_JAVADOC_VIEW); //$NON-NLS-1$ Group group= new Group(result, SWT.NONE); group.setLayout(new GridLayout()); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setText(PreferencesMessages.getString("WorkInProgress.search")); //$NON-NLS-1$ addCheckBox(group, PreferencesMessages.getString("WorkInProgress.search.small_menu"), PREF_SEARCH_MENU); //$NON-NLS-1$ applyDialogFont(result); return result; } /* * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) */ public void init(IWorkbench workbench) { } protected void createSpacer(Composite composite, int columnSpan) { Label label= new Label(composite, SWT.NONE); GridData gd= new GridData(); gd.horizontalSpan= columnSpan; label.setLayoutData(gd); } /* * @see org.eclipse.jface.preference.PreferencePage#doGetPreferenceStore() */ protected IPreferenceStore doGetPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { IPreferenceStore store= getPreferenceStore(); for (int i= 0; i < fCheckBoxes.size(); i++) { Button button= (Button) fCheckBoxes.get(i); String key= (String) button.getData(); button.setSelection(store.getDefaultBoolean(key)); } for (int i= 0; i < fRadioButtons.size(); i++) { Button button= (Button) fRadioButtons.get(i); String[] info= (String[]) button.getData(); button.setSelection(info[1].equals(store.getDefaultString(info[0]))); } for (int i= 0; i < fTextControls.size(); i++) { Text text= (Text) fTextControls.get(i); String key= (String) text.getData(); text.setText(store.getDefaultString(key)); } super.performDefaults(); } /* * @see IPreferencePage#performOk() */ public boolean performOk() { IPreferenceStore store= getPreferenceStore(); for (int i= 0; i < fCheckBoxes.size(); i++) { Button button= (Button) fCheckBoxes.get(i); String key= (String) button.getData(); store.setValue(key, button.getSelection()); } for (int i= 0; i < fRadioButtons.size(); i++) { Button button= (Button) fRadioButtons.get(i); if (button.getSelection()) { String[] info= (String[]) button.getData(); store.setValue(info[0], info[1]); } } for (int i= 0; i < fTextControls.size(); i++) { Text text= (Text) fTextControls.get(i); String key= (String) text.getData(); store.setValue(key, text.getText()); } JavaPlugin.getDefault().savePluginPreferences(); return super.performOk(); } /** * @param store */ public static void initDefaults(IPreferenceStore store) { store.setDefault(PreferenceConstants.EDITOR_SMART_SEMICOLON, false); store.setDefault(PreferenceConstants.EDITOR_SMART_OPENING_BRACE, false); store.setDefault(PreferenceConstants.EDITOR_QUICKASSIST_LIGHTBULB, false); store.setDefault(PREF_SEARCH_MENU, true); store.setDefault(PREF_BROWSER_WIDGET_IN_JAVADOC_VIEW, false); } }
49,099
Bug 49099 Reduced Search menu does too much [search]
I200312180010 The reduced search menu preference (work in progress) does too much and therefore I cannot use it: Exmples: - select an interface (in outline or any other view where you already know it is an interface. Try to search for implementors ==> not possible. - same applies for fields: it is no longer possible to search for read/write access.
resolved fixed
cfdbbb3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T16:41:28Z
2003-12-18T09:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/PreferenceConstants.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.RGB; import org.eclipse.jface.action.Action; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.ui.texteditor.AbstractTextEditor; import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.text.IJavaColorConstants; import org.eclipse.jdt.internal.ui.text.spelling.SpellCheckEngine; import org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellCheckPreferenceKeys; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightings; import org.eclipse.jdt.internal.ui.preferences.NewJavaProjectPreferencePage; import org.eclipse.jdt.internal.ui.preferences.WorkInProgressPreferencePage; import org.eclipse.jdt.internal.ui.preferences.formatter.ProfileManager; /** * Preference constants used in the JDT-UI preference store. Clients should only read the * JDT-UI preference store using these values. Clients are not allowed to modify the * preference store programmatically. * * @since 2.0 */ public class PreferenceConstants { private PreferenceConstants() { } /** * A named preference that controls return type rendering of methods in the UI. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> return types * are rendered * </p> */ public static final String APPEARANCE_METHOD_RETURNTYPE= "org.eclipse.jdt.ui.methodreturntype";//$NON-NLS-1$ /** * A named preference that controls if override indicators are rendered in the UI. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> override * indicators are rendered * </p> * @deprecated Override Indicator is now controlled on the platform's decorator preference page */ public static final String APPEARANCE_OVERRIDE_INDICATOR= "org.eclipse.jdt.ui.overrideindicator";//$NON-NLS-1$ /** * A named preference that controls if quick assist light bulbs are shown. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> light bulbs are shown * for quick assists. * </p> * * @since 3.0 */ public static final String EDITOR_QUICKASSIST_LIGHTBULB="org.eclipse.jdt.quickassist.lightbulb"; //$NON-NLS-1$ /** * A named preference that defines the pattern used for package name compression. * <p> * Value is of type <code>String</code>. For example foe the given package name 'org.eclipse.jdt' pattern * '.' will compress it to '..jdt', '1~' to 'o~.e~.jdt'. * </p> */ public static final String APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW= "PackagesView.pkgNamePatternForPackagesView";//$NON-NLS-1$ /** * A named preference that controls if package name compression is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * * @see #APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW */ public static final String APPEARANCE_COMPRESS_PACKAGE_NAMES= "org.eclipse.jdt.ui.compresspackagenames";//$NON-NLS-1$ /** * A named preference that controls if empty inner packages are folded in * the hierarchical mode of the package explorer. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> empty * inner packages are folded. * </p> * @since 2.1 */ public static final String APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER= "org.eclipse.jdt.ui.flatPackagesInPackageExplorer";//$NON-NLS-1$ /** * A named preference that defines how member elements are ordered by the * Java views using the <code>JavaElementSorter</code>. * <p> * Value is of type <code>String</code>: A comma separated list of the * following entries. Each entry must be in the list, no duplication. List * order defines the sort order. * <ul> * <li><b>T</b>: Types</li> * <li><b>C</b>: Constructors</li> * <li><b>I</b>: Initializers</li> * <li><b>M</b>: Methods</li> * <li><b>F</b>: Fields</li> * <li><b>SI</b>: Static Initializers</li> * <li><b>SM</b>: Static Methods</li> * <li><b>SF</b>: Static Fields</li> * </ul> * </p> * @since 2.1 */ public static final String APPEARANCE_MEMBER_SORT_ORDER= "outlinesortoption"; //$NON-NLS-1$ /** * A named preference that defines how member elements are ordered by visibility in the * Java views using the <code>JavaElementSorter</code>. * <p> * Value is of type <code>String</code>: A comma separated list of the * following entries. Each entry must be in the list, no duplication. List * order defines the sort order. * <ul> * <li><b>B</b>: Public</li> * <li><b>V</b>: Private</li> * <li><b>R</b>: Protected</li> * <li><b>D</b>: Default</li> * </ul> * </p> * @since 3.0 */ public static final String APPEARANCE_VISIBILITY_SORT_ORDER= "org.eclipse.jdt.ui.visibility.order"; //$NON-NLS-1$ /** * A named preferences that controls if java elements are also sorted by * visibility. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 3.0 */ public static final String APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER= "org.eclipse.jdt.ui.enable.visibility.order"; //$NON-NLS-1$ /** * A named preference that controls if prefix removal during setter/getter generation is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated Use JavaCore preference store (key JavaCore. * CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES) */ public static final String CODEGEN_USE_GETTERSETTER_PREFIX= "org.eclipse.jdt.ui.gettersetter.prefix.enable";//$NON-NLS-1$ /** * A named preference that holds a list of prefixes to be removed from a local variable to compute setter * and getter names. * <p> * Value is of type <code>String</code>: comma separated list of prefixed * </p> * * @deprecated Use JavaCore preference store (key JavaCore. * CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES) */ public static final String CODEGEN_GETTERSETTER_PREFIX= "org.eclipse.jdt.ui.gettersetter.prefix.list";//$NON-NLS-1$ /** * A named preference that controls if suffix removal during setter/getter generation is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated Use JavaCore preference store (key JavaCore. * CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES) */ public static final String CODEGEN_USE_GETTERSETTER_SUFFIX= "org.eclipse.jdt.ui.gettersetter.suffix.enable";//$NON-NLS-1$ /** * A named preference that holds a list of suffixes to be removed from a local variable to compute setter * and getter names. * <p> * Value is of type <code>String</code>: comma separated list of suffixes * </p> * @deprecated Use setting from JavaCore preference store (key JavaCore. * CODEASSIST_FIELD_SUFFIXES and CODEASSIST_STATIC_FIELD_SUFFIXES) */ public static final String CODEGEN_GETTERSETTER_SUFFIX= "org.eclipse.jdt.ui.gettersetter.suffix.list"; //$NON-NLS-1$ /** * A named preference that controls whether the keyword "this" will be added * automatically to field accesses in generated methods. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 3.0 */ public static final String CODEGEN_KEYWORD_THIS= "org.eclipse.jdt.ui.keywordthis"; //$NON-NLS-1$ /** * A named preference that controls whether to use the prefix "is" or the prefix "get" for * automatically created getters which return a boolean field. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 3.0 */ public static final String CODEGEN_IS_FOR_GETTERS= "org.eclipse.jdt.ui.gettersetter.use.is"; //$NON-NLS-1$ /** * A named preference that defines the preferred variable names for exceptions in * catch clauses. * <p> * Value is of type <code>String</code>. * </p> * @since 3.0 */ public static final String CODEGEN_EXCEPTION_VAR_NAME= "org.eclipse.jdt.ui.exception.name"; //$NON-NLS-1$ /** * A named preference that controls if comment stubs will be added * automatically to newly created types and methods. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String CODEGEN_ADD_COMMENTS= "org.eclipse.jdt.ui.javadoc"; //$NON-NLS-1$ /** * A named preference that controls if a comment stubs will be added * automatically to newly created types and methods. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated Use CODEGEN_ADD_COMMENTS instead (Name is more precise). */ public static final String CODEGEN__JAVADOC_STUBS= CODEGEN_ADD_COMMENTS; /** * A named preference that controls if a non-javadoc comment gets added to methods generated via the * "Override Methods" operation. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated New code template story: user can * specify the overriding method comment. */ public static final String CODEGEN__NON_JAVADOC_COMMENTS= "org.eclipse.jdt.ui.seecomments"; //$NON-NLS-1$ /** * A named preference that controls if a file comment gets added to newly created files. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated New code template story: user can * specify the new type code template. */ public static final String CODEGEN__FILE_COMMENTS= "org.eclipse.jdt.ui.filecomments"; //$NON-NLS-1$ /** * A named preference that holds a list of semicolon separated package names. The list specifies the import order used by * the "Organize Imports" operation. * <p> * Value is of type <code>String</code>: semicolon separated list of package * names * </p> */ public static final String ORGIMPORTS_IMPORTORDER= "org.eclipse.jdt.ui.importorder"; //$NON-NLS-1$ /** * A named preference that holds a list of semicolon separated fully qualified type names with wild card characters. * @since 3.0 */ public static final String TYPEFILTER_ENABLED= "org.eclipse.jdt.ui.typefilter.enabled"; //$NON-NLS-1$ /** * A named preference that holds a list of semicolon separated fully qualified type names with wild card characters. * @since 3.0 */ public static final String TYPEFILTER_DISABLED= "org.eclipse.jdt.ui.typefilter.disabled"; //$NON-NLS-1$ /** * A named preference that specifies the number of imports added before a star-import declaration is used. * <p> * Value is of type <code>Integer</code>: positive value specifying the number of non star-import is used * </p> */ public static final String ORGIMPORTS_ONDEMANDTHRESHOLD= "org.eclipse.jdt.ui.ondemandthreshold"; //$NON-NLS-1$ /** * A named preferences that controls if types that start with a lower case letters get added by the * "Organize Import" operation. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String ORGIMPORTS_IGNORELOWERCASE= "org.eclipse.jdt.ui.ignorelowercasenames"; //$NON-NLS-1$ /** * A named preference that speficies whether children of a compilation unit are shown in the package explorer. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String SHOW_CU_CHILDREN= "org.eclipse.jdt.ui.packages.cuchildren"; //$NON-NLS-1$ /** * A named preference that controls whether the package explorer's selection is linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String LINK_PACKAGES_TO_EDITOR= "org.eclipse.jdt.ui.packages.linktoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the hierarchy view's selection is linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String LINK_TYPEHIERARCHY_TO_EDITOR= "org.eclipse.jdt.ui.packages.linktypehierarchytoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the projects view's selection is * linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String LINK_BROWSING_PROJECTS_TO_EDITOR= "org.eclipse.jdt.ui.browsing.projectstoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the packages view's selection is * linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String LINK_BROWSING_PACKAGES_TO_EDITOR= "org.eclipse.jdt.ui.browsing.packagestoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the types view's selection is * linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String LINK_BROWSING_TYPES_TO_EDITOR= "org.eclipse.jdt.ui.browsing.typestoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the members view's selection is * linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String LINK_BROWSING_MEMBERS_TO_EDITOR= "org.eclipse.jdt.ui.browsing.memberstoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether new projects are generated using source and output folder. * <p> * Value is of type <code>Boolean</code>. if <code>true</code> new projects are created with a source and * output folder. If <code>false</code> source and output folder equals to the project. * </p> */ public static final String SRCBIN_FOLDERS_IN_NEWPROJ= "org.eclipse.jdt.ui.wizards.srcBinFoldersInNewProjects"; //$NON-NLS-1$ /** * A named preference that specifies the source folder name used when creating a new Java project. Value is inactive * if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>. * <p> * Value is of type <code>String</code>. * </p> * * @see #SRCBIN_FOLDERS_IN_NEWPROJ */ public static final String SRCBIN_SRCNAME= "org.eclipse.jdt.ui.wizards.srcBinFoldersSrcName"; //$NON-NLS-1$ /** * A named preference that specifies the output folder name used when creating a new Java project. Value is inactive * if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>. * <p> * Value is of type <code>String</code>. * </p> * * @see #SRCBIN_FOLDERS_IN_NEWPROJ */ public static final String SRCBIN_BINNAME= "org.eclipse.jdt.ui.wizards.srcBinFoldersBinName"; //$NON-NLS-1$ /** * A named preference that holds a list of possible JRE libraries used by the New Java Project wizard. An library * consists of a description and an arbitrary number of <code>IClasspathEntry</code>s, that will represent the * JRE on the new project's classpath. * <p> * Value is of type <code>String</code>: a semicolon separated list of encoded JRE libraries. * <code>NEWPROJECT_JRELIBRARY_INDEX</code> defines the currently used library. Clients * should use the method <code>encodeJRELibrary</code> to encode a JRE library into a string * and the methods <code>decodeJRELibraryDescription(String)</code> and <code> * decodeJRELibraryClasspathEntries(String)</code> to decode the description and the array * of classpath entries from an encoded string. * </p> * * @see #NEWPROJECT_JRELIBRARY_INDEX * @see #encodeJRELibrary(String, IClasspathEntry[]) * @see #decodeJRELibraryDescription(String) * @see #decodeJRELibraryClasspathEntries(String) */ public static final String NEWPROJECT_JRELIBRARY_LIST= "org.eclipse.jdt.ui.wizards.jre.list"; //$NON-NLS-1$ /** * A named preferences that specifies the current active JRE library. * <p> * Value is of type <code>Integer</code>: an index into the list of possible JRE libraries. * </p> * * @see #NEWPROJECT_JRELIBRARY_LIST */ public static final String NEWPROJECT_JRELIBRARY_INDEX= "org.eclipse.jdt.ui.wizards.jre.index"; //$NON-NLS-1$ /** * A named preference that controls if a new type hierarchy gets opened in a * new type hierarchy perspective or inside the type hierarchy view part. * <p> * Value is of type <code>String</code>: possible values are <code> * OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE</code> or <code> * OPEN_TYPE_HIERARCHY_IN_VIEW_PART</code>. * </p> * * @see #OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE * @see #OPEN_TYPE_HIERARCHY_IN_VIEW_PART */ public static final String OPEN_TYPE_HIERARCHY= "org.eclipse.jdt.ui.openTypeHierarchy"; //$NON-NLS-1$ /** * A string value used by the named preference <code>OPEN_TYPE_HIERARCHY</code>. * * @see #OPEN_TYPE_HIERARCHY */ public static final String OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE= "perspective"; //$NON-NLS-1$ /** * A string value used by the named preference <code>OPEN_TYPE_HIERARCHY</code>. * * @see #OPEN_TYPE_HIERARCHY */ public static final String OPEN_TYPE_HIERARCHY_IN_VIEW_PART= "viewPart"; //$NON-NLS-1$ /** * A named preference that controls the behavior when double clicking on a container in the packages view. * <p> * Value is of type <code>String</code>: possible values are <code> * DOUBLE_CLICK_GOES_INTO</code> or <code> * DOUBLE_CLICK_EXPANDS</code>. * </p> * * @see #DOUBLE_CLICK_EXPANDS * @see #DOUBLE_CLICK_GOES_INTO */ public static final String DOUBLE_CLICK= "packageview.doubleclick"; //$NON-NLS-1$ /** * A string value used by the named preference <code>DOUBLE_CLICK</code>. * * @see #DOUBLE_CLICK */ public static final String DOUBLE_CLICK_GOES_INTO= "packageview.gointo"; //$NON-NLS-1$ /** * A string value used by the named preference <code>DOUBLE_CLICK</code>. * * @see #DOUBLE_CLICK */ public static final String DOUBLE_CLICK_EXPANDS= "packageview.doubleclick.expands"; //$NON-NLS-1$ /** * A named preference that controls whether Java views update their presentation while editing or when saving the * content of an editor. * <p> * Value is of type <code>String</code>: possible values are <code> * UPDATE_ON_SAVE</code> or <code> * UPDATE_WHILE_EDITING</code>. * </p> * * @see #UPDATE_ON_SAVE * @see #UPDATE_WHILE_EDITING * @deprecated Since 3.0, views now always update while editing */ public static final String UPDATE_JAVA_VIEWS= "JavaUI.update"; //$NON-NLS-1$ /** * A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code> * * @see #UPDATE_JAVA_VIEWS * @deprecated Since 3.0, views now always update while editing */ public static final String UPDATE_ON_SAVE= "JavaUI.update.onSave"; //$NON-NLS-1$ /** * A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code> * * @see #UPDATE_JAVA_VIEWS * @deprecated Since 3.0, views now always update while editing */ public static final String UPDATE_WHILE_EDITING= "JavaUI.update.whileEditing"; //$NON-NLS-1$ /** * A named preference that holds the path of the Javadoc command used by the Javadoc creation wizard. * <p> * Value is of type <code>String</code>. * </p> */ public static final String JAVADOC_COMMAND= "command"; //$NON-NLS-1$ /** * A named preference that defines whether hint to make hover sticky should be shown. * * @see JavaUI * @since 3.0 */ public static final String EDITOR_SHOW_TEXT_HOVER_AFFORDANCE= "PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE"; //$NON-NLS-1$ /** * A named preference that defines the key for the hover modifiers. * * @see JavaUI * @since 2.1 */ public static final String EDITOR_TEXT_HOVER_MODIFIERS= "hoverModifiers"; //$NON-NLS-1$ /** * A named preference that defines the key for the hover modifier state masks. * The value is only used if the value of <code>EDITOR_TEXT_HOVER_MODIFIERS</code> * cannot be resolved to valid SWT modifier bits. * * @see JavaUI * @see #EDITOR_TEXT_HOVER_MODIFIERS * @since 2.1.1 */ public static final String EDITOR_TEXT_HOVER_MODIFIER_MASKS= "hoverModifierMasks"; //$NON-NLS-1$ /** * The id of the best match hover contributed for extension point * <code>javaEditorTextHovers</code>. * * @since 2.1 */ public static final String ID_BESTMATCH_HOVER= "org.eclipse.jdt.ui.BestMatchHover"; //$NON-NLS-1$ /** * The id of the source code hover contributed for extension point * <code>javaEditorTextHovers</code>. * * @since 2.1 */ public static final String ID_SOURCE_HOVER= "org.eclipse.jdt.ui.JavaSourceHover"; //$NON-NLS-1$ /** * The id of the javadoc hover contributed for extension point * <code>javaEditorTextHovers</code>. * * @since 2.1 */ public static final String ID_JAVADOC_HOVER= "org.eclipse.jdt.ui.JavadocHover"; //$NON-NLS-1$ /** * The id of the problem hover contributed for extension point * <code>javaEditorTextHovers</code>. * * @since 2.1 * @deprecated as of 3.0, this hover is no longer available */ public static final String ID_PROBLEM_HOVER= "org.eclipse.jdt.ui.ProblemHover"; //$NON-NLS-1$ /** * A named preference that controls whether bracket matching highlighting is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_MATCHING_BRACKETS= "matchingBrackets"; //$NON-NLS-1$ /** * A named preference that holds the color used to highlight matching brackets. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_MATCHING_BRACKETS_COLOR= "matchingBracketsColor"; //$NON-NLS-1$ /** * A named preference that controls whether the current line highlighting is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants} */ public final static String EDITOR_CURRENT_LINE= "currentLine"; //$NON-NLS-1$ /** * A named preference that holds the color used to highlight the current line. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants} */ public final static String EDITOR_CURRENT_LINE_COLOR= "currentLineColor"; //$NON-NLS-1$ /** * A named preference that controls whether the print margin is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants} */ public final static String EDITOR_PRINT_MARGIN= "printMargin"; //$NON-NLS-1$ /** * A named preference that holds the color used to render the print margin. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants} */ public final static String EDITOR_PRINT_MARGIN_COLOR= "printMarginColor"; //$NON-NLS-1$ /** * Print margin column. Integer value. * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants} */ public final static String EDITOR_PRINT_MARGIN_COLUMN= "printMarginColumn"; //$NON-NLS-1$ /** * A named preference that holds the color used for the find/replace scope. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_FIND_SCOPE_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE; /** * A named preference that specifies if the editor uses spaces for tabs. * <p> * Value is of type <code>Boolean</code>. If <code>true</code>spaces instead of tabs are used * in the editor. If <code>false</code> the editor inserts a tab character when pressing the tab * key. * </p> */ public final static String EDITOR_SPACES_FOR_TABS= "spacesForTabs"; //$NON-NLS-1$ /** * A named preference that holds the number of spaces used per tab in the editor. * <p> * Value is of type <code>Integer</code>: positive integer value specifying the number of * spaces per tab. * </p> * @deprecated As of 3.0 replaced by {@link AbstractDecoratedTextEditorPreferenceConstants#EDITOR_TAB_WIDTH} */ public final static String EDITOR_TAB_WIDTH= "org.eclipse.jdt.ui.editor.tab.width"; //$NON-NLS-1$ /** * A named preference that controls whether the outline view selection * should stay in sync with with the element at the current cursor position. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE= "JavaEditor.SyncOutlineOnCursorMove"; //$NON-NLS-1$ /** * A named preference that controls if correction indicators are shown in the UI. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_CORRECTION_INDICATION= "JavaEditor.ShowTemporaryProblem"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows problem indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_PROBLEM_INDICATION= "problemIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render problem indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_PROBLEM_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_PROBLEM_INDICATION_COLOR= "problemIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows warning indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_WARNING_INDICATION= "warningIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render warning indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_WARNING_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_WARNING_INDICATION_COLOR= "warningIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows task indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_TASK_INDICATION= "taskIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render task indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_TASK_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_TASK_INDICATION_COLOR= "taskIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows bookmark * indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_BOOKMARK_INDICATION= "bookmarkIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render bookmark indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_BOOKMARK_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_BOOKMARK_INDICATION_COLOR= "bookmarkIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows search * indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_SEARCH_RESULT_INDICATION= "searchResultIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render search indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_SEARCH_RESULT_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_SEARCH_RESULT_INDICATION_COLOR= "searchResultIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows unknown * indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_UNKNOWN_INDICATION= "othersIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render unknown * indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_UNKNOWN_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 * @deprecated * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_UNKNOWN_INDICATION_COLOR= "othersIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows error * indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER= "errorIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows warning * indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER= "warningIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows task * indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER= "taskIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows * bookmark indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER= "bookmarkIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows * search result indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER= "searchResultIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows * unknown indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER= "othersIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close strings' feature * is enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_STRINGS= "closeStrings"; //$NON-NLS-1$ /** * A named preference that controls whether the 'wrap strings' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_WRAP_STRINGS= "wrapStrings"; //$NON-NLS-1$ /** * A named preference that controls whether the 'escape strings' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 3.0 */ public final static String EDITOR_ESCAPE_STRINGS= "escapeStrings"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close brackets' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_BRACKETS= "closeBrackets"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close braces' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_BRACES= "closeBraces"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close java docs' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_JAVADOCS= "closeJavaDocs"; //$NON-NLS-1$ /** * A named preference that controls whether the 'add JavaDoc tags' feature * is enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_ADD_JAVADOC_TAGS= "addJavaDocTags"; //$NON-NLS-1$ /** * A named preference that controls whether the 'format Javadoc tags' * feature is enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_FORMAT_JAVADOCS= "autoFormatJavaDocs"; //$NON-NLS-1$ /** * A named preference that controls whether the 'smart paste' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SMART_PASTE= "smartPaste"; //$NON-NLS-1$ /** * A named preference that controls whether 'paste' should update the imports * <p> * Value is of type <code>Boolean</code>. * </p> * @since 3.0 */ public final static String EDITOR_IMPORTS_ON_PASTE= "importsOnPaste"; //$NON-NLS-1$ /** * A named preference that controls whether the 'smart home-end' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SMART_HOME_END= AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END; /** * A named preference that controls whether the 'sub-word navigation' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 3.0 */ public final static String EDITOR_SUB_WORD_NAVIGATION= "subWordNavigation"; //$NON-NLS-1$ /** * A named preference that controls if temporary problems are evaluated and shown in the UI. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_EVALUTE_TEMPORARY_PROBLEMS= "handleTemporaryProblems"; //$NON-NLS-1$ /** * A named preference that controls if the overview ruler is shown in the UI. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants} */ public final static String EDITOR_OVERVIEW_RULER= "overviewRuler"; //$NON-NLS-1$ /** * A named preference that controls if the line number ruler is shown in the UI. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants} */ public final static String EDITOR_LINE_NUMBER_RULER= "lineNumberRuler"; //$NON-NLS-1$ /** * A named preference that holds the color used to render line numbers inside the line number ruler. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @see #EDITOR_LINE_NUMBER_RULER * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants} */ public final static String EDITOR_LINE_NUMBER_RULER_COLOR= "lineNumberColor"; //$NON-NLS-1$ /** * A named preference that holds the color used to render linked positions inside code templates. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @deprecated not used any longer as the linked positions are displayed as annotations * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_LINKED_POSITION_COLOR= "linkedPositionColor"; //$NON-NLS-1$ /** * A named preference that holds the color used as the text foreground. * This value has not effect if the system default color is used. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_FOREGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND; /** * A named preference that describes if the system default foreground color * is used as the text foreground. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_FOREGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT; /** * A named preference that holds the color used as the text background. * This value has not effect if the system default color is used. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_BACKGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND; /** * A named preference that describes if the system default background color * is used as the text background. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_BACKGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT; /** * Preference key suffix for bold text style preference keys. * * @since 2.1 */ public static final String EDITOR_BOLD_SUFFIX= "_bold"; //$NON-NLS-1$ /** * Preference key suffix for italic text style preference keys. * * @since 3.0 */ public static final String EDITOR_ITALIC_SUFFIX= "_italic"; //$NON-NLS-1$ /** * A named preference that holds the color used to render multi line comments. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_MULTI_LINE_COMMENT_COLOR= IJavaColorConstants.JAVA_MULTI_LINE_COMMENT; /** * The symbolic font name for the Java editor text font * (value <code>"org.eclipse.jdt.ui.editors.textfont"</code>). * * @since 2.1 */ public final static String EDITOR_TEXT_FONT= "org.eclipse.jdt.ui.editors.textfont"; //$NON-NLS-1$ /** * A named preference that controls whether multi line comments are rendered in bold. * <p> * Value is of type <code>Boolean</code>. If <code>true</code> multi line comments are rendered * in bold. If <code>false</code> the are rendered using no font style attribute. * </p> */ public final static String EDITOR_MULTI_LINE_COMMENT_BOLD= IJavaColorConstants.JAVA_MULTI_LINE_COMMENT + EDITOR_BOLD_SUFFIX; /** * A named preference that controls whether multi line comments are rendered in italic. * <p> * Value is of type <code>Boolean</code>. If <code>true</code> multi line comments are rendered * in italic. If <code>false</code> the are rendered using no italic font style attribute. * </p> * * @since 3.0 */ public final static String EDITOR_MULTI_LINE_COMMENT_ITALIC= IJavaColorConstants.JAVA_MULTI_LINE_COMMENT + EDITOR_ITALIC_SUFFIX; /** * A named preference that holds the color used to render single line comments. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_SINGLE_LINE_COMMENT_COLOR= IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT; /** * A named preference that controls whether single line comments are rendered in bold. * <p> * Value is of type <code>Boolean</code>. If <code>true</code> single line comments are rendered * in bold. If <code>false</code> the are rendered using no font style attribute. * </p> */ public final static String EDITOR_SINGLE_LINE_COMMENT_BOLD= IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT + EDITOR_BOLD_SUFFIX; /** * A named preference that controls whether single line comments are rendered in italic. * <p> * Value is of type <code>Boolean</code>. If <code>true</code> single line comments are rendered * in italic. If <code>false</code> the are rendered using no italic font style attribute. * </p> * * @since 3.0 */ public final static String EDITOR_SINGLE_LINE_COMMENT_ITALIC= IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT + EDITOR_ITALIC_SUFFIX; /** * A named preference that holds the color used to render java keywords. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVA_KEYWORD_COLOR= IJavaColorConstants.JAVA_KEYWORD; /** * A named preference that controls whether keywords are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVA_KEYWORD_BOLD= IJavaColorConstants.JAVA_KEYWORD + EDITOR_BOLD_SUFFIX; /** * A named preference that controls whether keywords are rendered in italic. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_JAVA_KEYWORD_ITALIC= IJavaColorConstants.JAVA_KEYWORD + EDITOR_ITALIC_SUFFIX; /** * A named preference that holds the color used to render string constants. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_STRING_COLOR= IJavaColorConstants.JAVA_STRING; /** * A named preference that controls whether string constants are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_STRING_BOLD= IJavaColorConstants.JAVA_STRING + EDITOR_BOLD_SUFFIX; /** * A named preference that controls whether string constants are rendered in italic. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_STRING_ITALIC= IJavaColorConstants.JAVA_STRING + EDITOR_ITALIC_SUFFIX; /** * A named preference that holds the color used to render method names. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 3.0 */ public final static String EDITOR_JAVA_METHOD_NAME_COLOR= IJavaColorConstants.JAVA_METHOD_NAME; /** * A named preference that controls whether method names are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_JAVA_METHOD_NAME_BOLD= IJavaColorConstants.JAVA_METHOD_NAME + EDITOR_BOLD_SUFFIX; /** * A named preference that controls whether method names are rendered in italic. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_JAVA_METHOD_NAME_ITALIC= IJavaColorConstants.JAVA_METHOD_NAME + EDITOR_ITALIC_SUFFIX; /** * A named preference that holds the color used to render the 'return' keyword. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 3.0 */ public final static String EDITOR_JAVA_KEYWORD_RETURN_COLOR= IJavaColorConstants.JAVA_KEYWORD_RETURN; /** * A named preference that controls whether 'return' keyword is rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_JAVA_KEYWORD_RETURN_BOLD= IJavaColorConstants.JAVA_KEYWORD_RETURN + EDITOR_BOLD_SUFFIX; /** * A named preference that controls whether 'return' keyword is rendered in italic. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_JAVA_KEYWORD_RETURN_ITALIC= IJavaColorConstants.JAVA_KEYWORD_RETURN + EDITOR_ITALIC_SUFFIX; /** * A named preference that holds the color used to render operators and brackets. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 3.0 */ public final static String EDITOR_JAVA_OPERATOR_COLOR= IJavaColorConstants.JAVA_OPERATOR; /** * A named preference that controls whether operators and brackets are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_JAVA_OPERATOR_BOLD= IJavaColorConstants.JAVA_OPERATOR + EDITOR_BOLD_SUFFIX; /** * A named preference that controls whether operators and brackets are rendered in italic. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_JAVA_OPERATOR_ITALIC= IJavaColorConstants.JAVA_OPERATOR + EDITOR_ITALIC_SUFFIX; /** * A named preference that holds the color used to render java default text. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVA_DEFAULT_COLOR= IJavaColorConstants.JAVA_DEFAULT; /** * A named preference that controls whether Java default text is rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVA_DEFAULT_BOLD= IJavaColorConstants.JAVA_DEFAULT + EDITOR_BOLD_SUFFIX; /** * A named preference that controls whether Java default text is rendered in italic. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_JAVA_DEFAULT_ITALIC= IJavaColorConstants.JAVA_DEFAULT + EDITOR_ITALIC_SUFFIX; /** * A named preference that holds the color used to render task tags. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String EDITOR_TASK_TAG_COLOR= IJavaColorConstants.TASK_TAG; /** * A named preference that controls whether task tags are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_TASK_TAG_BOLD= IJavaColorConstants.TASK_TAG + EDITOR_BOLD_SUFFIX; /** * A named preference that controls whether task tags are rendered in italic. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_TASK_TAG_ITALIC= IJavaColorConstants.TASK_TAG + EDITOR_ITALIC_SUFFIX; /** * A named preference that holds the color used to render javadoc keywords. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_KEYWORD_COLOR= IJavaColorConstants.JAVADOC_KEYWORD; /** * A named preference that controls whether javadoc keywords are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_KEYWORD_BOLD= IJavaColorConstants.JAVADOC_KEYWORD + EDITOR_BOLD_SUFFIX; /** * A named preference that controls whether javadoc keywords are rendered in italic. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_JAVADOC_KEYWORD_ITALIC= IJavaColorConstants.JAVADOC_KEYWORD + EDITOR_ITALIC_SUFFIX; /** * A named preference that holds the color used to render javadoc tags. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_TAG_COLOR= IJavaColorConstants.JAVADOC_TAG; /** * A named preference that controls whether javadoc tags are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_TAG_BOLD= IJavaColorConstants.JAVADOC_TAG + EDITOR_BOLD_SUFFIX; /** * A named preference that controls whether javadoc tags are rendered in italic. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_JAVADOC_TAG_ITALIC= IJavaColorConstants.JAVADOC_TAG + EDITOR_ITALIC_SUFFIX; /** * A named preference that holds the color used to render javadoc links. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_LINKS_COLOR= IJavaColorConstants.JAVADOC_LINK; /** * A named preference that controls whether javadoc links are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_LINKS_BOLD= IJavaColorConstants.JAVADOC_LINK + EDITOR_BOLD_SUFFIX; /** * A named preference that controls whether javadoc links are rendered in italic. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_JAVADOC_LINKS_ITALIC= IJavaColorConstants.JAVADOC_LINK + EDITOR_ITALIC_SUFFIX; /** * A named preference that holds the color used to render javadoc default text. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_DEFAULT_COLOR= IJavaColorConstants.JAVADOC_DEFAULT; /** * A named preference that controls whether javadoc default text is rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_DEFAULT_BOLD= IJavaColorConstants.JAVADOC_DEFAULT + EDITOR_BOLD_SUFFIX; /** * A named preference that controls whether javadoc default text is rendered in italic. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_JAVADOC_DEFAULT_ITALIC= IJavaColorConstants.JAVADOC_DEFAULT + EDITOR_ITALIC_SUFFIX; /** * A named preference that holds the color used for 'linked-mode' underline. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String EDITOR_LINK_COLOR= "linkColor"; //$NON-NLS-1$ /** * A named preference that controls whether hover tooltips in the editor are turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String EDITOR_SHOW_HOVER= "org.eclipse.jdt.ui.editor.showHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when no control key is * pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a hover * contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} */ public static final String EDITOR_NONE_HOVER= "noneHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL</code> modifier key is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} */ public static final String EDITOR_CTRL_HOVER= "ctrlHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>SHIFT</code> modifier key is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} */ public static final String EDITOR_SHIFT_HOVER= "shiftHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL + ALT</code> modifier keys is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 */ public static final String EDITOR_CTRL_ALT_HOVER= "ctrlAltHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL + ALT + SHIFT</code> modifier keys is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 */ public static final String EDITOR_CTRL_ALT_SHIFT_HOVER= "ctrlAltShiftHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL + SHIFT</code> modifier keys is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 * @deprecated Will be removed in one of the next builds. */ public static final String EDITOR_CTRL_SHIFT_HOVER= "ctrlShiftHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>ALT</code> modifier key is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code>, * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} * @since 2.1 */ public static final String EDITOR_ALT_SHIFT_HOVER= "altShiftHover"; //$NON-NLS-1$ /** * A string value used by the named preferences for hover configuration to * describe that no hover should be shown for the given key modifiers. * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} * @since 2.1 */ public static final String EDITOR_NO_HOVER_CONFIGURED_ID= "noHoverConfiguredId"; //$NON-NLS-1$ /** * A string value used by the named preferences for hover configuration to * describe that the default hover should be shown for the given key * modifiers. The default hover is described by the * <code>EDITOR_DEFAULT_HOVER</code> property. * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} */ public static final String EDITOR_DEFAULT_HOVER_CONFIGURED_ID= "defaultHoverConfiguredId"; //$NON-NLS-1$ /** * A named preference that defines the hover named the 'default hover'. * Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or <code> the hover id of a hover * contributed as <code>javaEditorTextHovers</code>. * </p> * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} */ public static final String EDITOR_DEFAULT_HOVER= "defaultHover"; //$NON-NLS-1$ /** * A named preference that controls if segmented view (show selected element only) is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String EDITOR_SHOW_SEGMENTS= "org.eclipse.jdt.ui.editor.showSegments"; //$NON-NLS-1$ /** * A named preference that controls if browser like links are turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 2.1 */ public static final String EDITOR_BROWSER_LIKE_LINKS= "browserLikeLinks"; //$NON-NLS-1$ /** * A named preference that controls the key modifier for browser like links. * <p> * Value is of type <code>String</code>. * </p> * * @since 2.1 */ public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER= "browserLikeLinksKeyModifier"; //$NON-NLS-1$ /** * A named preference that controls the key modifier mask for browser like links. * The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code> * cannot be resolved to valid SWT modifier bits. * <p> * Value is of type <code>String</code>. * </p> * * @see #EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER * @since 2.1.1 */ public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= "browserLikeLinksKeyModifierMask"; //$NON-NLS-1$ /** * A named preference that controls whether occurrences are marked in the editor. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_MARK_OCCURRENCES= "markOccurrences"; //$NON-NLS-1$ /** * A named preference that controls whether occurrences are sticky in the editor. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_STICKY_OCCURRENCES= "stickyOccurrences"; //$NON-NLS-1$ /** * A named preference that controls whether type occurrences are marked. * Only valid if {@link #EDITOR_MARK_OCCURRENCES} is <code>true</code>. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_MARK_TYPE_OCCURRENCES= "markTypeOccurrences"; //$NON-NLS-1$ /** * A named preference that controls whether method occurrences are marked. * Only valid if {@link #EDITOR_MARK_OCCURRENCES} is <code>true</code>. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_MARK_METHOD_OCCURRENCES= "markMethodOccurrences"; //$NON-NLS-1$ /** * A named preference that controls whether non-constant field occurrences are marked. * Only valid if {@link #EDITOR_MARK_OCCURRENCES} is <code>true</code>. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_MARK_FIELD_OCCURRENCES= "markFieldOccurrences"; //$NON-NLS-1$ /** * A named preference that controls whether constant (static final) occurrences are marked. * Only valid if {@link #EDITOR_MARK_OCCURRENCES} is <code>true</code>. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_MARK_CONSTANT_OCCURRENCES= "markConstantOccurrences"; //$NON-NLS-1$ /** * A named preference that controls whether local variable occurrences are marked. * Only valid if {@link #EDITOR_MARK_OCCURRENCES} is <code>true</code>. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES= "markLocalVariableOccurrences"; //$NON-NLS-1$ /** * A named preference that controls whether exception occurrences are marked. * Only valid if {@link #EDITOR_MARK_OCCURRENCES} is <code>true</code>. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_MARK_EXCEPTION_OCCURRENCES= "markExceptionOccurrences"; //$NON-NLS-1$ /** * A named preference that controls whether method exit points are marked. * Only valid if {@link #EDITOR_MARK_OCCURRENCES} is <code>true</code>. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_MARK_METHOD_EXIT_POINTS= "markMethodExitPoints"; //$NON-NLS-1$ /** * A named preference prefix for semantic highlighting preferences. * * @since 3.0 */ public static final String EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX="semanticHighlighting."; //$NON-NLS-1$ /** * A named preference that controls if semantic highlighting is enabled. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> is enabled. * </p> * * @since 3.0 */ public static final String EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED=EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + "enabled"; //$NON-NLS-1$ /** * A named preference suffix that controls a semantic highlighting's color. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 3.0 */ public static final String EDITOR_SEMANTIC_HIGHLIGHTING_COLOR_SUFFIX=".color"; //$NON-NLS-1$ /** * A named preference suffix that controls if semantic highlighting has the text attribute bold. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> is enabled. * </p> * * @since 3.0 */ public static final String EDITOR_SEMANTIC_HIGHLIGHTING_BOLD_SUFFIX=".bold"; //$NON-NLS-1$ /** * A named preference suffix that controls if semantic highlighting has the text attribute bold. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> is enabled. * </p> * * @since 3.0 */ public static final String EDITOR_SEMANTIC_HIGHLIGHTING_ITALIC_SUFFIX=".italic"; //$NON-NLS-1$ /** * A named preference that controls disabling of the overwrite mode. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_DISABLE_OVERWRITE_MODE= "disable_overwrite_mode"; //$NON-NLS-1$ /** * A named preference that controls the "smart semicolon" smart typing handler * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_SMART_SEMICOLON= "smart_semicolon"; //$NON-NLS-1$ /** * A named preference that controls the smart backspace behavior. * <p> * Value is of type <code>Boolean</code>. * * @since 3.0 */ public static final String EDITOR_SMART_BACKSPACE= "smart_backspace"; //$NON-NLS-1$ /** * A named preference that controls the "smart opening brace" smart typing handler * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_SMART_OPENING_BRACE= "smart_opening_brace"; //$NON-NLS-1$ /** * A named preference that controls the smart tab behavior. * <p> * Value is of type <code>Boolean</code>. * * @since 3.0 */ public static final String EDITOR_SMART_TAB= "smart_tab"; //$NON-NLS-1$ /** * A named preference that controls whether Java comments should be * spell-checked. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String SPELLING_CHECK_SPELLING= ISpellCheckPreferenceKeys.SPELLING_CHECK_SPELLING; /** * A named preference that controls whether words containing digits should * be skipped during spell-checking. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String SPELLING_IGNORE_DIGITS= ISpellCheckPreferenceKeys.SPELLING_IGNORE_DIGITS; /** * A named preference that controls whether mixed case words should be * skipped during spell-checking. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String SPELLING_IGNORE_MIXED= ISpellCheckPreferenceKeys.SPELLING_IGNORE_MIXED; /** * A named preference that controls whether sentence capitalization should * be ignored during spell-checking. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String SPELLING_IGNORE_SENTENCE= ISpellCheckPreferenceKeys.SPELLING_IGNORE_SENTENCE; /** * A named preference that controls whether upper case words should be * skipped during spell-checking. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String SPELLING_IGNORE_UPPER= ISpellCheckPreferenceKeys.SPELLING_IGNORE_UPPER; /** * A named preference that controls whether URLs should be ignored during * spell-checking. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String SPELLING_IGNORE_URLS= ISpellCheckPreferenceKeys.SPELLING_IGNORE_URLS; /** * A named preference that controls the locale used for spell-checking. * <p> * Value is of type <code>String</code>. * </p> * * @since 3.0 */ public final static String SPELLING_LOCALE= ISpellCheckPreferenceKeys.SPELLING_LOCALE; /** * A named preference that controls the number of proposals offered during * spell-checking. * <p> * Value is of type <code>Integer</code>. * </p> * * @since 3.0 */ public final static String SPELLING_PROPOSAL_THRESHOLD= ISpellCheckPreferenceKeys.SPELLING_PROPOSAL_THRESHOLD; /** * A named preference that specifies the workspace user dictionary. * <p> * Value is of type <code>Integer</code>. * </p> * * @since 3.0 */ public final static String SPELLING_USER_DICTIONARY= ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY; /** * A named preference that specifies whether spelling dictionaries are available to content assist. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String SPELLING_ENABLE_CONTENTASSIST= ISpellCheckPreferenceKeys.SPELLING_ENABLE_CONTENTASSIST; /** * A named preference that controls whether code snippets are formatted * in Javadoc comments. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_FORMATSOURCE= "comment_format_source_code"; //$NON-NLS-1$ /** * A named preference that controls whether description of Javadoc * parameters are indented. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION= "comment_indent_parameter_description"; //$NON-NLS-1$ /** * A named preference that controls whether the header comment of * a Java source file is formatted. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_FORMATHEADER= "comment_format_header"; //$NON-NLS-1$ /** * A named preference that controls whether Javadoc root tags * are indented. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_INDENTROOTTAGS= "comment_indent_root_tags"; //$NON-NLS-1$ /** * A named preference that controls whether Javadoc comments * are formatted by the content formatter. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_FORMAT= "comment_format_comments"; //$NON-NLS-1$ /** * A named preference that controls whether a new line is inserted * after Javadoc root tag parameters. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_NEWLINEFORPARAMETER= "comment_new_line_for_parameter"; //$NON-NLS-1$ /** * A named preference that controls whether an empty line is inserted before * the Javadoc root tag block. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_SEPARATEROOTTAGS= "comment_separate_root_tags"; //$NON-NLS-1$ /** * A named preference that controls whether blank lines are cleared during formatting * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_CLEARBLANKLINES= "comment_clear_blank_lines"; //$NON-NLS-1$ /** * A named preference that controls the line length of comments. * <p> * Value is of type <code>Integer</code>. The value must be at least 4 for reasonable formatting. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_LINELENGTH= "comment_line_length"; //$NON-NLS-1$ /** * A named preference that controls whether HTML tags are formatted. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_FORMATHTML= "comment_format_html"; //$NON-NLS-1$ /** * A named preference that controls if the Java code assist gets auto activated. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String CODEASSIST_AUTOACTIVATION= "content_assist_autoactivation"; //$NON-NLS-1$ /** * A name preference that holds the auto activation delay time in milli seconds. * <p> * Value is of type <code>Integer</code>. * </p> */ public final static String CODEASSIST_AUTOACTIVATION_DELAY= "content_assist_autoactivation_delay"; //$NON-NLS-1$ /** * A named preference that controls if code assist contains only visible proposals. * <p> * Value is of type <code>Boolean</code>. if <code>true<code> code assist only contains visible members. If * <code>false</code> all members are included. * </p> */ public final static String CODEASSIST_SHOW_VISIBLE_PROPOSALS= "content_assist_show_visible_proposals"; //$NON-NLS-1$ /** * A named preference that controls if the Java code assist inserts a * proposal automatically if only one proposal is available. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String CODEASSIST_AUTOINSERT= "content_assist_autoinsert"; //$NON-NLS-1$ /** * A named preference that controls if the Java code assist adds import * statements. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String CODEASSIST_ADDIMPORT= "content_assist_add_import"; //$NON-NLS-1$ /** * A named preference that controls if the Java code assist only inserts * completions. If set to false the proposals can also _replace_ code. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String CODEASSIST_INSERT_COMPLETION= "content_assist_insert_completion"; //$NON-NLS-1$ /** * A named preference that controls whether code assist proposals filtering is case sensitive or not. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String CODEASSIST_CASE_SENSITIVITY= "content_assist_case_sensitivity"; //$NON-NLS-1$ /** * A named preference that defines if code assist proposals are sorted in alphabetical order. * <p> * Value is of type <code>Boolean</code>. If <code>true</code> that are sorted in alphabetical * order. If <code>false</code> that are unsorted. * </p> */ public final static String CODEASSIST_ORDER_PROPOSALS= "content_assist_order_proposals"; //$NON-NLS-1$ /** * A named preference that controls if argument names are filled in when a method is selected from as list * of code assist proposal. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String CODEASSIST_FILL_ARGUMENT_NAMES= "content_assist_fill_method_arguments"; //$NON-NLS-1$ /** * A named preference that controls if method arguments are guessed when a * method is selected from as list of code assist proposal. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String CODEASSIST_GUESS_METHOD_ARGUMENTS= "content_assist_guess_method_arguments"; //$NON-NLS-1$ /** * A named preference that holds the characters that auto activate code assist in Java code. * <p> * Value is of type <code>String</code>. All characters that trigger auto code assist in Java code. * </p> */ public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA= "content_assist_autoactivation_triggers_java"; //$NON-NLS-1$ /** * A named preference that holds the characters that auto activate code assist in Javadoc. * <p> * Value is of type <code>String</code>. All characters that trigger auto code assist in Javadoc. * </p> */ public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC= "content_assist_autoactivation_triggers_javadoc"; //$NON-NLS-1$ /** * A named preference that holds the background color used in the code assist selection dialog. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String CODEASSIST_PROPOSALS_BACKGROUND= "content_assist_proposals_background"; //$NON-NLS-1$ /** * A named preference that holds the foreground color used in the code assist selection dialog. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String CODEASSIST_PROPOSALS_FOREGROUND= "content_assist_proposals_foreground"; //$NON-NLS-1$ /** * A named preference that holds the background color used for parameter hints. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String CODEASSIST_PARAMETERS_BACKGROUND= "content_assist_parameters_background"; //$NON-NLS-1$ /** * A named preference that holds the foreground color used in the code assist selection dialog. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String CODEASSIST_PARAMETERS_FOREGROUND= "content_assist_parameters_foreground"; //$NON-NLS-1$ /** * A named preference that holds the background color used in the code * assist selection dialog to mark replaced code. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String CODEASSIST_REPLACEMENT_BACKGROUND= "content_assist_completion_replacement_background"; //$NON-NLS-1$ /** * A named preference that holds the foreground color used in the code * assist selection dialog to mark replaced code. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String CODEASSIST_REPLACEMENT_FOREGROUND= "content_assist_completion_replacement_foreground"; //$NON-NLS-1$ /** * A named preference that controls the behavior of the refactoring wizard for showing the error page. * <p> * Value is of type <code>String</code>. Valid values are: * <code>REFACTOR_FATAL_SEVERITY</code>, * <code>REFACTOR_ERROR_SEVERITY</code>, * <code>REFACTOR_WARNING_SEVERITY</code> * <code>REFACTOR_INFO_SEVERITY</code>, * <code>REFACTOR_OK_SEVERITY</code>. * </p> * * @see #REFACTOR_FATAL_SEVERITY * @see #REFACTOR_ERROR_SEVERITY * @see #REFACTOR_WARNING_SEVERITY * @see #REFACTOR_INFO_SEVERITY * @see #REFACTOR_OK_SEVERITY * * @deprecated Use method {@link org.eclipse.ltk.ui.refactoring.RefactoringUI#getConditionCheckingFailedSeverity()}. */ public static final String REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD= "Refactoring.ErrorPage.severityThreshold"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD * @deprecated Use constant {@link org.eclipse.ltk.core.refactoring.RefactoringStatus#FATAL} */ public static final String REFACTOR_FATAL_SEVERITY= "4"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD * @deprecated Use constant {@link org.eclipse.ltk.core.refactoring.RefactoringStatus#ERROR} */ public static final String REFACTOR_ERROR_SEVERITY= "3"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD * @deprecated Use constant {@link org.eclipse.ltk.core.refactoring.RefactoringStatus#WARNING} */ public static final String REFACTOR_WARNING_SEVERITY= "2"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD * @deprecated Use constant {@link org.eclipse.ltk.core.refactoring.RefactoringStatus#INFO} */ public static final String REFACTOR_INFO_SEVERITY= "1"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD * @deprecated Use constant {@link org.eclipse.ltk.core.refactoring.RefactoringStatus#OK} */ public static final String REFACTOR_OK_SEVERITY= "0"; //$NON-NLS-1$ /** * A named preference that controls whether all dirty editors are automatically saved before a refactoring is * executed. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String REFACTOR_SAVE_ALL_EDITORS= "Refactoring.savealleditors"; //$NON-NLS-1$ /** * A named preference that controls if the Java Browsing views are linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * * @see #LINK_PACKAGES_TO_EDITOR */ public static final String BROWSING_LINK_VIEW_TO_EDITOR= "org.eclipse.jdt.ui.browsing.linktoeditor"; //$NON-NLS-1$ /** * A named preference that controls the layout of the Java Browsing views vertically. Boolean value. * <p> * Value is of type <code>Boolean</code>. If <code>true<code> the views are stacked vertical. * If <code>false</code> they are stacked horizontal. * </p> */ public static final String BROWSING_STACK_VERTICALLY= "org.eclipse.jdt.ui.browsing.stackVertically"; //$NON-NLS-1$ /** * A named preference that controls if templates are formatted when applied. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 2.1 */ public static final String TEMPLATES_USE_CODEFORMATTER= "org.eclipse.jdt.ui.template.format"; //$NON-NLS-1$ /** * A named preference that controls which profile is used by the code formatter. * <p> * Value is of type <code>String</code>. * </p> * * @since 3.0 */ public static final String FORMATTER_PROFILE = "formatter_profile"; //$NON-NLS-1$ /** * A named preference that controls whether annotation roll over is used or not. * <p> * Value is of type <code>Boolean</code>. If <code>true<code> the annotation ruler column * uses a roll over to display multiple annotations * </p> * * @since 3.0 */ public static final String EDITOR_ANNOTATION_ROLL_OVER= "editor_annotation_roll_over"; //$NON-NLS-1$ /** * A named preference that controls if content assist inserts the common * prefix of all proposals before presenting choices. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String CODEASSIST_PREFIX_COMPLETION= "content_assist_prefix_completion"; //$NON-NLS-1$ /** * A named preference that controls whether folding is enabled in the Java editor. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_FOLDING_ENABLED= "editor_folding_enabled"; //$NON-NLS-1$ /** * A named preference that stores the configured folding provider. * <p> * Value is of type <code>String</code>. * </p> * * @since 3.0 */ public static final String EDITOR_FOLDING_PROVIDER= "editor_folding_provider"; //$NON-NLS-1$ /** * A named preference that stores the value for Javadoc folding for the default folding provider. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_FOLDING_JAVADOC= "editor_folding_default_javadoc"; //$NON-NLS-1$ /** * A named preference that stores the value for inner type folding for the default folding provider. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_FOLDING_INNERTYPES= "editor_folding_default_innertypes"; //$NON-NLS-1$ /** * A named preference that stores the value for method folding for the default folding provider. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_FOLDING_METHODS= "editor_folding_default_methods"; //$NON-NLS-1$ /** * A named preference that stores the value for imports folding for the default folding provider. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_FOLDING_IMPORTS= "editor_folding_default_imports"; //$NON-NLS-1$ /** * Initializes the given preference store with the default values. * * @param store the preference store to be initialized * * @since 2.1 */ public static void initializeDefaultValues(IPreferenceStore store) { // set the default values from AbstractDecoratedTextEditor AbstractDecoratedTextEditorPreferenceConstants.initializeDefaultValues(store); store.setDefault(PreferenceConstants.EDITOR_SHOW_SEGMENTS, false); // JavaBasePreferencePage store.setDefault(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, false); store.setDefault(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, false); store.setDefault(PreferenceConstants.OPEN_TYPE_HIERARCHY, PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_VIEW_PART); store.setDefault(PreferenceConstants.DOUBLE_CLICK, PreferenceConstants.DOUBLE_CLICK_EXPANDS); store.setDefault(PreferenceConstants.UPDATE_JAVA_VIEWS, PreferenceConstants.UPDATE_WHILE_EDITING); store.setToDefault(PreferenceConstants.UPDATE_JAVA_VIEWS); // clear preference, update on save not supported anymore store.setDefault(PreferenceConstants.LINK_BROWSING_PROJECTS_TO_EDITOR, true); store.setDefault(PreferenceConstants.LINK_BROWSING_PACKAGES_TO_EDITOR, true); store.setDefault(PreferenceConstants.LINK_BROWSING_TYPES_TO_EDITOR, true); store.setDefault(PreferenceConstants.LINK_BROWSING_MEMBERS_TO_EDITOR, true); // AppearancePreferencePage store.setDefault(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES, false); store.setDefault(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE, false); store.setDefault(PreferenceConstants.SHOW_CU_CHILDREN, true); store.setDefault(PreferenceConstants.BROWSING_STACK_VERTICALLY, false); store.setDefault(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW, ""); //$NON-NLS-1$ store.setDefault(PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER, true); // ImportOrganizePreferencePage store.setDefault(PreferenceConstants.ORGIMPORTS_IMPORTORDER, "java;javax;org;com"); //$NON-NLS-1$ store.setDefault(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD, 99); store.setDefault(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE, true); // TypeFilterPreferencePage store.setDefault(PreferenceConstants.TYPEFILTER_ENABLED, ""); //$NON-NLS-1$ store.setDefault(PreferenceConstants.TYPEFILTER_DISABLED, ""); //$NON-NLS-1$ // ClasspathVariablesPreferencePage // CodeFormatterPreferencePage // CompilerPreferencePage // no initialization needed // RefactoringPreferencePage store.setDefault(PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD, PreferenceConstants.REFACTOR_ERROR_SEVERITY); store.setDefault(PreferenceConstants.REFACTOR_SAVE_ALL_EDITORS, false); // TemplatePreferencePage store.setDefault(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER, true); // CodeGenerationPreferencePage // compatibility code if (store.getBoolean(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX)) { String prefix= store.getString(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX); if (prefix.length() > 0) { JavaCore.getPlugin().getPluginPreferences().setValue(JavaCore.CODEASSIST_FIELD_PREFIXES, prefix); store.setToDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX); store.setToDefault(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX); } } if (store.getBoolean(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX)) { String suffix= store.getString(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX); if (suffix.length() > 0) { JavaCore.getPlugin().getPluginPreferences().setValue(JavaCore.CODEASSIST_FIELD_SUFFIXES, suffix); store.setToDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX); store.setToDefault(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX); } } store.setDefault(PreferenceConstants.CODEGEN_KEYWORD_THIS, false); store.setDefault(PreferenceConstants.CODEGEN_IS_FOR_GETTERS, true); store.setDefault(PreferenceConstants.CODEGEN_EXCEPTION_VAR_NAME, "e"); //$NON-NLS-1$ store.setDefault(PreferenceConstants.CODEGEN_ADD_COMMENTS, true); // MembersOrderPreferencePage store.setDefault(PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER, "T,SF,SI,SM,I,F,C,M"); //$NON-NLS-1$ store.setDefault(PreferenceConstants.APPEARANCE_VISIBILITY_SORT_ORDER, "B,V,R,D"); //$NON-NLS-1$ store.setDefault(PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER, false); // must add here to guarantee that it is the first in the listener list store.addPropertyChangeListener(JavaPlugin.getDefault().getMemberOrderPreferenceCache()); // JavaEditorPreferencePage store.setDefault(PreferenceConstants.EDITOR_MATCHING_BRACKETS, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, new RGB(192, 192,192)); store.setDefault(PreferenceConstants.EDITOR_CURRENT_LINE, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_CURRENT_LINE_COLOR, new RGB(225, 235, 224)); store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN, false); store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 80); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR, new RGB(176, 180 , 185)); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_FIND_SCOPE_COLOR, new RGB(185, 176 , 180)); store.setDefault(PreferenceConstants.EDITOR_CORRECTION_INDICATION, true); store.setDefault(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, true); store.setDefault(PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, true); store.setDefault(PreferenceConstants.EDITOR_OVERVIEW_RULER, true); store.setDefault(PreferenceConstants.EDITOR_LINE_NUMBER_RULER, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR, new RGB(0, 0, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, new RGB(121, 121, 121)); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINK_COLOR, new RGB(0, 0, 255)); store.setDefault(PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR, true); store.setDefault(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, true); store.setDefault(PreferenceConstants.EDITOR_TAB_WIDTH, 4); store.setDefault(PreferenceConstants.EDITOR_SPACES_FOR_TABS, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR, new RGB(63, 127, 95)); store.setDefault(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD, false); store.setDefault(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_ITALIC, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR, new RGB(63, 127, 95)); store.setDefault(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD, false); store.setDefault(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_ITALIC, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR, new RGB(127, 0, 85)); store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD, true); store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_ITALIC, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_STRING_COLOR, new RGB(42, 0, 255)); store.setDefault(PreferenceConstants.EDITOR_STRING_BOLD, false); store.setDefault(PreferenceConstants.EDITOR_STRING_ITALIC, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR, new RGB(0, 0, 0)); store.setDefault(PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD, false); store.setDefault(PreferenceConstants.EDITOR_JAVA_DEFAULT_ITALIC, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR, new RGB(0, 0, 0)); store.setDefault(PreferenceConstants.EDITOR_JAVA_METHOD_NAME_BOLD, false); store.setDefault(PreferenceConstants.EDITOR_JAVA_METHOD_NAME_ITALIC, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_KEYWORD_RETURN_COLOR, new RGB(127, 0, 85)); store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_RETURN_BOLD, true); store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_RETURN_ITALIC, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_OPERATOR_COLOR, new RGB(0, 0, 0)); store.setDefault(PreferenceConstants.EDITOR_JAVA_OPERATOR_BOLD, false); store.setDefault(PreferenceConstants.EDITOR_JAVA_OPERATOR_ITALIC, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_TASK_TAG_COLOR, new RGB(127, 159, 191)); store.setDefault(PreferenceConstants.EDITOR_TASK_TAG_BOLD, true); store.setDefault(PreferenceConstants.EDITOR_TASK_TAG_ITALIC, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR, new RGB(127, 159, 191)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD, true); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_KEYWORD_ITALIC, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR, new RGB(127, 127, 159)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD, false); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_TAG_ITALIC, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR, new RGB(63, 63, 191)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD, false); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_LINKS_ITALIC, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR, new RGB(63, 95, 191)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD, false); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_DEFAULT_ITALIC, false); store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION, true); store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, 500); store.setDefault(PreferenceConstants.CODEASSIST_AUTOINSERT, true); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, new RGB(254, 241, 233)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, new RGB(0, 0, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND, new RGB(254, 241, 233)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND, new RGB(0, 0, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND, new RGB(255, 255, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND, new RGB(255, 0, 0)); store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, "."); //$NON-NLS-1$ store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, "@"); //$NON-NLS-1$ store.setDefault(PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, true); store.setDefault(PreferenceConstants.CODEASSIST_CASE_SENSITIVITY, false); store.setDefault(PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, false); store.setDefault(PreferenceConstants.CODEASSIST_ADDIMPORT, true); store.setDefault(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, true); store.setDefault(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, false); store.setDefault(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, true); store.setDefault(PreferenceConstants.CODEASSIST_PREFIX_COMPLETION, false); store.setDefault(PreferenceConstants.EDITOR_SMART_HOME_END, true); store.setDefault(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, true); store.setDefault(PreferenceConstants.EDITOR_SMART_PASTE, true); store.setDefault(PreferenceConstants.EDITOR_IMPORTS_ON_PASTE, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACES, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_JAVADOCS, true); store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS, true); store.setDefault(PreferenceConstants.EDITOR_ESCAPE_STRINGS, false); store.setDefault(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, true); store.setDefault(PreferenceConstants.EDITOR_FORMAT_JAVADOCS, false); store.setDefault(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE, false); String mod1Name= Action.findModifierString(SWT.MOD1); // SWT.COMMAND on Mac; SWT.CONTROL elsewhere store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, "org.eclipse.jdt.ui.BestMatchHover;0;org.eclipse.jdt.ui.JavaSourceHover;" + mod1Name); //$NON-NLS-1$ store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS, "org.eclipse.jdt.ui.BestMatchHover;0;org.eclipse.jdt.ui.JavaSourceHover;" + SWT.MOD1); //$NON-NLS-1$ store.setDefault(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE, true); store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, true); store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, mod1Name); store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, SWT.MOD1); store.setDefault(PreferenceConstants.EDITOR_SMART_TAB, true); store.setDefault(PreferenceConstants.EDITOR_SMART_BACKSPACE, true); store.setDefault(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER, false); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_FORMAT, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_FORMATHEADER, false); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_FORMATSOURCE, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_INDENTROOTTAGS, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_NEWLINEFORPARAMETER, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_SEPARATEROOTTAGS, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_CLEARBLANKLINES, false); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_FORMATHTML, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_LINELENGTH, 80); store.setDefault(PreferenceConstants.FORMATTER_PROFILE, ProfileManager.DEFAULT_PROFILE); // mark occurrences store.setDefault(PreferenceConstants.EDITOR_MARK_OCCURRENCES, false); store.setDefault(PreferenceConstants.EDITOR_STICKY_OCCURRENCES, true); store.setDefault(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES, true); store.setDefault(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES, true); store.setDefault(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES, true); store.setDefault(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES, true); store.setDefault(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES, true); store.setDefault(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES, true); store.setDefault(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS, true); // spell checking store.setDefault(PreferenceConstants.SPELLING_CHECK_SPELLING, false); store.setDefault(PreferenceConstants.SPELLING_LOCALE, SpellCheckEngine.getDefaultLocale().toString()); store.setDefault(PreferenceConstants.SPELLING_IGNORE_DIGITS, true); store.setDefault(PreferenceConstants.SPELLING_IGNORE_MIXED, true); store.setDefault(PreferenceConstants.SPELLING_IGNORE_SENTENCE, true); store.setDefault(PreferenceConstants.SPELLING_IGNORE_UPPER, true); store.setDefault(PreferenceConstants.SPELLING_IGNORE_URLS, true); store.setDefault(PreferenceConstants.SPELLING_USER_DICTIONARY, ""); //$NON-NLS-1$ store.setDefault(PreferenceConstants.SPELLING_PROPOSAL_THRESHOLD, 20); store.setDefault(PreferenceConstants.SPELLING_ENABLE_CONTENTASSIST, false); // folding store.setDefault(PreferenceConstants.EDITOR_FOLDING_ENABLED, false); store.setDefault(PreferenceConstants.EDITOR_FOLDING_PROVIDER, "org.eclipse.jdt.ui.text.defaultFoldingProvider"); //$NON-NLS-1$ store.setDefault(PreferenceConstants.EDITOR_FOLDING_JAVADOC, false); store.setDefault(PreferenceConstants.EDITOR_FOLDING_INNERTYPES, true); store.setDefault(PreferenceConstants.EDITOR_FOLDING_METHODS, false); store.setDefault(PreferenceConstants.EDITOR_FOLDING_IMPORTS, true); // override default extended text editor prefs store.setDefault(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_USE_CUSTOM_CARETS, true); // work in progress WorkInProgressPreferencePage.initDefaults(store); SemanticHighlightings.initDefaults(store); // do more complicated stuff NewJavaProjectPreferencePage.initDefaults(store); } /** * Returns the JDT-UI preference store. * * @return the JDT-UI preference store */ public static IPreferenceStore getPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } /** * Encodes a JRE library to be used in the named preference <code>NEWPROJECT_JRELIBRARY_LIST</code>. * * @param description a string value describing the JRE library. The description is used * to identify the JDR library in the UI * @param entries an array of classpath entries to be encoded * * @return the encoded string. */ public static String encodeJRELibrary(String description, IClasspathEntry[] entries) { return NewJavaProjectPreferencePage.encodeJRELibrary(description, entries); } /** * Decodes an encoded JRE library and returns its description string. * * @return the description of an encoded JRE library * * @see #encodeJRELibrary(String, IClasspathEntry[]) */ public static String decodeJRELibraryDescription(String encodedLibrary) { return NewJavaProjectPreferencePage.decodeJRELibraryDescription(encodedLibrary); } /** * Decodes an encoded JRE library and returns its classpath entries. * * @return the array of classpath entries of an encoded JRE library. * * @see #encodeJRELibrary(String, IClasspathEntry[]) */ public static IClasspathEntry[] decodeJRELibraryClasspathEntries(String encodedLibrary) { return NewJavaProjectPreferencePage.decodeJRELibraryClasspathEntries(encodedLibrary); } /** * Returns the current configuration for the JRE to be used as default in new Java projects. * This is a convenience method to access the named preference <code>NEWPROJECT_JRELIBRARY_LIST * </code> with the index defined by <code> NEWPROJECT_JRELIBRARY_INDEX</code>. * * @return the current default set of classpath entries * * @see #NEWPROJECT_JRELIBRARY_LIST * @see #NEWPROJECT_JRELIBRARY_INDEX */ public static IClasspathEntry[] getDefaultJRELibrary() { return NewJavaProjectPreferencePage.getDefaultJRELibrary(); } }
49,099
Bug 49099 Reduced Search menu does too much [search]
I200312180010 The reduced search menu preference (work in progress) does too much and therefore I cannot use it: Exmples: - select an interface (in outline or any other view where you already know it is an interface. Try to search for implementors ==> not possible. - same applies for fields: it is no longer possible to search for read/write access.
resolved fixed
cfdbbb3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T16:41:28Z
2003-12-18T09:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/JavaSearchActionGroup.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui.actions; import org.eclipse.jface.util.Assert; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.part.Page; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.jdt.internal.ui.actions.FindExceptionOccurrences; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jdt.internal.ui.preferences.WorkInProgressPreferencePage; import org.eclipse.jdt.internal.ui.search.SearchMessages; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.PreferenceConstants; /** * Action group that adds the Java search actions to a context menu and * the global menu bar. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class JavaSearchActionGroup extends ActionGroup { private JavaEditor fEditor; private IWorkbenchSite fSite; private ReferencesSearchGroup fReferencesGroup; private ReadReferencesSearchGroup fReadAccessGroup; private WriteReferencesSearchGroup fWriteAccessGroup; private DeclarationsSearchGroup fDeclarationsGroup; private ImplementorsSearchGroup fImplementorsGroup; private FindOccurrencesInFileAction fOccurrencesInFileAction; private FindExceptionOccurrences fExceptionOriginatorsAction; /** * Creates a new <code>JavaSearchActionGroup</code>. The group * requires that the selection provided by the part's selection provider * is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param part the view part that owns this action group */ public JavaSearchActionGroup(IViewPart part) { this(part.getViewSite()); fOccurrencesInFileAction= new FindOccurrencesInFileAction(part); part.getViewSite().getSelectionProvider().addSelectionChangedListener(fOccurrencesInFileAction); } /** * Creates a new <code>JavaSearchActionGroup</code>. The group * requires that the selection provided by the page's selection provider * is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param page the page that owns this action group */ public JavaSearchActionGroup(Page page) { this(page.getSite()); fOccurrencesInFileAction= new FindOccurrencesInFileAction(page); page.getSite().getSelectionProvider().addSelectionChangedListener(fOccurrencesInFileAction); } /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public JavaSearchActionGroup(JavaEditor editor) { Assert.isNotNull(editor); fEditor= editor; fSite= fEditor.getSite(); fReferencesGroup= new ReferencesSearchGroup(fEditor); fReadAccessGroup= new ReadReferencesSearchGroup(fEditor); fWriteAccessGroup= new WriteReferencesSearchGroup(fEditor); fDeclarationsGroup= new DeclarationsSearchGroup(fEditor); fImplementorsGroup= new ImplementorsSearchGroup(fEditor); fOccurrencesInFileAction= new FindOccurrencesInFileAction(fEditor); fExceptionOriginatorsAction= new FindExceptionOccurrences(fEditor); } private JavaSearchActionGroup(IWorkbenchSite site) { fReferencesGroup= new ReferencesSearchGroup(site); fReadAccessGroup= new ReadReferencesSearchGroup(site); fWriteAccessGroup= new WriteReferencesSearchGroup(site); fDeclarationsGroup= new DeclarationsSearchGroup(site); fImplementorsGroup= new ImplementorsSearchGroup(site); fSite= site; } /* * Method declared on ActionGroup. */ public void setContext(ActionContext context) { fReferencesGroup.setContext(context); fDeclarationsGroup.setContext(context); fImplementorsGroup.setContext(context); fReadAccessGroup.setContext(context); fWriteAccessGroup.setContext(context); } /* * Method declared on ActionGroup. */ public void fillActionBars(IActionBars actionBar) { super.fillActionBars(actionBar); fReferencesGroup.fillActionBars(actionBar); fDeclarationsGroup.fillActionBars(actionBar); fImplementorsGroup.fillActionBars(actionBar); fReadAccessGroup.fillActionBars(actionBar); fWriteAccessGroup.fillActionBars(actionBar); actionBar.setGlobalActionHandler(JdtActionConstants.FIND_OCCURRENCES_IN_FILE, fOccurrencesInFileAction); actionBar.setGlobalActionHandler(JdtActionConstants.FIND_EXCEPTION_OCCURRENCES, fExceptionOriginatorsAction); } /* * Method declared on ActionGroup. */ public void fillContextMenu(IMenuManager menu) { super.fillContextMenu(menu); if(PreferenceConstants.getPreferenceStore().getBoolean(WorkInProgressPreferencePage.PREF_SEARCH_MENU)) { fReferencesGroup.fillContextMenu(menu); fDeclarationsGroup.fillContextMenu(menu); if (fEditor == null) { fImplementorsGroup.fillContextMenu(menu); fReadAccessGroup.fillContextMenu(menu); fWriteAccessGroup.fillContextMenu(menu); addAction(menu, IContextMenuConstants.GROUP_SEARCH, fOccurrencesInFileAction); } } else { IMenuManager target= menu; IMenuManager searchSubMenu= null; if (fEditor != null) { String groupName= SearchMessages.getString("group.search"); //$NON-NLS-1$ searchSubMenu= new MenuManager(groupName, ITextEditorActionConstants.GROUP_FIND); searchSubMenu.add(new GroupMarker(ITextEditorActionConstants.GROUP_FIND)); target= searchSubMenu; } fReferencesGroup.fillContextMenu(target); fDeclarationsGroup.fillContextMenu(target); fImplementorsGroup.fillContextMenu(target); fReadAccessGroup.fillContextMenu(target); fWriteAccessGroup.fillContextMenu(target); if (searchSubMenu != null) { searchSubMenu.add(new Separator()); addAction(target, fOccurrencesInFileAction); } else { addAction(target, IContextMenuConstants.GROUP_SEARCH, fOccurrencesInFileAction); } // no other way to find out if we have added items. if (searchSubMenu != null && searchSubMenu.getItems().length > 2) { menu.appendToGroup(ITextEditorActionConstants.GROUP_FIND, searchSubMenu); } } } /* * Method declared on ActionGroup. */ public void dispose() { fReferencesGroup.dispose(); fDeclarationsGroup.dispose(); fImplementorsGroup.dispose(); fReadAccessGroup.dispose(); fWriteAccessGroup.dispose(); if (fOccurrencesInFileAction != null) fSite.getSelectionProvider().removeSelectionChangedListener(fOccurrencesInFileAction); super.dispose(); } private void addAction(IMenuManager manager, IAction action) { if (action != null && action.isEnabled()) manager.add(action); } private void addAction(IMenuManager manager, String group, IAction action) { if (action != null && action.isEnabled()) manager.appendToGroup(group, action); } }
55,845
Bug 55845 NPE when closing editor context menu [refactoring]
I 2004-03-24 + plugin-export 1) in a repositories view, drill down to TableItem.java in org.eclipse.set and open the file from the repository. 2) right-click to get the context menu 3) observe: you get a context menu with two entries: "Copy" and "Refactor". 4) go into the "Refactor" submenu 5) click somewhere else in the editor, thus closing the context menu 6) observe and exception: java.lang.NullPointerException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at java.lang.NullPointerException.<init>(NullPointerException.java:60) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringActions.convertToEnclosingOrPrimaryType(RefactoringActions.java:50) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringActions.getEnclosingOrPrimaryType(RefactoringActions.java:40) at org.eclipse.jdt.ui.actions.ExtractInterfaceAction.canEnable(ExtractInterfaceAction.java:144) at org.eclipse.jdt.ui.actions.ExtractInterfaceAction.selectionChanged(ExtractInterfaceAction.java:137) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchSelectionChanged(SelectionDispatchAction.java:202) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.update(SelectionDispatchAction.java:114) at org.eclipse.jdt.ui.actions.RefactorActionGroup.refactorMenuShown(RefactorActionGroup.java:461) at org.eclipse.jdt.ui.actions.RefactorActionGroup.access$0(RefactorActionGroup.java:446) at org.eclipse.jdt.ui.actions.RefactorActionGroup$1.menuAboutToShow(RefactorActionGroup.java:401) at org.eclipse.jface.action.MenuManager.fireAboutToShow(MenuManager.java:286) at org.eclipse.jface.action.MenuManager.handleAboutToShow(MenuManager.java:370) at org.eclipse.jface.action.MenuManager.access$0(MenuManager.java:367) at org.eclipse.jface.action.MenuManager$2.menuShown(MenuManager.java:383) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Control.WM_INITMENUPOPUP(Control.java:3295) at org.eclipse.swt.widgets.Control.windowProc(Control.java) at org.eclipse.swt.widgets.Decorations.windowProc(Decorations.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.win32.OS.TrackPopupMenu(Native Method) at org.eclipse.swt.widgets.Menu._setVisible(Menu.java:222) at org.eclipse.swt.widgets.Display.runPopups(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1541) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1515) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:257) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:90) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:288) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:232) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:116) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:79) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:41) at java.lang.reflect.Method.invoke(Method.java:386) at org.eclipse.core.launcher.Main.basicRun(Main.java:315) at org.eclipse.core.launcher.Main.run(Main.java:740) at org.eclipse.core.launcher.Main.main(Main.java:724)
verified fixed
d69dfe9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T17:22:38Z
2004-03-24T09:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/RefactorActionGroup.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui.actions; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.swt.events.MenuAdapter; import org.eclipse.swt.events.MenuEvent; import org.eclipse.swt.widgets.Menu; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IKeyBindingService; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.part.Page; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.ActionMessages; import org.eclipse.jdt.internal.ui.actions.ActionUtil; import org.eclipse.jdt.internal.ui.actions.JDTQuickMenuAction; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.javaeditor.JavaTextSelection; import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages; import org.eclipse.jdt.ui.IContextMenuConstants; /** * Action group that adds refactor actions (for example Rename..., Move..., etc) * to a context menu and the global menu bar. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class RefactorActionGroup extends ActionGroup { /** * Pop-up menu: id of the refactor sub menu (value <code>org.eclipse.jdt.ui.refactoring.menu</code>). * * @since 2.1 */ public static final String MENU_ID= "org.eclipse.jdt.ui.refactoring.menu"; //$NON-NLS-1$ /** * Pop-up menu: id of the reorg group of the refactor sub menu (value * <code>reorgGroup</code>). * * @since 2.1 */ public static final String GROUP_REORG= "reorgGroup"; //$NON-NLS-1$ /** * Pop-up menu: id of the type group of the refactor sub menu (value * <code>typeGroup</code>). * * @since 2.1 */ public static final String GROUP_TYPE= "typeGroup"; //$NON-NLS-1$ /** * Pop-up menu: id of the coding group of the refactor sub menu (value * <code>codingGroup</code>). * * @since 2.1 */ public static final String GROUP_CODING= "codingGroup"; //$NON-NLS-1$ private IWorkbenchSite fSite; private CompilationUnitEditor fEditor; private String fGroupName= IContextMenuConstants.GROUP_REORGANIZE; private SelectionDispatchAction fMoveAction; private SelectionDispatchAction fRenameAction; private SelectionDispatchAction fModifyParametersAction; private SelectionDispatchAction fConvertAnonymousToNestedAction; private SelectionDispatchAction fConvertNestedToTopAction; private SelectionDispatchAction fPullUpAction; private SelectionDispatchAction fPushDownAction; private SelectionDispatchAction fExtractInterfaceAction; private SelectionDispatchAction fChangeTypeAction; private SelectionDispatchAction fUseSupertypeAction; private SelectionDispatchAction fInlineAction; private SelectionDispatchAction fExtractMethodAction; private SelectionDispatchAction fExtractTempAction; private SelectionDispatchAction fExtractConstantAction; private SelectionDispatchAction fIntroduceParameterAction; private SelectionDispatchAction fIntroduceFactoryAction; private SelectionDispatchAction fConvertLocalToFieldAction; private SelectionDispatchAction fSelfEncapsulateField; private List fEditorActions; private static final String QUICK_MENU_ID= "org.eclipse.jdt.ui.edit.text.java.refactor.quickMenu"; //$NON-NLS-1$ private class RefactorQuickAccessAction extends JDTQuickMenuAction { public RefactorQuickAccessAction(CompilationUnitEditor editor) { super(editor, QUICK_MENU_ID); //$NON-NLS-1$ } protected void fillMenu(IMenuManager menu) { fillQuickMenu(menu); } } private RefactorQuickAccessAction fQuickAccessAction; private IKeyBindingService fKeyBindingService; private static class NoActionAvailable extends Action { public NoActionAvailable() { setEnabled(true); setText(RefactoringMessages.getString("RefactorActionGroup.no_refactoring_available")); //$NON-NLS-1$ } } private Action fNoActionAvailable= new NoActionAvailable(); /** * Creates a new <code>RefactorActionGroup</code>. The group requires * that the selection provided by the part's selection provider is of type <code> * org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param part the view part that owns this action group */ public RefactorActionGroup(IViewPart part) { this(part.getSite(), part.getSite().getKeyBindingService()); } /** * Creates a new <code>RefactorActionGroup</code>. The action requires * that the selection provided by the page's selection provider is of type <code> * org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param page the page that owns this action group */ public RefactorActionGroup(Page page) { this(page.getSite(), null); } /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public RefactorActionGroup(CompilationUnitEditor editor, String groupName) { fSite= editor.getEditorSite(); fEditor= editor; fGroupName= groupName; ISelectionProvider provider= editor.getSelectionProvider(); ISelection selection= provider.getSelection(); fEditorActions= new ArrayList(); fRenameAction= new RenameAction(editor); fRenameAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.RENAME_ELEMENT); fRenameAction.update(selection); editor.setAction("RenameElement", fRenameAction); //$NON-NLS-1$ fEditorActions.add(fRenameAction); fMoveAction= new MoveAction(editor); fMoveAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.MOVE_ELEMENT); fMoveAction.update(selection); editor.setAction("MoveElement", fMoveAction); //$NON-NLS-1$ fEditorActions.add(fMoveAction); fModifyParametersAction= new ModifyParametersAction(editor); fModifyParametersAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.MODIFY_METHOD_PARAMETERS); fModifyParametersAction.update(selection); editor.setAction("ModifyParameters", fModifyParametersAction); //$NON-NLS-1$ fEditorActions.add(fModifyParametersAction); fConvertAnonymousToNestedAction= new ConvertAnonymousToNestedAction(editor); fConvertAnonymousToNestedAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONVERT_ANONYMOUS_TO_NESTED); initAction(fConvertAnonymousToNestedAction, provider, selection); editor.setAction("ConvertAnonymousToNested", fConvertAnonymousToNestedAction); //$NON-NLS-1$ fEditorActions.add(fConvertAnonymousToNestedAction); fConvertNestedToTopAction= new ConvertNestedToTopAction(editor); fConvertNestedToTopAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.MOVE_INNER_TO_TOP); fConvertNestedToTopAction.update(selection); editor.setAction("MoveInnerToTop", fConvertNestedToTopAction); //$NON-NLS-1$ fEditorActions.add(fConvertNestedToTopAction); fPullUpAction= new PullUpAction(editor); fPullUpAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.PULL_UP); fPullUpAction.update(selection); editor.setAction("PullUp", fPullUpAction); //$NON-NLS-1$ fEditorActions.add(fPullUpAction); fPushDownAction= new PushDownAction(editor); fPushDownAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.PUSH_DOWN); fPushDownAction.update(selection); editor.setAction("PushDown", fPushDownAction); //$NON-NLS-1$ fEditorActions.add(fPushDownAction); fExtractInterfaceAction= new ExtractInterfaceAction(editor); fExtractInterfaceAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.EXTRACT_INTERFACE); fExtractInterfaceAction.update(selection); editor.setAction("ExtractInterface", fExtractInterfaceAction); //$NON-NLS-1$ fEditorActions.add(fExtractInterfaceAction); fChangeTypeAction= new ChangeTypeAction(editor); fChangeTypeAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.CHANGE_TYPE); initAction(fChangeTypeAction, provider, selection); editor.setAction("ChangeType", fChangeTypeAction); //$NON-NLS-1$ fEditorActions.add(fChangeTypeAction); fUseSupertypeAction= new UseSupertypeAction(editor); fUseSupertypeAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.USE_SUPERTYPE); fUseSupertypeAction.update(selection); editor.setAction("UseSupertype", fUseSupertypeAction); //$NON-NLS-1$ fEditorActions.add(fUseSupertypeAction); fInlineAction= new InlineAction(editor); fInlineAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.INLINE); fInlineAction.update(selection); editor.setAction("Inline", fInlineAction); //$NON-NLS-1$ fEditorActions.add(fInlineAction); fExtractMethodAction= new ExtractMethodAction(editor); fExtractMethodAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.EXTRACT_METHOD); initAction(fExtractMethodAction, provider, selection); editor.setAction("ExtractMethod", fExtractMethodAction); //$NON-NLS-1$ fEditorActions.add(fExtractMethodAction); fExtractTempAction= new ExtractTempAction(editor); fExtractTempAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.EXTRACT_LOCAL_VARIABLE); initAction(fExtractTempAction, provider, selection); editor.setAction("ExtractLocalVariable", fExtractTempAction); //$NON-NLS-1$ fEditorActions.add(fExtractTempAction); fExtractConstantAction= new ExtractConstantAction(editor); fExtractConstantAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.EXTRACT_CONSTANT); initAction(fExtractConstantAction, provider, selection); editor.setAction("ExtractConstant", fExtractConstantAction); //$NON-NLS-1$ fEditorActions.add(fExtractConstantAction); fIntroduceParameterAction= new IntroduceParameterAction(editor); fIntroduceParameterAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.INTRODUCE_PARAMETER); initAction(fIntroduceParameterAction, provider, selection); editor.setAction("IntroduceParameter", fIntroduceParameterAction); //$NON-NLS-1$ fEditorActions.add(fIntroduceParameterAction); fIntroduceFactoryAction= new IntroduceFactoryAction(editor); fIntroduceFactoryAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.INTRODUCE_FACTORY); initAction(fIntroduceFactoryAction, provider, selection); editor.setAction("IntroduceFactory", fIntroduceFactoryAction); //$NON-NLS-1$ fEditorActions.add(fIntroduceFactoryAction); fConvertLocalToFieldAction= new ConvertLocalToFieldAction(editor); fConvertLocalToFieldAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.PROMOTE_LOCAL_VARIABLE); initAction(fConvertLocalToFieldAction, provider, selection); editor.setAction("PromoteTemp", fConvertLocalToFieldAction); //$NON-NLS-1$ fEditorActions.add(fConvertLocalToFieldAction); fSelfEncapsulateField= new SelfEncapsulateFieldAction(editor); fSelfEncapsulateField.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELF_ENCAPSULATE_FIELD); fSelfEncapsulateField.update(selection); editor.setAction("SelfEncapsulateField", fSelfEncapsulateField); //$NON-NLS-1$ fEditorActions.add(fSelfEncapsulateField); fQuickAccessAction= new RefactorQuickAccessAction(editor); fKeyBindingService= editor.getEditorSite().getKeyBindingService(); fKeyBindingService.registerAction(fQuickAccessAction); } private RefactorActionGroup(IWorkbenchSite site, IKeyBindingService keyBindingService) { fSite= site; ISelectionProvider provider= fSite.getSelectionProvider(); ISelection selection= provider.getSelection(); fMoveAction= new MoveAction(site); fMoveAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.MOVE_ELEMENT); initAction(fMoveAction, provider, selection); fRenameAction= new RenameAction(site); fRenameAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.RENAME_ELEMENT); initAction(fRenameAction, provider, selection); fModifyParametersAction= new ModifyParametersAction(fSite); fModifyParametersAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.MODIFY_METHOD_PARAMETERS); initAction(fModifyParametersAction, provider, selection); fPullUpAction= new PullUpAction(fSite); fPullUpAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.PULL_UP); initAction(fPullUpAction, provider, selection); fPushDownAction= new PushDownAction(fSite); fPushDownAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.PUSH_DOWN); initAction(fPushDownAction, provider, selection); fSelfEncapsulateField= new SelfEncapsulateFieldAction(fSite); fSelfEncapsulateField.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELF_ENCAPSULATE_FIELD); initAction(fSelfEncapsulateField, provider, selection); fExtractInterfaceAction= new ExtractInterfaceAction(fSite); fExtractInterfaceAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.EXTRACT_INTERFACE); initAction(fExtractInterfaceAction, provider, selection); fChangeTypeAction= new ChangeTypeAction(fSite); fChangeTypeAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.CHANGE_TYPE); initAction(fChangeTypeAction, provider, selection); fConvertNestedToTopAction= new ConvertNestedToTopAction(fSite); fConvertNestedToTopAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.MOVE_INNER_TO_TOP); initAction(fConvertNestedToTopAction, provider, selection); fUseSupertypeAction= new UseSupertypeAction(fSite); fUseSupertypeAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.USE_SUPERTYPE); initAction(fUseSupertypeAction, provider, selection); fInlineAction= new InlineAction(fSite); fInlineAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.INLINE); initAction(fInlineAction, provider, selection); fIntroduceFactoryAction= new IntroduceFactoryAction(fSite); fIntroduceFactoryAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.INTRODUCE_FACTORY); initAction(fIntroduceFactoryAction, provider, selection); fConvertAnonymousToNestedAction= new ConvertAnonymousToNestedAction(fSite); fConvertAnonymousToNestedAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONVERT_ANONYMOUS_TO_NESTED); initAction(fConvertAnonymousToNestedAction, provider, selection); fKeyBindingService= keyBindingService; if (fKeyBindingService != null) { fQuickAccessAction= new RefactorQuickAccessAction(null); fKeyBindingService.registerAction(fQuickAccessAction); } } private static void initAction(SelectionDispatchAction action, ISelectionProvider provider, ISelection selection){ action.update(selection); provider.addSelectionChangedListener(action); } /* (non-Javadoc) * Method declared in ActionGroup */ public void fillActionBars(IActionBars actionBars) { super.fillActionBars(actionBars); actionBars.setGlobalActionHandler(JdtActionConstants.SELF_ENCAPSULATE_FIELD, fSelfEncapsulateField); actionBars.setGlobalActionHandler(JdtActionConstants.MOVE, fMoveAction); actionBars.setGlobalActionHandler(JdtActionConstants.RENAME, fRenameAction); actionBars.setGlobalActionHandler(JdtActionConstants.MODIFY_PARAMETERS, fModifyParametersAction); actionBars.setGlobalActionHandler(JdtActionConstants.PULL_UP, fPullUpAction); actionBars.setGlobalActionHandler(JdtActionConstants.PUSH_DOWN, fPushDownAction); actionBars.setGlobalActionHandler(JdtActionConstants.EXTRACT_TEMP, fExtractTempAction); actionBars.setGlobalActionHandler(JdtActionConstants.EXTRACT_CONSTANT, fExtractConstantAction); actionBars.setGlobalActionHandler(JdtActionConstants.INTRODUCE_PARAMETER, fIntroduceParameterAction); actionBars.setGlobalActionHandler(JdtActionConstants.INTRODUCE_FACTORY, fIntroduceFactoryAction); actionBars.setGlobalActionHandler(JdtActionConstants.EXTRACT_METHOD, fExtractMethodAction); actionBars.setGlobalActionHandler(JdtActionConstants.INLINE, fInlineAction); actionBars.setGlobalActionHandler(JdtActionConstants.EXTRACT_INTERFACE, fExtractInterfaceAction); actionBars.setGlobalActionHandler(JdtActionConstants.CHANGE_TYPE, fChangeTypeAction); actionBars.setGlobalActionHandler(JdtActionConstants.CONVERT_NESTED_TO_TOP, fConvertNestedToTopAction); actionBars.setGlobalActionHandler(JdtActionConstants.USE_SUPERTYPE, fUseSupertypeAction); actionBars.setGlobalActionHandler(JdtActionConstants.CONVERT_LOCAL_TO_FIELD, fConvertLocalToFieldAction); actionBars.setGlobalActionHandler(JdtActionConstants.CONVERT_ANONYMOUS_TO_NESTED, fConvertAnonymousToNestedAction); } /* (non-Javadoc) * Method declared in ActionGroup */ public void fillContextMenu(IMenuManager menu) { super.fillContextMenu(menu); addRefactorSubmenu(menu); } /* * @see ActionGroup#dispose() */ public void dispose() { ISelectionProvider provider= fSite.getSelectionProvider(); disposeAction(fSelfEncapsulateField, provider); disposeAction(fMoveAction, provider); disposeAction(fRenameAction, provider); disposeAction(fModifyParametersAction, provider); disposeAction(fPullUpAction, provider); disposeAction(fPushDownAction, provider); disposeAction(fExtractTempAction, provider); disposeAction(fExtractConstantAction, provider); disposeAction(fIntroduceParameterAction, provider); disposeAction(fIntroduceFactoryAction, provider); disposeAction(fExtractMethodAction, provider); disposeAction(fInlineAction, provider); disposeAction(fExtractInterfaceAction, provider); disposeAction(fChangeTypeAction, provider); disposeAction(fConvertNestedToTopAction, provider); disposeAction(fUseSupertypeAction, provider); disposeAction(fConvertLocalToFieldAction, provider); disposeAction(fConvertAnonymousToNestedAction, provider); if (fQuickAccessAction != null && fKeyBindingService != null) { fKeyBindingService.unregisterAction(fQuickAccessAction); } super.dispose(); } private void disposeAction(ISelectionChangedListener action, ISelectionProvider provider) { if (action != null) provider.removeSelectionChangedListener(action); } private void addRefactorSubmenu(IMenuManager menu) { String shortCut= null; //$NON-NLS-1$ if (fQuickAccessAction != null) { shortCut= fQuickAccessAction.getShortCutString(); //$NON-NLS-1$ } IMenuManager refactorSubmenu= new MenuManager( ActionMessages.getString("RefactorMenu.label") + (shortCut != null ? "\t" + shortCut : ""), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ MENU_ID); if (fEditor != null) { IJavaElement element= SelectionConverter.getInput(fEditor); if (element != null && ActionUtil.isOnBuildPath(element)) { refactorSubmenu.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { refactorMenuShown(manager); } }); refactorSubmenu.add(fNoActionAvailable); menu.appendToGroup(fGroupName, refactorSubmenu); } else { refactorSubmenu.add(fNoActionAvailable); menu.appendToGroup(fGroupName, refactorSubmenu); } } else { if (fillRefactorMenu(refactorSubmenu) > 0) menu.appendToGroup(fGroupName, refactorSubmenu); } } private int fillRefactorMenu(IMenuManager refactorSubmenu) { int added= 0; refactorSubmenu.add(new Separator(GROUP_REORG)); added+= addAction(refactorSubmenu, fRenameAction); added+= addAction(refactorSubmenu, fMoveAction); added+= addAction(refactorSubmenu, fModifyParametersAction); added+= addAction(refactorSubmenu, fConvertAnonymousToNestedAction); added+= addAction(refactorSubmenu, fConvertNestedToTopAction); refactorSubmenu.add(new Separator(GROUP_TYPE)); added+= addAction(refactorSubmenu, fPullUpAction); added+= addAction(refactorSubmenu, fPushDownAction); added+= addAction(refactorSubmenu, fExtractInterfaceAction); added+= addAction(refactorSubmenu, fChangeTypeAction); added+= addAction(refactorSubmenu, fUseSupertypeAction); refactorSubmenu.add(new Separator(GROUP_CODING)); added+= addAction(refactorSubmenu, fInlineAction); added+= addAction(refactorSubmenu, fExtractMethodAction); added+= addAction(refactorSubmenu, fExtractTempAction); added+= addAction(refactorSubmenu, fExtractConstantAction); added+= addAction(refactorSubmenu, fIntroduceParameterAction); added+= addAction(refactorSubmenu, fIntroduceFactoryAction); added+= addAction(refactorSubmenu, fConvertLocalToFieldAction); added+= addAction(refactorSubmenu, fSelfEncapsulateField); return added; } private int addAction(IMenuManager menu, IAction action) { if (action != null && action.isEnabled()) { menu.add(action); return 1; } return 0; } private void refactorMenuShown(final IMenuManager refactorSubmenu) { // we know that we have an MenuManager since we created it in // addRefactorSubmenu. Menu menu= ((MenuManager)refactorSubmenu).getMenu(); menu.addMenuListener(new MenuAdapter() { public void menuHidden(MenuEvent e) { refactorMenuHidden(refactorSubmenu); } }); ITextSelection textSelection= (ITextSelection)fEditor.getSelectionProvider().getSelection(); JavaTextSelection javaSelection= new JavaTextSelection( getEditorInput(), getDocument(), textSelection.getOffset(), textSelection.getLength()); for (Iterator iter= fEditorActions.iterator(); iter.hasNext(); ) { SelectionDispatchAction action= (SelectionDispatchAction)iter.next(); action.update(javaSelection); } refactorSubmenu.removeAll(); if (fillRefactorMenu(refactorSubmenu) == 0) refactorSubmenu.add(fNoActionAvailable); } private void refactorMenuHidden(IMenuManager manager) { ITextSelection textSelection= (ITextSelection)fEditor.getSelectionProvider().getSelection(); for (Iterator iter= fEditorActions.iterator(); iter.hasNext(); ) { SelectionDispatchAction action= (SelectionDispatchAction)iter.next(); action.update(textSelection); } } private IJavaElement getEditorInput() { return JavaPlugin.getDefault().getWorkingCopyManager().getWorkingCopy( fEditor.getEditorInput()); } private IDocument getDocument() { return JavaPlugin.getDefault().getCompilationUnitDocumentProvider(). getDocument(fEditor.getEditorInput()); } private void fillQuickMenu(IMenuManager menu) { if (fEditor != null) { IJavaElement element= SelectionConverter.getInput(fEditor); if (element == null || !ActionUtil.isOnBuildPath(element)) { menu.add(fNoActionAvailable); return; } ITextSelection textSelection= (ITextSelection)fEditor.getSelectionProvider().getSelection(); JavaTextSelection javaSelection= new JavaTextSelection( getEditorInput(), getDocument(), textSelection.getOffset(), textSelection.getLength()); for (Iterator iter= fEditorActions.iterator(); iter.hasNext(); ) { ((SelectionDispatchAction)iter.next()).update(javaSelection); } fillRefactorMenu(menu); for (Iterator iter= fEditorActions.iterator(); iter.hasNext(); ) { ((SelectionDispatchAction)iter.next()).update(textSelection); } } else { fillRefactorMenu(menu); } } }
52,773
Bug 52773 Check how refactorings handle non Java errors [refactoring]
Set Compiler settings to default Turn on Javadoc/Missing Javadoc comments "warning/public/check" Create new class: public class Test { private String fValue; void a() { System.out.println(fValue); } } Now invoke SEF on fValue. Click on "Preview>"
closed fixed
f43f57a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T17:45:47Z
2004-02-22T17:13:20Z
org.eclipse.jdt.ui/core
52,773
Bug 52773 Check how refactorings handle non Java errors [refactoring]
Set Compiler settings to default Turn on Javadoc/Missing Javadoc comments "warning/public/check" Create new class: public class Test { private String fValue; void a() { System.out.println(fValue); } } Now invoke SEF on fValue. Click on "Preview>"
closed fixed
f43f57a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-07T17:45:47Z
2004-02-22T17:13:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractConstantRefactoring.java
47,315
Bug 47315 Add quick fix for remove an unused @ Javadoc tag. [quick fix]
The 3.0.m5 Javadoc warnings are *great* and will improve our Javadocs. Could we hae quick fixes for the new warnings when possible. For example: when a @throws is no longer valid, a quick fix to remove the comment would be great. Version 3.0.m5.
resolved fixed
17e1fb1
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-08T17:04:55Z
2003-11-23T20:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/JavadocTagsSubProcessor.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.text.edits.InsertEdit; import org.eclipse.text.edits.TextEdit; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.core.dom.rewrite.ListRewrite; import org.eclipse.jdt.ui.CodeGeneration; import org.eclipse.jdt.ui.text.java.IInvocationContext; import org.eclipse.jdt.ui.text.java.IProblemLocation; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil; import org.eclipse.jdt.internal.corext.util.Strings; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.JavaUIStatus; /** * */ public class JavadocTagsSubProcessor { public static void getMissingJavadocCommentProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ASTNode node= problem.getCoveringNode(context.getASTRoot()); if (node == null) { return; } BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(node); if (declaration == null) { return; } ICompilationUnit cu= context.getCompilationUnit(); ITypeBinding binding= Bindings.getBindingOfParentType(declaration); if (binding == null) { return; } if (declaration instanceof MethodDeclaration) { MethodDeclaration methodDecl= (MethodDeclaration) declaration; IMethodBinding methodBinding= methodDecl.resolveBinding(); if (methodBinding != null) { methodBinding= Bindings.findDeclarationInHierarchy(binding, methodBinding.getName(), methodBinding.getParameterTypes()); } String string= CodeGeneration.getMethodComment(cu, binding.getName(), methodDecl, methodBinding, String.valueOf('\n')); if (string != null) { String label= CorrectionMessages.getString("JavadocTagsSubProcessor.addjavadoc.method.description"); //$NON-NLS-1$ proposals.add(getNewJavadocTagProposal(cu, declaration.getStartPosition(), string, label)); } } else if (declaration instanceof TypeDeclaration) { String typeQualifiedName= Bindings.getTypeQualifiedName(binding); String string= CodeGeneration.getTypeComment(cu, typeQualifiedName, String.valueOf('\n')); if (string != null) { String label= CorrectionMessages.getString("JavadocTagsSubProcessor.addjavadoc.type.description"); //$NON-NLS-1$ proposals.add(getNewJavadocTagProposal(cu, declaration.getStartPosition(), string, label)); } } else if (declaration instanceof FieldDeclaration) { String comment= "/**\n *\n */\n"; //$NON-NLS-1$ List fragments= ((FieldDeclaration)declaration).fragments(); if (fragments != null && fragments.size() > 0) { VariableDeclaration decl= (VariableDeclaration)fragments.get(0); String fieldName= decl.getName().getIdentifier(); String typeName= binding.getName(); comment= CodeGeneration.getFieldComment(cu, typeName, fieldName, String.valueOf('\n')); } String label= CorrectionMessages.getString("JavadocTagsSubProcessor.addjavadoc.field.description"); //$NON-NLS-1$ proposals.add(getNewJavadocTagProposal(cu, declaration.getStartPosition(), comment, label)); } } private static CUCorrectionProposal getNewJavadocTagProposal(ICompilationUnit cu, final int insertPosition, final String comment, String label) { Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVADOCTAG); return new CUCorrectionProposal(label, cu, 1, image) { protected void addEdits(IDocument document, TextEdit rootEdit) throws CoreException { try { String lineDelimiter= TextUtilities.getDefaultLineDelimiter(document); int tabWidth= CodeFormatterUtil.getTabWidth(); IRegion region= document.getLineInformationOfOffset(insertPosition); String lineContent= document.get(region.getOffset(), region.getLength()); String indentString= Strings.getIndentString(lineContent, tabWidth); String str= Strings.changeIndent(comment, 0, tabWidth, indentString, lineDelimiter); InsertEdit edit= new InsertEdit(insertPosition, str); rootEdit.addChild(edit); //$NON-NLS-1$ if (comment.charAt(comment.length() - 1) != '\n') { rootEdit.addChild(new InsertEdit(insertPosition, lineDelimiter)); rootEdit.addChild(new InsertEdit(insertPosition, indentString)); } } catch (BadLocationException e) { throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e)); } } }; } public static void getMissingJavadocTagProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { ASTNode node= problem.getCoveringNode(context.getASTRoot()); if (node == null) { return; } BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(node); if (!(declaration instanceof MethodDeclaration)) { return; } Javadoc javadoc= declaration.getJavadoc(); if (javadoc == null) { return; } MethodDeclaration methodDecl= (MethodDeclaration) declaration; AST ast= javadoc.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); ListRewrite tagsRewriter= rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY); Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVADOCTAG); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", context.getCompilationUnit(), rewrite, 1, image); //$NON-NLS-1$ switch (problem.getProblemId()) { case IProblem.JavadocMissingParamTag: { String name= ASTNodes.asString(node); proposal.setDisplayName(CorrectionMessages.getString("JavadocTagsSubProcessor.addjavadoc.paramtag.description")); //$NON-NLS-1$ TagElement newTag= ast.newTagElement(); newTag.setTagName("@param"); //$NON-NLS-1$ newTag.fragments().add(ast.newSimpleName(name)); insertParamTag(javadoc, tagsRewriter, newTag, node.getParent()); break; } case IProblem.JavadocMissingReturnTag: { proposal.setDisplayName(CorrectionMessages.getString("JavadocTagsSubProcessor.addjavadoc.returntag.description")); //$NON-NLS-1$ TagElement newTag= ast.newTagElement(); newTag.setTagName("@return"); //$NON-NLS-1$ insertReturnTag(javadoc, tagsRewriter, newTag); break; } case IProblem.JavadocMissingThrowsTag: { proposal.setDisplayName(CorrectionMessages.getString("JavadocTagsSubProcessor.addjavadoc.throwstag.description")); //$NON-NLS-1$ TagElement newTag= ast.newTagElement(); newTag.setTagName("@throws"); //$NON-NLS-1$ insertThrowsTag(javadoc, tagsRewriter, newTag, node); break; } default: return; } proposals.add(proposal); rewrite= ASTRewrite.create(ast); tagsRewriter= rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY); String label= CorrectionMessages.getString("JavadocTagsSubProcessor.addjavadoc.allmissing.description"); //$NON-NLS-1$ ASTRewriteCorrectionProposal addAllMissing= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image); //$NON-NLS-1$ List list= methodDecl.parameters(); for (int i= list.size() - 1; i >= 0 ; i--) { SingleVariableDeclaration decl= (SingleVariableDeclaration) list.get(i); String name= decl.getName().getIdentifier(); if (findTag(javadoc, "@param", name) == null) { //$NON-NLS-1$ TagElement newTag= ast.newTagElement(); newTag.setTagName("@param"); //$NON-NLS-1$ newTag.fragments().add(ast.newSimpleName(name)); insertParamTag(javadoc, tagsRewriter, newTag, decl); } } if (!methodDecl.isConstructor()) { Type type= methodDecl.getReturnType(); if (!type.isPrimitiveType() || (((PrimitiveType) type).getPrimitiveTypeCode() != PrimitiveType.VOID)) { if (findTag(javadoc, "@return", null) == null) { //$NON-NLS-1$ TagElement newTag= ast.newTagElement(); newTag.setTagName("@return"); //$NON-NLS-1$ insertReturnTag(javadoc, tagsRewriter, newTag); } } } List throwsExceptions= methodDecl.thrownExceptions(); for (int i= throwsExceptions.size() - 1; i >= 0 ; i--) { Name exception= (Name) throwsExceptions.get(i); ITypeBinding binding= exception.resolveTypeBinding(); if (binding != null) { String name= binding.getName(); if (findThrowsTag(javadoc, name) == null) { TagElement newTag= ast.newTagElement(); newTag.setTagName("@throws"); //$NON-NLS-1$ newTag.fragments().add(ast.newSimpleName(name)); insertThrowsTag(javadoc, tagsRewriter, newTag, exception); } } } proposals.add(addAllMissing); } public static TagElement findTag(Javadoc javadoc, String name, String arg) { List tags= javadoc.tags(); int nTags= tags.size(); for (int i= 0; i < nTags; i++) { TagElement curr= (TagElement) tags.get(i); if (name.equals(curr.getTagName())) { if (arg != null) { String argument= getArgument(curr); if (arg.equals(argument)) { return curr; } } else { return curr; } } } return null; } private static TagElement findThrowsTag(Javadoc javadoc, String arg) { List tags= javadoc.tags(); int nTags= tags.size(); for (int i= 0; i < nTags; i++) { TagElement curr= (TagElement) tags.get(i); String currName= curr.getTagName(); if ("@throws".equals(currName) || "@exception".equals(currName)) { //$NON-NLS-1$//$NON-NLS-2$ String argument= getArgument(curr); if (arg.equals(argument)) { return curr; } } } return null; } private static void insertThrowsTag(Javadoc javadoc, ListRewrite rewriter, TagElement newElement, ASTNode node) { Set previousArgs= new HashSet(); List list= ((MethodDeclaration) javadoc.getParent()).thrownExceptions(); for (int i= 0; i < list.size() && node != list.get(i); i++) { Name curr= (Name) list.get(i); previousArgs.add(ASTNodes.getSimpleNameIdentifier(curr)); } List tags= rewriter.getRewrittenList(); ASTNode before= null; for (int i= tags.size() - 1; i >= 0; i--) { TagElement curr= (TagElement) tags.get(i); String tagName= curr.getTagName(); if ("@throws".equals(tagName) || "@exception".equals(tagName)) { //$NON-NLS-1$//$NON-NLS-2$ String arg= getArgument(curr); if (arg != null && previousArgs.contains(arg)) { rewriter.insertAfter(newElement, curr, null); return; } before= curr; } } if (before != null) { rewriter.insertBefore(newElement, before, null); } else { rewriter.insertLast(newElement, null); } } private static void insertReturnTag(Javadoc javadoc, ListRewrite rewriter, TagElement newElement) { List tags= rewriter.getRewrittenList(); ASTNode before= null; for (int i= tags.size() - 1; i >= 0; i--) { TagElement curr= (TagElement) tags.get(i); String tagName=curr.getTagName(); if ("@throws".equals(tagName) || "@exception".equals(tagName)) { //$NON-NLS-1$ //$NON-NLS-2$ before= curr; } else if ("@param".equals(tagName)) { //$NON-NLS-1$ break; } } if (before != null) { rewriter.insertBefore(newElement, before, null); } else { rewriter.insertLast(newElement, null); } } private static void insertParamTag(Javadoc javadoc, ListRewrite rewriter, TagElement newElement, ASTNode node) { Set previousArgs= new HashSet(); List list= ((MethodDeclaration) javadoc.getParent()).parameters(); for (int i= 0; i < list.size() && (list.get(i) != node); i++) { SingleVariableDeclaration curr= (SingleVariableDeclaration) list.get(i); previousArgs.add(curr.getName().getIdentifier()); } List tags= rewriter.getRewrittenList(); for (int i= tags.size() - 1; i >= 0; i--) { TagElement curr= (TagElement) tags.get(i); if ("@param".equals(curr.getTagName())) { //$NON-NLS-1$ String arg= getArgument(curr); if (arg != null && previousArgs.contains(arg)) { rewriter.insertAfter(newElement, curr, null); return; } } } if (!tags.isEmpty()) { TagElement first= (TagElement) tags.get(0); if (first.getTagName() == null) { rewriter.insertAfter(newElement, first, null); return; } } rewriter.insertFirst(newElement, null); } private static String getArgument(TagElement curr) { List fragments= curr.fragments(); if (!fragments.isEmpty()) { Object first= fragments.get(0); if (first instanceof Name) { return ASTNodes.getSimpleNameIdentifier((Name) first); } } return null; } }
47,315
Bug 47315 Add quick fix for remove an unused @ Javadoc tag. [quick fix]
The 3.0.m5 Javadoc warnings are *great* and will improve our Javadocs. Could we hae quick fixes for the new warnings when possible. For example: when a @throws is no longer valid, a quick fix to remove the comment would be great. Version 3.0.m5.
resolved fixed
17e1fb1
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-08T17:04:55Z
2003-11-23T20:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickFixProcessor.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.ui.text.java.IInvocationContext; import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal; import org.eclipse.jdt.ui.text.java.IProblemLocation; import org.eclipse.jdt.ui.text.java.IQuickFixProcessor; /** */ public class QuickFixProcessor implements IQuickFixProcessor { public boolean hasCorrections(ICompilationUnit cu, int problemId) { switch (problemId) { case IProblem.UnterminatedString: case IProblem.UnusedImport: case IProblem.DuplicateImport: case IProblem.CannotImportPackage: case IProblem.ConflictingImport: case IProblem.ImportNotFound: case IProblem.UndefinedMethod: case IProblem.UndefinedConstructor: case IProblem.ParameterMismatch: case IProblem.MethodButWithConstructorName: case IProblem.UndefinedField: case IProblem.UndefinedName: case IProblem.PublicClassMustMatchFileName: case IProblem.PackageIsNotExpectedPackage: case IProblem.UndefinedType: case IProblem.FieldTypeNotFound: case IProblem.ArgumentTypeNotFound: case IProblem.ReturnTypeNotFound: case IProblem.SuperclassNotFound: case IProblem.ExceptionTypeNotFound: case IProblem.InterfaceNotFound: case IProblem.TypeMismatch: case IProblem.UnhandledException: case IProblem.UnreachableCatch: case IProblem.InvalidCatchBlockSequence: case IProblem.VoidMethodReturnsValue: case IProblem.ShouldReturnValue: case IProblem.MissingReturnType: case IProblem.NonExternalizedStringLiteral: case IProblem.NonStaticAccessToStaticField: case IProblem.NonStaticAccessToStaticMethod: case IProblem.StaticMethodRequested: case IProblem.NonStaticFieldFromStaticInvocation: case IProblem.InstanceMethodDuringConstructorInvocation: case IProblem.InstanceFieldDuringConstructorInvocation: case IProblem.NotVisibleMethod: case IProblem.NotVisibleConstructor: case IProblem.NotVisibleType: case IProblem.SuperclassNotVisible: case IProblem.InterfaceNotVisible: case IProblem.FieldTypeNotVisible: case IProblem.ArgumentTypeNotVisible: case IProblem.ReturnTypeNotVisible: case IProblem.ExceptionTypeNotVisible: case IProblem.NotVisibleField: case IProblem.ImportNotVisible: case IProblem.BodyForAbstractMethod: case IProblem.AbstractMethodInAbstractClass: case IProblem.AbstractMethodMustBeImplemented: case IProblem.BodyForNativeMethod: case IProblem.OuterLocalMustBeFinal: case IProblem.UninitializedLocalVariable: case IProblem.UndefinedConstructorInDefaultConstructor: case IProblem.UnhandledExceptionInDefaultConstructor: case IProblem.NotVisibleConstructorInDefaultConstructor: case IProblem.FieldTypeAmbiguous: case IProblem.ArgumentTypeAmbiguous: case IProblem.ExceptionTypeAmbiguous: case IProblem.ReturnTypeAmbiguous: case IProblem.SuperclassAmbiguous: case IProblem.InterfaceAmbiguous: case IProblem.AmbiguousType: case IProblem.UnusedPrivateMethod: case IProblem.UnusedPrivateConstructor: case IProblem.UnusedPrivateField: case IProblem.UnusedPrivateType: case IProblem.LocalVariableIsNeverUsed: case IProblem.ArgumentIsNeverUsed: case IProblem.MethodRequiresBody: case IProblem.NeedToEmulateFieldReadAccess: case IProblem.NeedToEmulateFieldWriteAccess: case IProblem.NeedToEmulateMethodAccess: case IProblem.NeedToEmulateConstructorAccess: case IProblem.SuperfluousSemicolon: case IProblem.UnnecessaryCast: case IProblem.UnnecessaryArgumentCast: case IProblem.UnnecessaryInstanceof: case IProblem.IndirectAccessToStaticField: case IProblem.IndirectAccessToStaticMethod: case IProblem.Task: case IProblem.UnusedMethodDeclaredThrownException: case IProblem.UnusedConstructorDeclaredThrownException: case IProblem.UnqualifiedFieldAccess: case IProblem.JavadocMissing: case IProblem.JavadocMissingParamTag: case IProblem.JavadocMissingReturnTag: case IProblem.JavadocMissingThrowsTag: case IProblem.JavadocUndefinedType: case IProblem.JavadocAmbiguousType: case IProblem.JavadocNotVisibleType: case IProblem.NonBlankFinalLocalAssignment: case IProblem.DuplicateFinalLocalInitialization: case IProblem.FinalFieldAssignment: case IProblem.DuplicateBlankFinalFieldInitialization: case IProblem.AnonymousClassCannotExtendFinalClass: case IProblem.ClassExtendFinalClass: case IProblem.FinalMethodCannotBeOverridden: case IProblem.InheritedMethodReducesVisibility: case IProblem.MethodReducesVisibility: case IProblem.OverridingNonVisibleMethod: case IProblem.CannotOverrideAStaticMethodWithAnInstanceMethod: case IProblem.CannotHideAnInstanceMethodWithAStaticMethod: case IProblem.LocalVariableHidingLocalVariable: case IProblem.LocalVariableHidingField: case IProblem.FieldHidingLocalVariable: case IProblem.FieldHidingField: case IProblem.ArgumentHidingLocalVariable: case IProblem.ArgumentHidingField: case IProblem.IllegalModifierForInterfaceMethod: case IProblem.IllegalModifierForInterface: case IProblem.IllegalModifierForClass: case IProblem.IllegalModifierForInterfaceField: case IProblem.IllegalModifierForMemberInterface: case IProblem.IllegalModifierForMemberClass: case IProblem.IllegalModifierForLocalClass: case IProblem.IllegalModifierForArgument: case IProblem.IllegalModifierForField: case IProblem.IllegalModifierForMethod: case IProblem.IllegalModifierForVariable: case IProblem.IllegalVisibilityModifierForInterfaceMemberType: case IProblem.IncompatibleReturnType: case IProblem.IncompatibleExceptionInThrowsClause: case IProblem.NoMessageSendOnArrayType: return true; default: return false; } } private static int moveBack(int offset, int start, String ignoreCharacters, ICompilationUnit cu) { try { IBuffer buf= cu.getBuffer(); while (offset >= start) { if (ignoreCharacters.indexOf(buf.getChar(offset - 1)) == -1) { //$NON-NLS-1$ return offset; } offset--; } } catch(JavaModelException e) { } return start; } /* (non-Javadoc) * @see IAssistProcessor#getCorrections(org.eclipse.jdt.internal.ui.text.correction.IAssistContext, org.eclipse.jdt.internal.ui.text.correction.IProblemLocation[]) */ public IJavaCompletionProposal[] getCorrections(IInvocationContext context, IProblemLocation[] locations) throws CoreException { if (locations == null || locations.length == 0) { return null; } HashSet handledProblems= new HashSet(locations.length); ArrayList resultingCollections= new ArrayList(); for (int i= 0; i < locations.length; i++) { IProblemLocation curr= locations[i]; Integer id= new Integer(curr.getProblemId()); if (handledProblems.add(id)) { process(context, curr, resultingCollections); } } return (IJavaCompletionProposal[]) resultingCollections.toArray(new IJavaCompletionProposal[resultingCollections.size()]); } private void process(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { int id= problem.getProblemId(); if (id == 0) { // no proposals for none-problem locations return; } switch (id) { case IProblem.UnterminatedString: String quoteLabel= CorrectionMessages.getString("JavaCorrectionProcessor.addquote.description"); //$NON-NLS-1$ int pos= moveBack(problem.getOffset() + problem.getLength(), problem.getOffset(), "\n\r", context.getCompilationUnit()); //$NON-NLS-1$ proposals.add(new ReplaceCorrectionProposal(quoteLabel, context.getCompilationUnit(), pos, 0, "\"", 0)); //$NON-NLS-1$ break; case IProblem.UnusedImport: case IProblem.DuplicateImport: case IProblem.CannotImportPackage: case IProblem.ConflictingImport: ReorgCorrectionsSubProcessor.removeImportStatementProposals(context, problem, proposals); break; case IProblem.ImportNotFound: ReorgCorrectionsSubProcessor.importNotFoundProposals(context, problem, proposals); ReorgCorrectionsSubProcessor.removeImportStatementProposals(context, problem, proposals); break; case IProblem.UndefinedMethod: UnresolvedElementsSubProcessor.getMethodProposals(context, problem, false, proposals); break; case IProblem.UndefinedConstructor: UnresolvedElementsSubProcessor.getConstructorProposals(context, problem, proposals); break; case IProblem.ParameterMismatch: UnresolvedElementsSubProcessor.getMethodProposals(context, problem, true, proposals); break; case IProblem.MethodButWithConstructorName: ReturnTypeSubProcessor.addMethodWithConstrNameProposals(context, problem, proposals); break; case IProblem.UndefinedField: case IProblem.UndefinedName: UnresolvedElementsSubProcessor.getVariableProposals(context, problem, proposals); break; case IProblem.FieldTypeAmbiguous: case IProblem.ArgumentTypeAmbiguous: case IProblem.ExceptionTypeAmbiguous: case IProblem.ReturnTypeAmbiguous: case IProblem.SuperclassAmbiguous: case IProblem.InterfaceAmbiguous: case IProblem.AmbiguousType: case IProblem.JavadocAmbiguousType: UnresolvedElementsSubProcessor.getAmbiguosTypeReferenceProposals(context, problem, proposals); break; case IProblem.PublicClassMustMatchFileName: ReorgCorrectionsSubProcessor.getWrongTypeNameProposals(context, problem, proposals); break; case IProblem.PackageIsNotExpectedPackage: ReorgCorrectionsSubProcessor.getWrongPackageDeclNameProposals(context, problem, proposals); break; case IProblem.UndefinedType: case IProblem.FieldTypeNotFound: case IProblem.ArgumentTypeNotFound: case IProblem.ReturnTypeNotFound: case IProblem.SuperclassNotFound: case IProblem.ExceptionTypeNotFound: case IProblem.InterfaceNotFound: case IProblem.JavadocUndefinedType: UnresolvedElementsSubProcessor.getTypeProposals(context, problem, proposals); break; case IProblem.TypeMismatch: TypeMismatchSubProcessor.addTypeMismatchProposals(context, problem, proposals); break; case IProblem.IncompatibleReturnType: TypeMismatchSubProcessor.addIncompatibleReturnTypeProposals(context, problem, proposals); break; case IProblem.IncompatibleExceptionInThrowsClause: TypeMismatchSubProcessor.addIncompatibleThrowsProposals(context, problem, proposals); break; case IProblem.UnhandledException: LocalCorrectionsSubProcessor.addUncaughtExceptionProposals(context, problem, proposals); break; case IProblem.UnreachableCatch: case IProblem.InvalidCatchBlockSequence: LocalCorrectionsSubProcessor.addUnreachableCatchProposals(context, problem, proposals); break; case IProblem.VoidMethodReturnsValue: ReturnTypeSubProcessor.addVoidMethodReturnsProposals(context, problem, proposals); break; case IProblem.MissingReturnType: ReturnTypeSubProcessor.addMissingReturnTypeProposals(context, problem, proposals); break; case IProblem.ShouldReturnValue: ReturnTypeSubProcessor.addMissingReturnStatementProposals(context, problem, proposals); break; case IProblem.NonExternalizedStringLiteral: LocalCorrectionsSubProcessor.addNLSProposals(context, problem, proposals); break; case IProblem.NonStaticAccessToStaticField: case IProblem.NonStaticAccessToStaticMethod: case IProblem.IndirectAccessToStaticField: case IProblem.IndirectAccessToStaticMethod: LocalCorrectionsSubProcessor.addCorrectAccessToStaticProposals(context, problem, proposals); break; case IProblem.StaticMethodRequested: case IProblem.NonStaticFieldFromStaticInvocation: case IProblem.InstanceMethodDuringConstructorInvocation: case IProblem.InstanceFieldDuringConstructorInvocation: ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_STATIC, 5); break; case IProblem.NonBlankFinalLocalAssignment: case IProblem.DuplicateFinalLocalInitialization: case IProblem.FinalFieldAssignment: case IProblem.DuplicateBlankFinalFieldInitialization: case IProblem.AnonymousClassCannotExtendFinalClass: case IProblem.ClassExtendFinalClass: ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_FINAL, 9); break; case IProblem.InheritedMethodReducesVisibility: case IProblem.MethodReducesVisibility: case IProblem.OverridingNonVisibleMethod: ModifierCorrectionSubProcessor.addChangeOverriddenModfierProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_VISIBLE); break; case IProblem.FinalMethodCannotBeOverridden: ModifierCorrectionSubProcessor.addChangeOverriddenModfierProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_FINAL); break; case IProblem.CannotOverrideAStaticMethodWithAnInstanceMethod: ModifierCorrectionSubProcessor.addChangeOverriddenModfierProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_STATIC); break; case IProblem.CannotHideAnInstanceMethodWithAStaticMethod: case IProblem.IllegalModifierForInterfaceMethod: case IProblem.IllegalModifierForInterface: case IProblem.IllegalModifierForClass: case IProblem.IllegalModifierForInterfaceField: case IProblem.IllegalModifierForMemberInterface: case IProblem.IllegalModifierForMemberClass: case IProblem.IllegalModifierForLocalClass: case IProblem.IllegalModifierForArgument: case IProblem.IllegalModifierForField: case IProblem.IllegalModifierForMethod: case IProblem.IllegalModifierForVariable: case IProblem.IllegalVisibilityModifierForInterfaceMemberType: ModifierCorrectionSubProcessor.addRemoveInvalidModfiersProposal(context, problem, proposals, 5); break; case IProblem.NotVisibleMethod: case IProblem.NotVisibleConstructor: case IProblem.NotVisibleType: case IProblem.SuperclassNotVisible: case IProblem.InterfaceNotVisible: case IProblem.FieldTypeNotVisible: case IProblem.ArgumentTypeNotVisible: case IProblem.ReturnTypeNotVisible: case IProblem.ExceptionTypeNotVisible: case IProblem.NotVisibleField: case IProblem.ImportNotVisible: case IProblem.JavadocNotVisibleType: ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_VISIBLE, 10); break; case IProblem.BodyForAbstractMethod: case IProblem.AbstractMethodInAbstractClass: ModifierCorrectionSubProcessor.addAbstractMethodProposals(context, problem, proposals); break; case IProblem.AbstractMethodMustBeImplemented: LocalCorrectionsSubProcessor.addUnimplementedMethodsProposals(context, problem, proposals); break; case IProblem.BodyForNativeMethod: ModifierCorrectionSubProcessor.addNativeMethodProposals(context, problem, proposals); break; case IProblem.MethodRequiresBody: ModifierCorrectionSubProcessor.addMethodRequiresBodyProposals(context, problem, proposals); break; case IProblem.OuterLocalMustBeFinal: ModifierCorrectionSubProcessor.addNonFinalLocalProposal(context, problem, proposals); break; case IProblem.UninitializedLocalVariable: LocalCorrectionsSubProcessor.addUninitializedLocalVariableProposal(context, problem, proposals); break; case IProblem.UnhandledExceptionInDefaultConstructor: case IProblem.UndefinedConstructorInDefaultConstructor: case IProblem.NotVisibleConstructorInDefaultConstructor: LocalCorrectionsSubProcessor.addConstructorFromSuperclassProposal(context, problem, proposals); break; case IProblem.UnusedPrivateMethod: case IProblem.UnusedPrivateConstructor: case IProblem.UnusedPrivateField: case IProblem.UnusedPrivateType: case IProblem.LocalVariableIsNeverUsed: case IProblem.ArgumentIsNeverUsed: LocalCorrectionsSubProcessor.addUnusedMemberProposal(context, problem, proposals); break; case IProblem.NeedToEmulateFieldReadAccess: case IProblem.NeedToEmulateFieldWriteAccess: case IProblem.NeedToEmulateMethodAccess: case IProblem.NeedToEmulateConstructorAccess: ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_PRIVATE, 5); break; case IProblem.SuperfluousSemicolon: LocalCorrectionsSubProcessor.addSuperfluousSemicolonProposal(context, problem, proposals); break; case IProblem.UnnecessaryCast: case IProblem.UnnecessaryArgumentCast: LocalCorrectionsSubProcessor.addUnnecessaryCastProposal(context, problem, proposals); break; case IProblem.UnnecessaryInstanceof: LocalCorrectionsSubProcessor.addUnnecessaryInstanceofProposal(context, problem, proposals); break; case IProblem.UnusedMethodDeclaredThrownException: case IProblem.UnusedConstructorDeclaredThrownException: LocalCorrectionsSubProcessor.addUnnecessaryThrownExceptionProposal(context, problem, proposals); break; case IProblem.UnqualifiedFieldAccess: LocalCorrectionsSubProcessor.addUnqualifiedFieldAccessProposal(context, problem, proposals); break; case IProblem.Task: proposals.add(new TaskMarkerProposal(context.getCompilationUnit(), problem, 10)); break; case IProblem.JavadocMissing: JavadocTagsSubProcessor.getMissingJavadocCommentProposals(context, problem, proposals); break; case IProblem.JavadocMissingParamTag: case IProblem.JavadocMissingReturnTag: case IProblem.JavadocMissingThrowsTag: JavadocTagsSubProcessor.getMissingJavadocTagProposals(context, problem, proposals); break; case IProblem.LocalVariableHidingLocalVariable: case IProblem.LocalVariableHidingField: case IProblem.FieldHidingLocalVariable: case IProblem.FieldHidingField: case IProblem.ArgumentHidingLocalVariable: case IProblem.ArgumentHidingField: LocalCorrectionsSubProcessor.addHidingVariablesProposals(context, problem, proposals); break; case IProblem.NoMessageSendOnArrayType: UnresolvedElementsSubProcessor.getArrayAccessProposals(context, problem, proposals); break; default: } } }
61,383
Bug 61383 [preferences] Syntax highlighting list not updated on Restore Defaults
- enable advanced highlighting -> advanced highightings appear in list - Restore Defaults -> advanced highlighting becomes disabled but the highlightings are not removed from the list
resolved fixed
79b47a1
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-10T07:40:40Z
2004-05-07T14:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorPreferencePage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Preferences; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.IColorProvider; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchViewerSorter; import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.ChainedPreferenceStore; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer; import org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlighting; import org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightingManager; import org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightings; import org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightingManager.HighlightedRange; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.PreferencesAdapter; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; /** * The page for setting the editor options. */ public class JavaEditorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { /** * Item in the highlighting color list. * * @since 3.0 */ private class HighlightingColorListItem { /** Display name */ private String fDisplayName; /** Color preference key */ private String fColorKey; /** Bold preference key */ private String fBoldKey; /** Italic preference key */ private String fItalicKey; /** Item color */ private Color fItemColor; /** * Initialize the item with the given values. * * @param displayName the display name * @param colorKey the color preference key * @param boldKey the bold preference key * @param italicKey the italic preference key * @param itemColor the item color */ public HighlightingColorListItem(String displayName, String colorKey, String boldKey, String italicKey, Color itemColor) { fDisplayName= displayName; fColorKey= colorKey; fBoldKey= boldKey; fItalicKey= italicKey; fItemColor= itemColor; } /** * @return the bold preference key */ public String getBoldKey() { return fBoldKey; } /** * @return the bold preference key */ public String getItalicKey() { return fItalicKey; } /** * @return the color preference key */ public String getColorKey() { return fColorKey; } /** * @return the display name */ public String getDisplayName() { return fDisplayName; } /** * @return the item color */ public Color getItemColor() { return fItemColor; } } /** * Color list label provider. * * @since 3.0 */ private class ColorListLabelProvider extends LabelProvider implements IColorProvider { /* * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) */ public String getText(Object element) { return ((HighlightingColorListItem)element).getDisplayName(); } /* * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object) */ public Color getForeground(Object element) { return ((HighlightingColorListItem)element).getItemColor(); } /* * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object) */ public Color getBackground(Object element) { return null; } } /** * Color list content provider. * * @since 3.0 */ private class ColorListContentProvider implements IStructuredContentProvider { /* * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) */ public Object[] getElements(Object inputElement) { return ((java.util.List)inputElement).toArray(); } /* * @see org.eclipse.jface.viewers.IContentProvider#dispose() */ public void dispose() { } /* * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object) */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } } private static final String BOLD= PreferenceConstants.EDITOR_BOLD_SUFFIX; /** * Preference key suffix for italic preferences. * @since 3.0 */ private static final String ITALIC= PreferenceConstants.EDITOR_ITALIC_SUFFIX; private static final String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS; private static final String DELIMITER= PreferencesMessages.getString("JavaEditorPreferencePage.navigation.delimiter"); //$NON-NLS-1$ /** The keys of the overlay store. */ private final String[][] fSyntaxColorListModel= new String[][] { { PreferencesMessages.getString("JavaEditorPreferencePage.multiLineComment"), PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.singleLineComment"), PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.returnKeyword"), PreferenceConstants.EDITOR_JAVA_KEYWORD_RETURN_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.keywords"), PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.strings"), PreferenceConstants.EDITOR_STRING_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.methodNames"), PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.operators"), PreferenceConstants.EDITOR_JAVA_OPERATOR_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.others"), PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaCommentTaskTags"), PreferenceConstants.EDITOR_TASK_TAG_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocKeywords"), PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocHtmlTags"), PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocLinks"), PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR }, //$NON-NLS-1$ { PreferencesMessages.getString("JavaEditorPreferencePage.javaDocOthers"), PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR } //$NON-NLS-1$ }; private final String[][] fAppearanceColorListModel= new String[][] { {PreferencesMessages.getString("JavaEditorPreferencePage.lineNumberForegroundColor"), AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR, null}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.matchingBracketsHighlightColor2"), PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, null}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.currentLineHighlighColor"), AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR, null}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.printMarginColor2"), AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR, null}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.findScopeColor2"), PreferenceConstants.EDITOR_FIND_SCOPE_COLOR, null}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.linkColor2"), PreferenceConstants.EDITOR_LINK_COLOR, null}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.selectionForegroundColor"), AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_DEFAULT_COLOR}, //$NON-NLS-1$ {PreferencesMessages.getString("JavaEditorPreferencePage.selectionBackgroundColor"), AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_DEFAULT_COLOR}, //$NON-NLS-1$ }; private OverlayPreferenceStore fOverlayStore; private JavaEditorHoverConfigurationBlock fJavaEditorHoverConfigurationBlock; private FoldingConfigurationBlock fFoldingConfigurationBlock; private Map fColorButtons= new HashMap(); private Map fCheckBoxes= new HashMap(); private SelectionListener fCheckBoxListener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { Button button= (Button) e.widget; fOverlayStore.setValue((String) fCheckBoxes.get(button), button.getSelection()); } }; private Map fTextFields= new HashMap(); private ModifyListener fTextFieldListener= new ModifyListener() { public void modifyText(ModifyEvent e) { Text text= (Text) e.widget; fOverlayStore.setValue((String) fTextFields.get(text), text.getText()); } }; private ArrayList fNumberFields= new ArrayList(); private ModifyListener fNumberFieldListener= new ModifyListener() { public void modifyText(ModifyEvent e) { numberFieldChanged((Text) e.widget); } }; private List fAppearanceColorList; private ColorEditor fSyntaxForegroundColorEditor; private ColorEditor fAppearanceColorEditor; private Button fAppearanceColorDefault; private ColorEditor fBackgroundColorEditor; private Button fBackgroundDefaultRadioButton; private Button fBackgroundCustomRadioButton; private Button fBackgroundColorButton; private Button fBoldCheckBox; /** * Check box for italic preference. * @since 3.0 */ private Button fItalicCheckBox; private JavaSourceViewer fPreviewViewer; private Color fBackgroundColor; private Text fBrowserLikeLinksKeyModifierText; private Button fBrowserLikeLinksCheckBox; private StatusInfo fBrowserLikeLinksKeyModifierStatus; /** * Tells whether the fields are initialized. * @since 3.0 */ private boolean fFieldsInitialized= false; /** * List of master/slave listeners when there's a dependency. * * @see #createDependency(Button, String, Control) * @since 3.0 */ private ArrayList fMasterSlaveListeners= new ArrayList(); /** * Highlighting color list * @since 3.0 */ private final java.util.List fHighlightingColorList= new ArrayList(); /** * Highlighting color list viewer * @since 3.0 */ private TableViewer fHighlightingColorListViewer; /** * Color of Semantic Highlighting items in color list (RGB) * @since 3.0 */ private static final int[] SEMANTIC_HIGHLIGHTING_ITEM_COLOR= new int[] { 0, 0, 0x80 }; /** * Semantic Highlighting color list * @since 3.0 */ private java.util.List fSemanticHighlightingColorList= new ArrayList(); /** * Semantic highlighting manager * @since 3.0 */ private SemanticHighlightingManager fSemanticHighlightingManager; /** * Semantic highlighting check-box * @since 3.0 */ private Button fSemanticHighlightingEnabled; /** * Creates a new preference page. */ public JavaEditorPreferencePage() { setDescription(PreferencesMessages.getString("JavaEditorPreferencePage.description")); //$NON-NLS-1$ setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); Color itemColor= JavaPlugin.getDefault().getJavaTextTools().getColorManager().getColor(new RGB(SEMANTIC_HIGHLIGHTING_ITEM_COLOR[0], SEMANTIC_HIGHLIGHTING_ITEM_COLOR[1], SEMANTIC_HIGHLIGHTING_ITEM_COLOR[2])); SemanticHighlighting[] semanticHighlightings= SemanticHighlightings.getSemanticHighlightings(); for (int i= 0, n= semanticHighlightings.length; i < n; i++) fSemanticHighlightingColorList.add(new HighlightingColorListItem(semanticHighlightings[i].getDisplayName(), SemanticHighlightings.getColorPreferenceKey(semanticHighlightings[i]), SemanticHighlightings.getBoldPreferenceKey(semanticHighlightings[i]), SemanticHighlightings.getItalicPreferenceKey(semanticHighlightings[i]), itemColor)); fOverlayStore= new OverlayPreferenceStore(getPreferenceStore(), createOverlayStoreKeys()); } private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() { ArrayList overlayKeys= new ArrayList(); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_FOREGROUND_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_BACKGROUND_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_DEFAULT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_DEFAULT_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH)); for (int i= 0; i < fSyntaxColorListModel.length; i++) { String colorKey= fSyntaxColorListModel[i][1]; overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, colorKey)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, colorKey + BOLD)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, colorKey + ITALIC)); } overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MATCHING_BRACKETS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_USE_CUSTOM_CARETS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_WIDE_CARET)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_QUICKASSIST_LIGHTBULB)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_FIND_SCOPE_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_LINK_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CORRECTION_INDICATION)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SPACES_FOR_TABS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_PASTE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_IMPORTS_ON_PASTE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_STRINGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_BRACKETS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_BRACES)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_JAVADOCS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_WRAP_STRINGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_ESCAPE_STRINGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_HOME_END)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_SEMICOLON)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_TAB)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_OPENING_BRACE)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED)); for (int i= 0, n= fSemanticHighlightingColorList.size(); i < n; i++) { HighlightingColorListItem item= (HighlightingColorListItem) fSemanticHighlightingColorList.get(i); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, item.getColorKey())); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, item.getBoldKey())); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, item.getItalicKey())); } OverlayPreferenceStore.OverlayKey[] keys= new OverlayPreferenceStore.OverlayKey[overlayKeys.size()]; overlayKeys.toArray(keys); return keys; } /* * @see IWorkbenchPreferencePage#init() */ public void init(IWorkbench workbench) { } /* * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); } private void handleSyntaxColorListSelection() { HighlightingColorListItem item= getHighlightingColorListItem(); RGB rgb= PreferenceConverter.getColor(fOverlayStore, item.getColorKey()); fSyntaxForegroundColorEditor.setColorValue(rgb); fBoldCheckBox.setSelection(fOverlayStore.getBoolean(item.getBoldKey())); fItalicCheckBox.setSelection(fOverlayStore.getBoolean(item.getItalicKey())); } private void handleAppearanceColorListSelection() { int i= fAppearanceColorList.getSelectionIndex(); String key= fAppearanceColorListModel[i][1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); fAppearanceColorEditor.setColorValue(rgb); updateAppearanceColorWidgets(fAppearanceColorListModel[i][2]); } private void updateAppearanceColorWidgets(String systemDefaultKey) { if (systemDefaultKey == null) { fAppearanceColorDefault.setSelection(false); fAppearanceColorDefault.setVisible(false); fAppearanceColorEditor.getButton().setEnabled(true); } else { boolean systemDefault= fOverlayStore.getBoolean(systemDefaultKey); fAppearanceColorDefault.setSelection(systemDefault); fAppearanceColorDefault.setVisible(true); fAppearanceColorEditor.getButton().setEnabled(!systemDefault); } } private Control createSyntaxPage(Composite parent) { Composite colorComposite= new Composite(parent, SWT.NONE); colorComposite.setLayout(new GridLayout()); Group backgroundComposite= new Group(colorComposite, SWT.SHADOW_ETCHED_IN); GridLayout layout= new GridLayout(); layout.numColumns= 3; backgroundComposite.setLayout(layout); backgroundComposite.setText(PreferencesMessages.getString("JavaEditorPreferencePage.backgroundColor"));//$NON-NLS-1$ SelectionListener backgroundSelectionListener= new SelectionListener() { public void widgetSelected(SelectionEvent e) { boolean custom= fBackgroundCustomRadioButton.getSelection(); fBackgroundColorButton.setEnabled(custom); fOverlayStore.setValue(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, !custom); } public void widgetDefaultSelected(SelectionEvent e) {} }; fBackgroundDefaultRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); fBackgroundDefaultRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.systemDefault")); //$NON-NLS-1$ fBackgroundDefaultRadioButton.addSelectionListener(backgroundSelectionListener); fBackgroundCustomRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); fBackgroundCustomRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.custom")); //$NON-NLS-1$ fBackgroundCustomRadioButton.addSelectionListener(backgroundSelectionListener); fBackgroundColorEditor= new ColorEditor(backgroundComposite); fBackgroundColorButton= fBackgroundColorEditor.getButton(); fSemanticHighlightingEnabled= addCheckBox(colorComposite, PreferencesMessages.getString("JavaEditorPreferencePage.semanticHighlighting.option"), PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED, 0); //$NON-NLS-1$ fSemanticHighlightingEnabled.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { fHighlightingColorListViewer.getControl().setRedraw(false); if (fSemanticHighlightingEnabled.getSelection()) { fHighlightingColorList.addAll(fSemanticHighlightingColorList); fHighlightingColorListViewer.add(fSemanticHighlightingColorList.toArray()); } else { int fullSize= fHighlightingColorList.size(); fHighlightingColorList.removeAll(fSemanticHighlightingColorList); HighlightingColorListItem item= getHighlightingColorListItem(); if (!fHighlightingColorList.contains(item)) { int i= 0; while (item != fHighlightingColorListViewer.getElementAt(i)) i++; while (!fHighlightingColorList.contains(fHighlightingColorListViewer.getElementAt(i)) && i < fullSize) i++; while (!fHighlightingColorList.contains(fHighlightingColorListViewer.getElementAt(i)) && i >= 0) i--; // Assume non-empty list fHighlightingColorListViewer.setSelection(new StructuredSelection(fHighlightingColorListViewer.getElementAt(i))); } fHighlightingColorListViewer.remove(fSemanticHighlightingColorList.toArray()); } fHighlightingColorListViewer.getControl().setRedraw(true); fHighlightingColorListViewer.reveal(getHighlightingColorListItem()); } }); Label label= new Label(colorComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.foreground")); //$NON-NLS-1$ label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Composite editorComposite= new Composite(colorComposite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); GridData gd= new GridData(GridData.FILL_BOTH); editorComposite.setLayoutData(gd); fHighlightingColorListViewer= new TableViewer(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); fHighlightingColorListViewer.setLabelProvider(new ColorListLabelProvider()); fHighlightingColorListViewer.setContentProvider(new ColorListContentProvider()); fHighlightingColorListViewer.setSorter(new WorkbenchViewerSorter()); gd= new GridData(GridData.FILL_BOTH); gd.heightHint= convertHeightInCharsToPixels(5); fHighlightingColorListViewer.getControl().setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); label= new Label(stylesComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; label.setLayoutData(gd); fSyntaxForegroundColorEditor= new ColorEditor(stylesComposite); Button foregroundColorButton= fSyntaxForegroundColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; foregroundColorButton.setLayoutData(gd); fBoldCheckBox= new Button(stylesComposite, SWT.CHECK); fBoldCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.bold")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fBoldCheckBox.setLayoutData(gd); fItalicCheckBox= new Button(stylesComposite, SWT.CHECK); fItalicCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.italic")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fItalicCheckBox.setLayoutData(gd); label= new Label(colorComposite, SWT.LEFT); label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.preview")); //$NON-NLS-1$ label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Control previewer= createPreviewer(colorComposite); gd= new GridData(GridData.FILL_BOTH); gd.widthHint= convertWidthInCharsToPixels(20); gd.heightHint= convertHeightInCharsToPixels(5); previewer.setLayoutData(gd); fHighlightingColorListViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { handleSyntaxColorListSelection(); } }); foregroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { HighlightingColorListItem item= getHighlightingColorListItem(); PreferenceConverter.setValue(fOverlayStore, item.getColorKey(), fSyntaxForegroundColorEditor.getColorValue()); } }); fBackgroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { PreferenceConverter.setValue(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR, fBackgroundColorEditor.getColorValue()); } }); fBoldCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { HighlightingColorListItem item= getHighlightingColorListItem(); fOverlayStore.setValue(item.getBoldKey(), fBoldCheckBox.getSelection()); } }); fItalicCheckBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { HighlightingColorListItem item= getHighlightingColorListItem(); fOverlayStore.setValue(item.getItalicKey(), fItalicCheckBox.getSelection()); } }); return colorComposite; } private Control createPreviewer(Composite parent) { IPreferenceStore store= new ChainedPreferenceStore(new IPreferenceStore[] { fOverlayStore, new PreferencesAdapter(createTemporaryCorePreferenceStore()) }); fPreviewViewer= new JavaSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER, store); JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools(); JavaSourceViewerConfiguration configuration= new JavaSourceViewerConfiguration(tools.getColorManager(), store, null, IJavaPartitions.JAVA_PARTITIONING); fPreviewViewer.configure(configuration); Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT); fPreviewViewer.getTextWidget().setFont(font); new JavaSourcePreviewerUpdater(fPreviewViewer, configuration, store); fPreviewViewer.setEditable(false); String content= loadPreviewContentFromFile("ColorSettingPreviewCode.txt"); //$NON-NLS-1$ IDocument document= new Document(content); tools.setupJavaDocumentPartitioner(document, IJavaPartitions.JAVA_PARTITIONING); fPreviewViewer.setDocument(document); installSemanticHighlighting(); return fPreviewViewer.getControl(); } private Preferences createTemporaryCorePreferenceStore() { Preferences result= new Preferences(); result.setValue(COMPILER_TASK_TAGS, "TASK,TODO"); //$NON-NLS-1$ return result; } private Control createAppearancePage(Composite parent) { Composite appearanceComposite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; appearanceComposite.setLayout(layout); String label= PreferencesMessages.getString("JavaEditorPreferencePage.displayedTabWidth"); //$NON-NLS-1$ addTextField(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH, 3, 0, true); label= PreferencesMessages.getString("JavaEditorPreferencePage.printMarginColumn"); //$NON-NLS-1$ addTextField(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 3, 0, true); label= PreferencesMessages.getString("JavaEditorPreferencePage.showOverviewRuler"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.showLineNumbers"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.highlightMatchingBrackets"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_MATCHING_BRACKETS, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.highlightCurrentLine"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.showPrintMargin"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.quickassist.lightbulb"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_QUICKASSIST_LIGHTBULB, 0); //$NON-NLS-1$ label= PreferencesMessages.getString("JavaEditorPreferencePage.showQuickFixables"); //$NON-NLS-1$ addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_CORRECTION_INDICATION, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.accessibility.disableCustomCarets"); //$NON-NLS-1$ Button master= addCheckBox(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_USE_CUSTOM_CARETS, 0); label= PreferencesMessages.getString("JavaEditorPreferencePage.accessibility.wideCaret"); //$NON-NLS-1$ Button slave= addCheckBox(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_WIDE_CARET, 0); createDependency(master, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_USE_CUSTOM_CARETS, slave); Label l= new Label(appearanceComposite, SWT.LEFT ); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; l.setLayoutData(gd); l= new Label(appearanceComposite, SWT.LEFT); l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.appearanceOptions")); //$NON-NLS-1$ gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; l.setLayoutData(gd); Composite editorComposite= new Composite(appearanceComposite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); gd.horizontalSpan= 2; editorComposite.setLayoutData(gd); fAppearanceColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); gd.heightHint= convertHeightInCharsToPixels(8); fAppearanceColorList.setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); l= new Label(stylesComposite, SWT.LEFT); l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ gd= new GridData(); gd.horizontalAlignment= GridData.BEGINNING; l.setLayoutData(gd); fAppearanceColorEditor= new ColorEditor(stylesComposite); Button foregroundColorButton= fAppearanceColorEditor.getButton(); gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; foregroundColorButton.setLayoutData(gd); SelectionListener colorDefaultSelectionListener= new SelectionListener() { public void widgetSelected(SelectionEvent e) { boolean systemDefault= fAppearanceColorDefault.getSelection(); fAppearanceColorEditor.getButton().setEnabled(!systemDefault); int i= fAppearanceColorList.getSelectionIndex(); String key= fAppearanceColorListModel[i][2]; if (key != null) fOverlayStore.setValue(key, systemDefault); } public void widgetDefaultSelected(SelectionEvent e) {} }; fAppearanceColorDefault= new Button(stylesComposite, SWT.CHECK); fAppearanceColorDefault.setText(PreferencesMessages.getString("JavaEditorPreferencePage.systemDefault")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fAppearanceColorDefault.setLayoutData(gd); fAppearanceColorDefault.setVisible(false); fAppearanceColorDefault.addSelectionListener(colorDefaultSelectionListener); fAppearanceColorList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleAppearanceColorListSelection(); } }); foregroundColorButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fAppearanceColorList.getSelectionIndex(); String key= fAppearanceColorListModel[i][1]; PreferenceConverter.setValue(fOverlayStore, key, fAppearanceColorEditor.getColorValue()); } }); return appearanceComposite; } private Control createTypingPage(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 1; composite.setLayout(layout); String label= PreferencesMessages.getString("JavaEditorPreferencePage.analyseAnnotationsWhileTyping"); //$NON-NLS-1$ addCheckBox(composite, label, PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, 0); addFiller(composite); label= PreferencesMessages.getString("JavaEditorPreferencePage.overwriteMode"); //$NON-NLS-1$ addCheckBox(composite, label, PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE, 1); addFiller(composite); Group group= new Group(composite, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; group.setLayout(layout); group.setText(PreferencesMessages.getString("JavaEditorPreferencePage.typing.description")); //$NON-NLS-1$ label= PreferencesMessages.getString("JavaEditorPreferencePage.wrapStrings"); //$NON-NLS-1$ Button master= addCheckBox(group, label, PreferenceConstants.EDITOR_WRAP_STRINGS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.escapeStrings"); //$NON-NLS-1$ Button slave= addCheckBox(group, label, PreferenceConstants.EDITOR_ESCAPE_STRINGS, 1); createDependency(master, PreferenceConstants.EDITOR_WRAP_STRINGS, slave); label= PreferencesMessages.getString("JavaEditorPreferencePage.smartPaste"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_SMART_PASTE, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.importsOnPaste"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_IMPORTS_ON_PASTE, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.insertSpaceForTabs"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_SPACES_FOR_TABS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeStrings"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_STRINGS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeBrackets"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_BRACKETS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeBraces"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_BRACES, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.closeJavaDocs"); //$NON-NLS-1$ master= addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_JAVADOCS, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.addJavaDocTags"); //$NON-NLS-1$ slave= addCheckBox(group, label, PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, 1); createDependency(master, PreferenceConstants.EDITOR_CLOSE_JAVADOCS, slave); label= PreferencesMessages.getString("JavaEditorPreferencePage.typing.smartSemicolon"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_SMART_SEMICOLON, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.typing.smartOpeningBrace"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_SMART_OPENING_BRACE, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.typing.smartTab"); //$NON-NLS-1$ addCheckBox(group, label, PreferenceConstants.EDITOR_SMART_TAB, 1); // label= PreferencesMessages.getString("JavaEditorPreferencePage.formatJavaDocs"); //$NON-NLS-1$ // addCheckBox(group, label, PreferenceConstants.EDITOR_FORMAT_JAVADOCS, 1); return composite; } private void addFiller(Composite composite) { Label filler= new Label(composite, SWT.LEFT ); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; filler.setLayoutData(gd); } private static void indent(Control control) { GridData gridData= new GridData(); gridData.horizontalIndent= 20; control.setLayoutData(gridData); } private void createDependency(final Button master, String masterKey, final Control slave) { indent(slave); boolean masterState= fOverlayStore.getBoolean(masterKey); slave.setEnabled(masterState); SelectionListener listener= new SelectionListener() { public void widgetSelected(SelectionEvent e) { slave.setEnabled(master.getSelection()); } public void widgetDefaultSelected(SelectionEvent e) {} }; master.addSelectionListener(listener); fMasterSlaveListeners.add(listener); } private Control createNavigationPage(Composite parent) { Composite composite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; composite.setLayout(layout); String label= PreferencesMessages.getString("JavaEditorPreferencePage.smartHomeEnd"); //$NON-NLS-1$ addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_HOME_END, 1); label= PreferencesMessages.getString("JavaEditorPreferencePage.subWordNavigation"); //$NON-NLS-1$ addCheckBox(composite, label, PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, 1); addFiller(composite); label= PreferencesMessages.getString("JavaEditorPreferencePage.navigation.browserLikeLinks"); //$NON-NLS-1$ fBrowserLikeLinksCheckBox= addCheckBox(composite, label, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, 0); fBrowserLikeLinksCheckBox.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { boolean state= fBrowserLikeLinksCheckBox.getSelection(); fBrowserLikeLinksKeyModifierText.setEnabled(state); handleBrowserLikeLinksKeyModifierModified(); } public void widgetDefaultSelected(SelectionEvent e) { } }); // Text field for modifier string label= PreferencesMessages.getString("JavaEditorPreferencePage.navigation.browserLikeLinksKeyModifier"); //$NON-NLS-1$ fBrowserLikeLinksKeyModifierText= addTextField(composite, label, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, 20, 0, false); fBrowserLikeLinksKeyModifierText.setTextLimit(Text.LIMIT); if (computeStateMask(fOverlayStore.getString(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER)) == -1) { // Fix possible illegal modifier string int stateMask= fOverlayStore.getInt(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); if (stateMask == -1) fBrowserLikeLinksKeyModifierText.setText(""); //$NON-NLS-1$ else fBrowserLikeLinksKeyModifierText.setText(EditorUtility.getModifierString(stateMask)); } fBrowserLikeLinksKeyModifierText.addKeyListener(new KeyListener() { private boolean isModifierCandidate; public void keyPressed(KeyEvent e) { isModifierCandidate= e.keyCode > 0 && e.character == 0 && e.stateMask == 0; } public void keyReleased(KeyEvent e) { if (isModifierCandidate && e.stateMask > 0 && e.stateMask == e.stateMask && e.character == 0) {// && e.time -time < 1000) { String modifierString= fBrowserLikeLinksKeyModifierText.getText(); Point selection= fBrowserLikeLinksKeyModifierText.getSelection(); int i= selection.x - 1; while (i > -1 && Character.isWhitespace(modifierString.charAt(i))) { i--; } boolean needsPrefixDelimiter= i > -1 && !String.valueOf(modifierString.charAt(i)).equals(DELIMITER); i= selection.y; while (i < modifierString.length() && Character.isWhitespace(modifierString.charAt(i))) { i++; } boolean needsPostfixDelimiter= i < modifierString.length() && !String.valueOf(modifierString.charAt(i)).equals(DELIMITER); String insertString; if (needsPrefixDelimiter && needsPostfixDelimiter) insertString= PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.insertDelimiterAndModifierAndDelimiter", new String[] {Action.findModifierString(e.stateMask)}); //$NON-NLS-1$ else if (needsPrefixDelimiter) insertString= PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.insertDelimiterAndModifier", new String[] {Action.findModifierString(e.stateMask)}); //$NON-NLS-1$ else if (needsPostfixDelimiter) insertString= PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.insertModifierAndDelimiter", new String[] {Action.findModifierString(e.stateMask)}); //$NON-NLS-1$ else insertString= Action.findModifierString(e.stateMask); fBrowserLikeLinksKeyModifierText.insert(insertString); } } }); fBrowserLikeLinksKeyModifierText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { handleBrowserLikeLinksKeyModifierModified(); } }); return composite; } private void handleBrowserLikeLinksKeyModifierModified() { String modifiers= fBrowserLikeLinksKeyModifierText.getText(); int stateMask= computeStateMask(modifiers); if (fBrowserLikeLinksCheckBox.getSelection() && (stateMask == -1 || (stateMask & SWT.SHIFT) != 0)) { if (stateMask == -1) fBrowserLikeLinksKeyModifierStatus= new StatusInfo(IStatus.ERROR, PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.modifierIsNotValid", modifiers)); //$NON-NLS-1$ else fBrowserLikeLinksKeyModifierStatus= new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("JavaEditorPreferencePage.navigation.shiftIsDisabled")); //$NON-NLS-1$ setValid(false); StatusUtil.applyToStatusLine(this, fBrowserLikeLinksKeyModifierStatus); } else { fBrowserLikeLinksKeyModifierStatus= new StatusInfo(); updateStatus(fBrowserLikeLinksKeyModifierStatus); } } private IStatus getBrowserLikeLinksKeyModifierStatus() { if (fBrowserLikeLinksKeyModifierStatus == null) fBrowserLikeLinksKeyModifierStatus= new StatusInfo(); return fBrowserLikeLinksKeyModifierStatus; } /** * Computes the state mask for the given modifier string. * * @param modifiers the string with the modifiers, separated by '+', '-', ';', ',' or '.' * @return the state mask or -1 if the input is invalid */ private int computeStateMask(String modifiers) { if (modifiers == null) return -1; if (modifiers.length() == 0) return SWT.NONE; int stateMask= 0; StringTokenizer modifierTokenizer= new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$ while (modifierTokenizer.hasMoreTokens()) { int modifier= EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken()); if (modifier == 0 || (stateMask & modifier) == modifier) return -1; stateMask= stateMask | modifier; } return stateMask; } /* * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { initializeDefaultColors(); fJavaEditorHoverConfigurationBlock= new JavaEditorHoverConfigurationBlock(this, fOverlayStore); fFoldingConfigurationBlock= new FoldingConfigurationBlock(fOverlayStore); fOverlayStore.load(); fOverlayStore.start(); TabFolder folder= new TabFolder(parent, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new GridData(GridData.FILL_BOTH)); TabItem item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.general")); //$NON-NLS-1$ item.setControl(createAppearancePage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.colors")); //$NON-NLS-1$ item.setControl(createSyntaxPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.typing.tabTitle")); //$NON-NLS-1$ item.setControl(createTypingPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.hoverTab.title")); //$NON-NLS-1$ item.setControl(fJavaEditorHoverConfigurationBlock.createControl(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.navigationTab.title")); //$NON-NLS-1$ item.setControl(createNavigationPage(folder)); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.folding.title")); //$NON-NLS-1$ item.setControl(fFoldingConfigurationBlock.createControl(folder)); initialize(); Dialog.applyDialogFont(folder); return folder; } private void initialize() { initializeFields(); for (int i= 0, n= fSyntaxColorListModel.length; i < n; i++) fHighlightingColorList.add(new HighlightingColorListItem (fSyntaxColorListModel[i][0], fSyntaxColorListModel[i][1], fSyntaxColorListModel[i][1] + BOLD, fSyntaxColorListModel[i][1] + ITALIC, null)); if (fSemanticHighlightingEnabled.getSelection()) fHighlightingColorList.addAll(fSemanticHighlightingColorList); fHighlightingColorListViewer.setInput(fHighlightingColorList); fHighlightingColorListViewer.setSelection(new StructuredSelection(fHighlightingColorListViewer.getElementAt(0))); for (int i= 0; i < fAppearanceColorListModel.length; i++) fAppearanceColorList.add(fAppearanceColorListModel[i][0]); fAppearanceColorList.getDisplay().asyncExec(new Runnable() { public void run() { if (fAppearanceColorList != null && !fAppearanceColorList.isDisposed()) { fAppearanceColorList.select(0); handleAppearanceColorListSelection(); } } }); fFoldingConfigurationBlock.initialize(); } private void initializeFields() { Iterator e= fColorButtons.keySet().iterator(); while (e.hasNext()) { ColorEditor c= (ColorEditor) e.next(); String key= (String) fColorButtons.get(c); RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); c.setColorValue(rgb); } e= fCheckBoxes.keySet().iterator(); while (e.hasNext()) { Button b= (Button) e.next(); String key= (String) fCheckBoxes.get(b); b.setSelection(fOverlayStore.getBoolean(key)); } e= fTextFields.keySet().iterator(); while (e.hasNext()) { Text t= (Text) e.next(); String key= (String) fTextFields.get(t); t.setText(fOverlayStore.getString(key)); } RGB rgb= PreferenceConverter.getColor(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR); fBackgroundColorEditor.setColorValue(rgb); boolean default_= fOverlayStore.getBoolean(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR); fBackgroundDefaultRadioButton.setSelection(default_); fBackgroundCustomRadioButton.setSelection(!default_); fBackgroundColorButton.setEnabled(!default_); fBrowserLikeLinksKeyModifierText.setEnabled(fBrowserLikeLinksCheckBox.getSelection()); fFieldsInitialized= true; updateStatus(validatePositiveNumber("0")); //$NON-NLS-1$ // Update slaves Iterator iter= fMasterSlaveListeners.iterator(); while (iter.hasNext()) { SelectionListener listener= (SelectionListener)iter.next(); listener.widgetSelected(null); } } private void initializeDefaultColors() { if (!getPreferenceStore().contains(PreferenceConstants.EDITOR_BACKGROUND_COLOR)) { RGB rgb= getControl().getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB(); PreferenceConverter.setDefault(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgb); PreferenceConverter.setDefault(getPreferenceStore(), PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgb); } if (!getPreferenceStore().contains(PreferenceConstants.EDITOR_FOREGROUND_COLOR)) { RGB rgb= getControl().getDisplay().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(); PreferenceConverter.setDefault(fOverlayStore, PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgb); PreferenceConverter.setDefault(getPreferenceStore(), PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgb); } if (!getPreferenceStore().contains(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR)) { RGB rgb= getControl().getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION).getRGB(); PreferenceConverter.setDefault(fOverlayStore, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR, rgb); PreferenceConverter.setDefault(getPreferenceStore(), AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR, rgb); } if (!getPreferenceStore().contains(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR)) { RGB rgb= getControl().getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT).getRGB(); PreferenceConverter.setDefault(fOverlayStore, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR, rgb); PreferenceConverter.setDefault(getPreferenceStore(), AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR, rgb); } } /* * @see PreferencePage#performOk() */ public boolean performOk() { fJavaEditorHoverConfigurationBlock.performOk(); fFoldingConfigurationBlock.performOk(); fOverlayStore.setValue(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, computeStateMask(fBrowserLikeLinksKeyModifierText.getText())); fOverlayStore.propagate(); JavaPlugin.getDefault().savePluginPreferences(); return true; } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { fOverlayStore.loadDefaults(); initializeFields(); handleSyntaxColorListSelection(); handleAppearanceColorListSelection(); fJavaEditorHoverConfigurationBlock.performDefaults(); fFoldingConfigurationBlock.performDefaults(); super.performDefaults(); fPreviewViewer.invalidateTextPresentation(); } /* * @see DialogPage#dispose() */ public void dispose() { uninstallSemanticHighlighting(); fFoldingConfigurationBlock.dispose(); if (fOverlayStore != null) { fOverlayStore.stop(); fOverlayStore= null; } if (fBackgroundColor != null && !fBackgroundColor.isDisposed()) fBackgroundColor.dispose(); super.dispose(); } private Button addCheckBox(Composite parent, String label, String key, int indentation) { Button checkBox= new Button(parent, SWT.CHECK); checkBox.setText(label); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalIndent= indentation; gd.horizontalSpan= 2; checkBox.setLayoutData(gd); checkBox.addSelectionListener(fCheckBoxListener); fCheckBoxes.put(checkBox, key); return checkBox; } private Text addTextField(Composite composite, String label, String key, int textLimit, int indentation, boolean isNumber) { return getTextControl(addLabelledTextField(composite, label, key, textLimit, indentation, isNumber)); } private static Text getTextControl(Control[] labelledTextField){ return (Text)labelledTextField[1]; } /** * Returns an array of size 2: * - first element is of type <code>Label</code> * - second element is of type <code>Text</code> * Use <code>getLabelControl</code> and <code>getTextControl</code> to get the 2 controls. * * @param composite the parent composite * @param label the text field's label * @param key the preference key * @param textLimit the text limit * @param indentation the field's indentation * @param isNumber <code>true</code> iff this text field is used to e4dit a number * @return */ private Control[] addLabelledTextField(Composite composite, String label, String key, int textLimit, int indentation, boolean isNumber) { Label labelControl= new Label(composite, SWT.NONE); labelControl.setText(label); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalIndent= indentation; labelControl.setLayoutData(gd); Text textControl= new Text(composite, SWT.BORDER | SWT.SINGLE); gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.widthHint= convertWidthInCharsToPixels(textLimit + 1); textControl.setLayoutData(gd); textControl.setTextLimit(textLimit); fTextFields.put(textControl, key); if (isNumber) { fNumberFields.add(textControl); textControl.addModifyListener(fNumberFieldListener); } else { textControl.addModifyListener(fTextFieldListener); } return new Control[]{labelControl, textControl}; } private String loadPreviewContentFromFile(String filename) { String line; String separator= System.getProperty("line.separator"); //$NON-NLS-1$ StringBuffer buffer= new StringBuffer(512); BufferedReader reader= null; try { reader= new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename))); while ((line= reader.readLine()) != null) { buffer.append(line); buffer.append(separator); } } catch (IOException io) { JavaPlugin.log(io); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) {} } } return buffer.toString(); } private void numberFieldChanged(Text textControl) { String number= textControl.getText(); IStatus status= validatePositiveNumber(number); if (!status.matches(IStatus.ERROR)) fOverlayStore.setValue((String) fTextFields.get(textControl), number); updateStatus(status); } private IStatus validatePositiveNumber(String number) { StatusInfo status= new StatusInfo(); if (number.length() == 0) { status.setError(PreferencesMessages.getString("JavaEditorPreferencePage.empty_input")); //$NON-NLS-1$ } else { try { int value= Integer.parseInt(number); if (value < 0) status.setError(PreferencesMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ } catch (NumberFormatException e) { status.setError(PreferencesMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ } } return status; } void updateStatus(IStatus status) { if (!fFieldsInitialized) return; if (!status.matches(IStatus.ERROR)) { for (int i= 0; i < fNumberFields.size(); i++) { Text text= (Text) fNumberFields.get(i); IStatus s= validatePositiveNumber(text.getText()); status= StatusUtil.getMoreSevere(s, status); } } status= StatusUtil.getMoreSevere(fJavaEditorHoverConfigurationBlock.getStatus(), status); status= StatusUtil.getMoreSevere(getBrowserLikeLinksKeyModifierStatus(), status); setValid(!status.matches(IStatus.ERROR)); StatusUtil.applyToStatusLine(this, status); } /** * Install Semantic Highlighting on the previewer * * @since 3.0 */ private void installSemanticHighlighting() { if (fSemanticHighlightingManager == null) { fSemanticHighlightingManager= new SemanticHighlightingManager(); fSemanticHighlightingManager.install(fPreviewViewer, JavaPlugin.getDefault().getJavaTextTools().getColorManager(), fOverlayStore, createPreviewerRanges()); } } /** * Uninstall Semantic Highlighting from the previewer * * @since 3.0 */ private void uninstallSemanticHighlighting() { if (fSemanticHighlightingManager != null) { fSemanticHighlightingManager.uninstall(); fSemanticHighlightingManager= null; } } /** * Create the hard coded previewer ranges * * @return the hard coded previewer ranges * @since 3.0 */ private SemanticHighlightingManager.HighlightedRange[] createPreviewerRanges() { return new SemanticHighlightingManager.HighlightedRange[] { createHighlightedRange(6, 26, 8, SemanticHighlightings.STATIC_FINAL_FIELD), createHighlightedRange(8, 20, 11, SemanticHighlightings.STATIC_FIELD), createHighlightedRange(10, 16, 5, SemanticHighlightings.FIELD), createHighlightedRange(12, 12, 3, SemanticHighlightings.METHOD_DECLARATION), createHighlightedRange(12, 20, 9, SemanticHighlightings.PARAMETER_VARIABLE), createHighlightedRange(13, 2, 14, SemanticHighlightings.ABSTRACT_METHOD_INVOCATION), createHighlightedRange(14, 6, 5, SemanticHighlightings.LOCAL_VARIABLE_DECLARATION), createHighlightedRange(14, 16, 8, SemanticHighlightings.INHERITED_METHOD_INVOCATION), createHighlightedRange(15, 2, 12, SemanticHighlightings.STATIC_METHOD_INVOCATION), createHighlightedRange(16, 13, 5, SemanticHighlightings.LOCAL_VARIABLE), }; } /** * Create a highlighted range on the previewers document with the given line, column, length and key. * * @param line the line * @param column the column * @param length the length * @param key the key * @return the highlighted range * @since 3.0 */ private HighlightedRange createHighlightedRange(int line, int column, int length, String key) { try { IDocument document= fPreviewViewer.getDocument(); int offset= document.getLineOffset(line) + column; return new HighlightedRange(offset, length, key); } catch (BadLocationException x) { JavaPlugin.log(x); } return null; } /** * Returns the current highlighting color list item. * * @return the current highlighting color list item * @since 3.0 */ private HighlightingColorListItem getHighlightingColorListItem() { IStructuredSelection selection= (IStructuredSelection) fHighlightingColorListViewer.getSelection(); return (HighlightingColorListItem) selection.getFirstElement(); } }
61,469
Bug 61469 Code review for CustomFiltersActionGroup#initializeWithViewDefaults() suggested
I200405060200 while (tokenizer.hasMoreTokens()) { String id= tokenizer.nextToken(); if (fFilterDescriptorMap.containsKey(id) && !fLRUFilterIdsStack.contains(id)); fLRUFilterIdsStack.push(id); } See original code. Either formatting is wrong, or - which looks more likely to me - the semicolon should be removed. Don't know if this even causes a visible bug, just discovered this piece of code randomly.
resolved fixed
d9a2c71
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-10T09:57:53Z
2004-05-07T22:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/CustomFiltersActionGroup.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui.actions; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeSet; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.ContributionItem; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.IContentProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jface.window.Window; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IMemento; import org.eclipse.ui.IViewPart; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.filters.CustomFiltersDialog; import org.eclipse.jdt.internal.ui.filters.FilterDescriptor; import org.eclipse.jdt.internal.ui.filters.FilterMessages; import org.eclipse.jdt.internal.ui.filters.NamePatternFilter; /** * Action group to add the filter action to a view part's tool bar * menu. * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class CustomFiltersActionGroup extends ActionGroup { class ShowFilterDialogAction extends Action { ShowFilterDialogAction() { setText(FilterMessages.getString("OpenCustomFiltersDialogAction.text")); //$NON-NLS-1$ setImageDescriptor(JavaPluginImages.DESC_ELCL_FILTER); setDisabledImageDescriptor(JavaPluginImages.DESC_DLCL_FILTER); } public void run() { openDialog(); } } /** * Menu contribution item which shows and lets check and uncheck filters. * * @since 3.0 */ class FilterActionMenuContributionItem extends ContributionItem { private int fItemNumber; private boolean fState; private String fFilterId; private String fFilterName; private CustomFiltersActionGroup fActionGroup; /** * Constructor for FilterActionMenuContributionItem. * * @param actionGroup the action group * @param filterId the id of the filter * @param filterName the name of the filter * @param state the initial state of the filter * @param itemNumber the menu item index */ public FilterActionMenuContributionItem(CustomFiltersActionGroup actionGroup, String filterId, String filterName, boolean state, int itemNumber) { super(filterId); Assert.isNotNull(actionGroup); Assert.isNotNull(filterId); Assert.isNotNull(filterName); fActionGroup= actionGroup; fFilterId= filterId; fFilterName= filterName; fState= state; fItemNumber= itemNumber; } /* * Overrides method from ContributionItem. */ public void fill(Menu menu, int index) { MenuItem mi= new MenuItem(menu, SWT.CHECK, index); mi.setText("&" + fItemNumber + " " + fFilterName); //$NON-NLS-1$ //$NON-NLS-2$ /* * XXX: Don't set the image - would look bad because other menu items don't provide image * XXX: Get working set specific image name from XML - would need to cache icons */ // mi.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVA_WORKING_SET)); mi.setSelection(fState); mi.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { fState= !fState; fActionGroup.setFilter(fFilterId, fState); } }); } /* * @see org.eclipse.jface.action.IContributionItem#isDynamic() */ public boolean isDynamic() { return true; } } private static final String TAG_CUSTOM_FILTERS = "customFilters"; //$NON-NLS-1$ private static final String TAG_USER_DEFINED_PATTERNS_ENABLED= "userDefinedPatternsEnabled"; //$NON-NLS-1$ private static final String TAG_USER_DEFINED_PATTERNS= "userDefinedPatterns"; //$NON-NLS-1$ private static final String TAG_XML_DEFINED_FILTERS= "xmlDefinedFilters"; //$NON-NLS-1$ private static final String TAG_LRU_FILTERS = "lastRecentlyUsedFilters"; //$NON-NLS-1$ private static final String TAG_CHILD= "child"; //$NON-NLS-1$ private static final String TAG_PATTERN= "pattern"; //$NON-NLS-1$ private static final String TAG_FILTER_ID= "filterId"; //$NON-NLS-1$ private static final String TAG_IS_ENABLED= "isEnabled"; //$NON-NLS-1$ private static final String SEPARATOR= ","; //$NON-NLS-1$ private static final int MAX_FILTER_MENU_ENTRIES= 3; private static final String RECENT_FILTERS_GROUP_NAME= "recentFiltersGroup"; //$NON-NLS-1$ private StructuredViewer fViewer; private NamePatternFilter fPatternFilter; private Map fInstalledBuiltInFilters; private Map fEnabledFilterIds; private boolean fUserDefinedPatternsEnabled; private String[] fUserDefinedPatterns; /** * Recently changed filter Ids stack with oldest on top (i.e. at the end). * * @since 3.0 */ private Stack fLRUFilterIdsStack; /** * Handle to menu manager to dynamically update * the last recently used filters. * * @since 3.0 */ private IMenuManager fMenuManager; /** * The menu listener which dynamically updates * the last recently used filters. * * @since 3.0 */ private IMenuListener fMenuListener; /** * Filter Ids used in the last view menu invocation. * * @since 3.0 */ private String[] fFilterIdsUsedInLastViewMenu; private HashMap fFilterDescriptorMap; private String fTargetId; /** * Creates a new <code>CustomFiltersActionGroup</code>. * * @param part the view part that owns this action group * @param viewer the viewer to be filtered */ public CustomFiltersActionGroup(IViewPart part, StructuredViewer viewer) { this(part.getViewSite().getId(), viewer); } /** * Creates a new <code>CustomFiltersActionGroup</code>. * * @param ownerId the id of this action group's owner * @param viewer the viewer to be filtered */ public CustomFiltersActionGroup(String ownerId, StructuredViewer viewer) { Assert.isNotNull(ownerId); Assert.isNotNull(viewer); fTargetId= ownerId; fViewer= viewer; fLRUFilterIdsStack= new Stack(); initializeWithPluginContributions(); initializeWithViewDefaults(); installFilters(); } /* * Method declared on ActionGroup. */ public void fillActionBars(IActionBars actionBars) { fillToolBar(actionBars.getToolBarManager()); fillViewMenu(actionBars.getMenuManager()); } public String[] removeFiltersFor(Object parent, Object element, IContentProvider contentProvider) { String[] enabledFilters= getEnabledFilterIds(); Set newFilters= new HashSet(); for (int i= 0; i < enabledFilters.length; i++) { String filterName= enabledFilters[i]; ViewerFilter filter= (ViewerFilter) fInstalledBuiltInFilters.get(filterName); if (filter == null) newFilters.add(filterName); else if (isSelected(parent, element, contentProvider, filter)) newFilters.add(filterName); } if (newFilters.size() == enabledFilters.length) return new String[0]; return (String[])newFilters.toArray(new String[newFilters.size()]); } public void setFilters(String[] newFilters) { setEnabledFilterIds(newFilters); updateViewerFilters(true); } private boolean isSelected(Object parent, Object element, IContentProvider contentProvider, ViewerFilter filter) { if (contentProvider instanceof ITreeContentProvider) { // the element and all its parents have to be selected ITreeContentProvider provider = (ITreeContentProvider) contentProvider; while (element != null && !(element instanceof IJavaModel)) { if (!filter.select(fViewer, parent, element)) return false; element= provider.getParent( element); } return true; } return filter.select(fViewer, parent, element); } /** * Sets the enable state of the given filter. * * @param filterId the id of the filter * @param state the filter state */ private void setFilter(String filterId, boolean state) { // Renew filter id in LRU stack fLRUFilterIdsStack.remove(filterId); fLRUFilterIdsStack.add(0, filterId); fEnabledFilterIds.put(filterId, new Boolean(state)); storeViewDefaults(); updateViewerFilters(true); } private String[] getEnabledFilterIds() { Set enabledFilterIds= new HashSet(fEnabledFilterIds.size()); Iterator iter= fEnabledFilterIds.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry= (Map.Entry)iter.next(); String id= (String)entry.getKey(); boolean isEnabled= ((Boolean)entry.getValue()).booleanValue(); if (isEnabled) enabledFilterIds.add(id); } return (String[])enabledFilterIds.toArray(new String[enabledFilterIds.size()]); } private void setEnabledFilterIds(String[] enabledIds) { Iterator iter= fEnabledFilterIds.keySet().iterator(); while (iter.hasNext()) { String id= (String)iter.next(); fEnabledFilterIds.put(id, Boolean.FALSE); } for (int i= 0; i < enabledIds.length; i++) fEnabledFilterIds.put(enabledIds[i], Boolean.TRUE); } private void setUserDefinedPatterns(String[] patterns) { fUserDefinedPatterns= patterns; cleanUpPatternDuplicates(); } /** * Sets the recently changed filters. * * @param changeHistory the change history * @since 3.0 */ private void setRecentlyChangedFilters(Stack changeHistory) { Stack oldestFirstStack= new Stack(); int length= Math.min(changeHistory.size(), MAX_FILTER_MENU_ENTRIES); for (int i= 0; i < length; i++) oldestFirstStack.push(((FilterDescriptor)changeHistory.pop()).getId()); length= Math.min(fLRUFilterIdsStack.size(), MAX_FILTER_MENU_ENTRIES - oldestFirstStack.size()); int NEWEST= 0; for (int i= 0; i < length; i++) { Object filter= fLRUFilterIdsStack.remove(NEWEST); if (!oldestFirstStack.contains(filter)) oldestFirstStack.push(filter); } fLRUFilterIdsStack= oldestFirstStack; } private boolean areUserDefinedPatternsEnabled() { return fUserDefinedPatternsEnabled; } private void setUserDefinedPatternsEnabled(boolean state) { fUserDefinedPatternsEnabled= state; } private void fillToolBar(IToolBarManager tooBar) { } /** * Fills the given view menu with the entries managed by the * group. * * @param viewMenu the menu to fill */ public void fillViewMenu(IMenuManager viewMenu) { /* * Don't change the separator group name. * Using this name ensures that other filters * get contributed to the same group. */ viewMenu.add(new Separator("filters")); //$NON-NLS-1$ viewMenu.add(new GroupMarker(RECENT_FILTERS_GROUP_NAME)); viewMenu.add(new ShowFilterDialogAction()); fMenuManager= viewMenu; fMenuListener= new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { removePreviousLRUFilterActions(manager); addLRUFilterActions(manager); } }; fMenuManager.addMenuListener(fMenuListener); } private void removePreviousLRUFilterActions(IMenuManager mm) { if (fFilterIdsUsedInLastViewMenu == null) return; for (int i= 0; i < fFilterIdsUsedInLastViewMenu.length; i++) mm.remove(fFilterIdsUsedInLastViewMenu[i]); } private void addLRUFilterActions(IMenuManager mm) { if (fLRUFilterIdsStack.isEmpty()) { fFilterIdsUsedInLastViewMenu= null; return; } SortedSet sortedFilters= new TreeSet(fLRUFilterIdsStack); String[] recentlyChangedFilterIds= (String[])sortedFilters.toArray(new String[sortedFilters.size()]); fFilterIdsUsedInLastViewMenu= new String[recentlyChangedFilterIds.length]; for (int i= 0; i < recentlyChangedFilterIds.length; i++) { String id= recentlyChangedFilterIds[i]; fFilterIdsUsedInLastViewMenu[i]= id; boolean state= fEnabledFilterIds.containsKey(id) && ((Boolean)fEnabledFilterIds.get(id)).booleanValue(); FilterDescriptor filterDesc= (FilterDescriptor)fFilterDescriptorMap.get(id); if (filterDesc != null) { IContributionItem item= new FilterActionMenuContributionItem(this, id, filterDesc.getName(), state, i+1); mm.insertBefore(RECENT_FILTERS_GROUP_NAME, item); } } } /* * Method declared on ActionGroup. */ public void dispose() { if (fMenuManager != null) fMenuManager.removeMenuListener(fMenuListener); super.dispose(); } private void initializeWithPluginContributions() { fUserDefinedPatterns= new String[0]; fUserDefinedPatternsEnabled= false; FilterDescriptor[] filterDescs= FilterDescriptor.getFilterDescriptors(fTargetId); fFilterDescriptorMap= new HashMap(filterDescs.length); fEnabledFilterIds= new HashMap(filterDescs.length); for (int i= 0; i < filterDescs.length; i++) { String id= filterDescs[i].getId(); Boolean isEnabled= new Boolean(filterDescs[i].isEnabled()); if (fEnabledFilterIds.containsKey(id)) JavaPlugin.logErrorMessage("WARNING: Duplicate id for extension-point \"org.eclipse.jdt.ui.javaElementFilters\""); //$NON-NLS-1$ fEnabledFilterIds.put(id, isEnabled); fFilterDescriptorMap.put(id, filterDescs[i]); } } // ---------- viewer filter handling ---------- private void installFilters() { fInstalledBuiltInFilters= new HashMap(fEnabledFilterIds.size()); fPatternFilter= new NamePatternFilter(); fPatternFilter.setPatterns(getUserAndBuiltInPatterns()); fViewer.addFilter(fPatternFilter); updateBuiltInFilters(); } private void updateViewerFilters(boolean refresh) { String[] patterns= getUserAndBuiltInPatterns(); fPatternFilter.setPatterns(patterns); fViewer.getControl().setRedraw(false); updateBuiltInFilters(); if (refresh) fViewer.refresh(); fViewer.getControl().setRedraw(true); } private void updateBuiltInFilters() { Set installedFilters= fInstalledBuiltInFilters.keySet(); Set filtersToAdd= new HashSet(fEnabledFilterIds.size()); Set filtersToRemove= new HashSet(fEnabledFilterIds.size()); Iterator iter= fEnabledFilterIds.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry= (Map.Entry)iter.next(); String id= (String)entry.getKey(); boolean isEnabled= ((Boolean)entry.getValue()).booleanValue(); if (isEnabled && !installedFilters.contains(id)) filtersToAdd.add(id); else if (!isEnabled && installedFilters.contains(id)) filtersToRemove.add(id); } // Install the filters FilterDescriptor[] filterDescs= FilterDescriptor.getFilterDescriptors(fTargetId); for (int i= 0; i < filterDescs.length; i++) { String id= filterDescs[i].getId(); // just to double check - id should denote a custom filter anyway boolean isCustomFilter= filterDescs[i].isCustomFilter(); if (isCustomFilter) { if (filtersToAdd.contains(id)) { ViewerFilter filter= filterDescs[i].createViewerFilter(); if (filter != null) { fViewer.addFilter(filter); fInstalledBuiltInFilters.put(id, filter); } } if (filtersToRemove.contains(id)) { fViewer.removeFilter((ViewerFilter)fInstalledBuiltInFilters.get(id)); fInstalledBuiltInFilters.remove(id); } } } } private String[] getUserAndBuiltInPatterns() { List patterns= new ArrayList(fUserDefinedPatterns.length); if (areUserDefinedPatternsEnabled()) patterns.addAll(Arrays.asList(fUserDefinedPatterns)); FilterDescriptor[] filterDescs= FilterDescriptor.getFilterDescriptors(fTargetId); for (int i= 0; i < filterDescs.length; i++) { String id= filterDescs[i].getId(); boolean isPatternFilter= filterDescs[i].isPatternFilter(); Object isEnabled= fEnabledFilterIds.get(id); if (isEnabled != null && isPatternFilter && ((Boolean)isEnabled).booleanValue()) patterns.add(filterDescs[i].getPattern()); } return (String[])patterns.toArray(new String[patterns.size()]); } // ---------- view kind/defaults persistency ---------- private void initializeWithViewDefaults() { // get default values for view IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); // XXX: can be removed once bug 22533 is fixed. if (!store.contains(getPreferenceKey("TAG_DUMMY_TO_TEST_EXISTENCE")))//$NON-NLS-1$ return; // XXX: Uncomment once bug 22533 is fixed. // if (!store.contains(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED))) // return; fUserDefinedPatternsEnabled= store.getBoolean(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED)); setUserDefinedPatterns(CustomFiltersDialog.convertFromString(store.getString(getPreferenceKey(TAG_USER_DEFINED_PATTERNS)), SEPARATOR)); Iterator iter= fEnabledFilterIds.keySet().iterator(); while (iter.hasNext()) { String id= (String)iter.next(); Boolean isEnabled= new Boolean(store.getBoolean(id)); fEnabledFilterIds.put(id, isEnabled); } fLRUFilterIdsStack.clear(); String lruFilterIds= store.getString(TAG_LRU_FILTERS); StringTokenizer tokenizer= new StringTokenizer(lruFilterIds, SEPARATOR); while (tokenizer.hasMoreTokens()) { String id= tokenizer.nextToken(); if (fFilterDescriptorMap.containsKey(id) && !fLRUFilterIdsStack.contains(id)); fLRUFilterIdsStack.push(id); } } private void storeViewDefaults() { // get default values for view IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); // XXX: can be removed once bug 22533 is fixed. store.setValue(getPreferenceKey("TAG_DUMMY_TO_TEST_EXISTENCE"), "storedViewPreferences");//$NON-NLS-1$//$NON-NLS-2$ store.setValue(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED), fUserDefinedPatternsEnabled); store.setValue(getPreferenceKey(TAG_USER_DEFINED_PATTERNS), CustomFiltersDialog.convertToString(fUserDefinedPatterns ,SEPARATOR)); Iterator iter= fEnabledFilterIds.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry= (Map.Entry)iter.next(); String id= (String)entry.getKey(); boolean isEnabled= ((Boolean)entry.getValue()).booleanValue(); store.setValue(id, isEnabled); } StringBuffer buf= new StringBuffer(fLRUFilterIdsStack.size() * 20); iter= fLRUFilterIdsStack.iterator(); while (iter.hasNext()) { buf.append((String)iter.next()); buf.append(SEPARATOR); } store.setValue(TAG_LRU_FILTERS, buf.toString()); } private String getPreferenceKey(String tag) { return "CustomFiltersActionGroup." + fTargetId + '.' + tag; //$NON-NLS-1$ } // ---------- view instance persistency ---------- /** * Saves the state of the custom filters in a memento. * * @param memento the memento into which the state is saved */ public void saveState(IMemento memento) { IMemento customFilters= memento.createChild(TAG_CUSTOM_FILTERS); customFilters.putString(TAG_USER_DEFINED_PATTERNS_ENABLED, new Boolean(fUserDefinedPatternsEnabled).toString()); saveUserDefinedPatterns(customFilters); saveXmlDefinedFilters(customFilters); saveLRUFilters(customFilters); } private void saveXmlDefinedFilters(IMemento memento) { if(fEnabledFilterIds != null && !fEnabledFilterIds.isEmpty()) { IMemento xmlDefinedFilters= memento.createChild(TAG_XML_DEFINED_FILTERS); Iterator iter= fEnabledFilterIds.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry= (Map.Entry)iter.next(); String id= (String)entry.getKey(); Boolean isEnabled= (Boolean)entry.getValue(); IMemento child= xmlDefinedFilters.createChild(TAG_CHILD); child.putString(TAG_FILTER_ID, id); child.putString(TAG_IS_ENABLED, isEnabled.toString()); } } } /** * Stores the last recently used filter Ids into * the given memento * * @param memento the memento into which to store the LRU filter Ids * @since 3.0 */ private void saveLRUFilters(IMemento memento) { if(fLRUFilterIdsStack != null && !fLRUFilterIdsStack.isEmpty()) { IMemento lruFilters= memento.createChild(TAG_LRU_FILTERS); Iterator iter= fLRUFilterIdsStack.iterator(); while (iter.hasNext()) { String id= (String)iter.next(); IMemento child= lruFilters.createChild(TAG_CHILD); child.putString(TAG_FILTER_ID, id); } } } private void saveUserDefinedPatterns(IMemento memento) { if(fUserDefinedPatterns != null && fUserDefinedPatterns.length > 0) { IMemento userDefinedPatterns= memento.createChild(TAG_USER_DEFINED_PATTERNS); for (int i= 0; i < fUserDefinedPatterns.length; i++) { IMemento child= userDefinedPatterns.createChild(TAG_CHILD); child.putString(TAG_PATTERN, fUserDefinedPatterns[i]); } } } /** * Restores the state of the filter actions from a memento. * <p> * Note: This method does not refresh the viewer. * </p> * * @param memento the memento from which the state is restored */ public void restoreState(IMemento memento) { if (memento == null) return; IMemento customFilters= memento.getChild(TAG_CUSTOM_FILTERS); if (customFilters == null) return; String userDefinedPatternsEnabled= customFilters.getString(TAG_USER_DEFINED_PATTERNS_ENABLED); if (userDefinedPatternsEnabled == null) return; fUserDefinedPatternsEnabled= Boolean.valueOf(userDefinedPatternsEnabled).booleanValue(); restoreUserDefinedPatterns(customFilters); restoreXmlDefinedFilters(customFilters); restoreLRUFilters(customFilters); updateViewerFilters(false); } private void restoreUserDefinedPatterns(IMemento memento) { IMemento userDefinedPatterns= memento.getChild(TAG_USER_DEFINED_PATTERNS); if(userDefinedPatterns != null) { IMemento children[]= userDefinedPatterns.getChildren(TAG_CHILD); String[] patterns= new String[children.length]; for (int i = 0; i < children.length; i++) patterns[i]= children[i].getString(TAG_PATTERN); setUserDefinedPatterns(patterns); } else setUserDefinedPatterns(new String[0]); } private void restoreXmlDefinedFilters(IMemento memento) { IMemento xmlDefinedFilters= memento.getChild(TAG_XML_DEFINED_FILTERS); if(xmlDefinedFilters != null) { IMemento[] children= xmlDefinedFilters.getChildren(TAG_CHILD); for (int i= 0; i < children.length; i++) { String id= children[i].getString(TAG_FILTER_ID); Boolean isEnabled= new Boolean(children[i].getString(TAG_IS_ENABLED)); fEnabledFilterIds.put(id, isEnabled); } } } private void restoreLRUFilters(IMemento memento) { IMemento lruFilters= memento.getChild(TAG_LRU_FILTERS); fLRUFilterIdsStack.clear(); if(lruFilters != null) { IMemento[] children= lruFilters.getChildren(TAG_CHILD); for (int i= 0; i < children.length; i++) { String id= children[i].getString(TAG_FILTER_ID); if (fFilterDescriptorMap.containsKey(id) && !fLRUFilterIdsStack.contains(id)) fLRUFilterIdsStack.push(id); } } } private void cleanUpPatternDuplicates() { if (!areUserDefinedPatternsEnabled()) return; List userDefinedPatterns= new ArrayList(Arrays.asList(fUserDefinedPatterns)); FilterDescriptor[] filters= FilterDescriptor.getFilterDescriptors(fTargetId); for (int i= 0; i < filters.length; i++) { if (filters[i].isPatternFilter()) { String pattern= filters[i].getPattern(); if (userDefinedPatterns.contains(pattern)) { fEnabledFilterIds.put(filters[i].getId(), Boolean.TRUE); boolean hasMore= true; while (hasMore) hasMore= userDefinedPatterns.remove(pattern); } } } fUserDefinedPatterns= (String[])userDefinedPatterns.toArray(new String[userDefinedPatterns.size()]); setUserDefinedPatternsEnabled(fUserDefinedPatternsEnabled && fUserDefinedPatterns.length > 0); } // ---------- dialog related code ---------- private void openDialog() { CustomFiltersDialog dialog= new CustomFiltersDialog( fViewer.getControl().getShell(), fTargetId, areUserDefinedPatternsEnabled(), fUserDefinedPatterns, getEnabledFilterIds()); if (dialog.open() == Window.OK) { setEnabledFilterIds(dialog.getEnabledFilterIds()); setUserDefinedPatternsEnabled(dialog.areUserDefinedPatternsEnabled()); setUserDefinedPatterns(dialog.getUserDefinedPatterns()); setRecentlyChangedFilters(dialog.getFilterDescriptorChangeHistory()); storeViewDefaults(); updateViewerFilters(true); } } }
60,415
Bug 60415 Should remove Search extension page
I20040428 We should remove the search extension page and should make sure that participants can't damage a search. If a participant generates an exception the participant should be disabled for the rest of the Eclipse sessions. This is consistent with Platform/UI and refactoring.
resolved fixed
b56f924
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-10T14:46:27Z
2004-04-29T14:46:40Z
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/search/ParticipantTest.java
60,415
Bug 60415 Should remove Search extension page
I20040428 We should remove the search extension page and should make sure that participants can't damage a search. If a participant generates an exception the participant should be disabled for the rest of the Eclipse sessions. This is consistent with Platform/UI and refactoring.
resolved fixed
b56f924
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-10T14:46:27Z
2004-04-29T14:46:40Z
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/search/SearchTest.java
/******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui.tests.search; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.search.ui.NewSearchUI; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.internal.ui.search.JavaSearchQuery; import org.eclipse.jdt.internal.ui.search.JavaSearchResult; import org.eclipse.jdt.internal.ui.search.ReferenceScopeFactory; import org.eclipse.jdt.ui.search.ElementQuerySpecification; public class SearchTest { public static Test suite() { TestSuite suite= new TestSuite("Java Search Tests"); //$NON-NLS-1$ //suite.addTestSuite(WorkspaceScopeTest.class); suite.addTest(WorkspaceReferenceTest.allTests()); suite.addTest(TreeContentProviderTest.allTests()); return suite; } static int countMethodRefs(String TypeName, String methodName, String[] parameterTypes) throws JavaModelException { JavaSearchQuery query= runMethodRefQuery(TypeName, methodName, parameterTypes); JavaSearchResult result= (JavaSearchResult) query.getSearchResult(); return result.getMatchCount(); } static JavaSearchQuery runMethodRefQuery(String TypeName, String methodName, String[] parameterTypes) throws JavaModelException { IMethod method= getMethod(TypeName, methodName, parameterTypes); NewSearchUI.activateSearchResultView(); JavaSearchQuery query= new JavaSearchQuery(new ElementQuerySpecification(method, IJavaSearchConstants.REFERENCES, ReferenceScopeFactory.createWorkspaceScope(true), "workspace scope")); NewSearchUI.runQueryInForeground(null, query); return query; } static IMethod getMethod(String TypeName, String methodName, String[] parameterTypes) throws JavaModelException { IType type= getType(TypeName); IMethod method= type.getMethod(methodName, parameterTypes); return method; } static IType getType(String TypeName) throws JavaModelException { IJavaProject p= JUnitSourceSetup.getProject(); IType type= p.findType(TypeName); return type; } }
60,415
Bug 60415 Should remove Search extension page
I20040428 We should remove the search extension page and should make sure that participants can't damage a search. If a participant generates an exception the participant should be disabled for the rest of the Eclipse sessions. This is consistent with Platform/UI and refactoring.
resolved fixed
b56f924
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-10T14:46:27Z
2004-04-29T14:46:40Z
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/search/TestParticipant.java
60,415
Bug 60415 Should remove Search extension page
I20040428 We should remove the search extension page and should make sure that participants can't damage a search. If a participant generates an exception the participant should be disabled for the rest of the Eclipse sessions. This is consistent with Platform/UI and refactoring.
resolved fixed
b56f924
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-10T14:46:27Z
2004-04-29T14:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/SearchParticipantsPreferencePage.java
/* * Created on Apr 13, 2004 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package org.eclipse.jdt.internal.ui.preferences; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.Platform; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.search.JavaSearchPage; import org.eclipse.jdt.internal.ui.wizards.dialogfields.CheckedListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; public class SearchParticipantsPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private CheckedListDialogField fParticipantList; static class ParticipantLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage(Object element, int columnIndex) { return getImage(element); } public String getColumnText(Object element, int columnIndex) { return getText(element); } public String getText(Object element) { return ((IConfigurationElement)element).getAttribute("name"); //$NON-NLS-1$ } } public SearchParticipantsPreferencePage() { setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); setTitle(PreferencesMessages.getString("SearchParticipantsPreferencePage.title")); //$NON-NLS-1$ setDescription(PreferencesMessages.getString("SearchParticipantsPreferencePage.description")); //$NON-NLS-1$ String[] buttonLabels= new String[] { PreferencesMessages.getString("SearchParticipantsPreferencePage.select_all"), //$NON-NLS-1$ PreferencesMessages.getString("SearchParticipantsPreferencePage.deselect_all"), //$NON-NLS-1$ }; fParticipantList= new CheckedListDialogField(null, buttonLabels, new ParticipantLabelProvider()); fParticipantList.setLabelText(PreferencesMessages.getString("SearchParticipantsPreferencePage.participants.label")); //$NON-NLS-1$ fParticipantList.setCheckAllButtonIndex(0); fParticipantList.setUncheckAllButtonIndex(1); initialize(readActiveParticipants()); } private void initialize(Map activeParticipants) { fParticipantList.setElements(Arrays.asList(Platform.getExtensionRegistry().getConfigurationElementsFor(JavaSearchPage.PARTICIPANT_EXTENSION_POINT))); fParticipantList.setCheckedElements(activeParticipants.values()); } protected void performDefaults() { initialize(readDefaultActiveParticipants()); super.performDefaults(); } public boolean performOk() { IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); List checked= fParticipantList.getCheckedElements(); writeActiveParticpants(checked); return true; } private final static String STORE_ACTIVE_PARTICIPANTS= "JAVA_SEARCH_ACTIVE_PARTICIPANTS"; //$NON-NLS-1$ private static void writeActiveParticpants(Collection participantIDs) { String[] ids= new String[participantIDs.size()]; Iterator participants= participantIDs.iterator(); int i= 0; while (participants.hasNext()) { IConfigurationElement element= (IConfigurationElement)participants.next(); ids[i++]= element.getAttribute("id"); //$NON-NLS-1$ } String idString= packOrderList(ids); JavaPlugin.getDefault().getPreferenceStore().putValue(STORE_ACTIVE_PARTICIPANTS, idString); JavaPlugin.getDefault().savePluginPreferences(); } public static Map readActiveParticipants() { String idString= JavaPlugin.getDefault().getPreferenceStore().getString(STORE_ACTIVE_PARTICIPANTS); return createActiveParticipants(idString); } private static Map readDefaultActiveParticipants() { String idString= JavaPlugin.getDefault().getPreferenceStore().getDefaultString(STORE_ACTIVE_PARTICIPANTS); return createActiveParticipants(idString); } public static boolean hasAnyParticipants() { return Platform.getExtensionRegistry().getConfigurationElementsFor(JavaSearchPage.PARTICIPANT_EXTENSION_POINT).length > 0; } private static Map createActiveParticipants(String idList) { String[] ids= unpackOrderList(idList); HashMap activeParticipants= new HashMap(); if (ids != null) { IConfigurationElement[] allParticipants= Platform.getExtensionRegistry().getConfigurationElementsFor(JavaSearchPage.PARTICIPANT_EXTENSION_POINT); for (int i= 0; i < allParticipants.length; i++) { for (int j= 0; j < ids.length; j++) { if (ids[j].equals(allParticipants[i].getAttribute("id"))) //$NON-NLS-1$ activeParticipants.put(ids[j], allParticipants[i]); } } } return activeParticipants; } public static Map readAllParticipants() { HashMap activeParticipants= new HashMap(); IConfigurationElement[] allParticipants= Platform.getExtensionRegistry().getConfigurationElementsFor(JavaSearchPage.PARTICIPANT_EXTENSION_POINT); for (int i= 0; i < allParticipants.length; i++) { activeParticipants.put(allParticipants[i].getAttribute("id"), allParticipants[i]); //$NON-NLS-1$ } return activeParticipants; } private static String[] unpackOrderList(String str) { StringTokenizer tok= new StringTokenizer(str, ";"); //$NON-NLS-1$ int nTokens= tok.countTokens(); String[] res= new String[nTokens]; for (int i= 0; i < nTokens; i++) { res[i]= tok.nextToken(); } return res; } private static String packOrderList(String[] orderList) { StringBuffer buf= new StringBuffer(); for (int i= 0; i < orderList.length; i++) { buf.append(orderList[i]); buf.append(';'); } return buf.toString(); } protected Control createContents(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; layout.marginWidth= 0; layout.marginHeight= 0; composite.setLayout(layout); fParticipantList.doFillIntoGrid(composite, 3); LayoutUtil.setHorizontalSpan(fParticipantList.getLabelControl(null), 2); LayoutUtil.setWidthHint(fParticipantList.getLabelControl(null), convertWidthInCharsToPixels(40)); LayoutUtil.setHorizontalGrabbing(fParticipantList.getListControl(null)); fParticipantList.getTableViewer().setSorter(new ViewerSorter() {}); Dialog.applyDialogFont(composite); return composite; } public void init(IWorkbench workbench) { // TODO Auto-generated method stub } }
60,415
Bug 60415 Should remove Search extension page
I20040428 We should remove the search extension page and should make sure that participants can't damage a search. If a participant generates an exception the participant should be disabled for the rest of the Eclipse sessions. This is consistent with Platform/UI and refactoring.
resolved fixed
b56f924
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-10T14:46:27Z
2004-04-29T14:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchPage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.search; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.browsing.LogicalPackage; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.util.RowLayouter; import org.eclipse.jdt.ui.search.ElementQuerySpecification; import org.eclipse.jdt.ui.search.PatternQuerySpecification; import org.eclipse.jdt.ui.search.QuerySpecification; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.DialogPage; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.search.ui.ISearchPage; import org.eclipse.search.ui.ISearchPageContainer; import org.eclipse.search.ui.ISearchResultViewEntry; import org.eclipse.search.ui.NewSearchUI; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkingSet; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.IWorkbenchAdapter; public class JavaSearchPage extends DialogPage implements ISearchPage, IJavaSearchConstants { private static class SearchPatternData { private int searchFor; private int limitTo; private String pattern; private boolean isCaseSensitive; private IJavaElement javaElement; private int scope; private IWorkingSet[] workingSets; public SearchPatternData(int searchFor, int limitTo, boolean isCaseSensitive, String pattern, IJavaElement element) { this(searchFor, limitTo, pattern, isCaseSensitive, element, ISearchPageContainer.WORKSPACE_SCOPE, null); } public SearchPatternData(int s, int l, String p, boolean i, IJavaElement element, int scope, IWorkingSet[] workingSets) { setSearchFor(s); setLimitTo(l); setPattern(p); setCaseSensitive(i); setJavaElement(element); this.setScope(scope); this.setWorkingSets(workingSets); } public void setCaseSensitive(boolean isCaseSensitive) { this.isCaseSensitive= isCaseSensitive; } public boolean isCaseSensitive() { return isCaseSensitive; } public void setJavaElement(IJavaElement javaElement) { this.javaElement= javaElement; } public IJavaElement getJavaElement() { return javaElement; } public void setLimitTo(int limitTo) { this.limitTo= limitTo; } public int getLimitTo() { return limitTo; } public void setPattern(String pattern) { this.pattern= pattern; } public String getPattern() { return pattern; } public void setScope(int scope) { this.scope= scope; } public int getScope() { return scope; } public void setSearchFor(int searchFor) { this.searchFor= searchFor; } public int getSearchFor() { return searchFor; } public void setWorkingSets(IWorkingSet[] workingSets) { this.workingSets= workingSets; } public IWorkingSet[] getWorkingSets() { return workingSets; } } public static final String PARTICIPANT_EXTENSION_POINT= "org.eclipse.jdt.ui.queryParticipants"; //$NON-NLS-1$ public static final String EXTENSION_POINT_ID= "org.eclipse.jdt.ui.JavaSearchPage"; //$NON-NLS-1$ public static final String PREF_SEARCH_JRE= "org.eclipse.jdt.ui.searchJRE"; //$NON-NLS-1$ // Dialog store id constants private final static String PAGE_NAME= "JavaSearchPage"; //$NON-NLS-1$ private final static String STORE_CASE_SENSITIVE= PAGE_NAME + "CASE_SENSITIVE"; //$NON-NLS-1$ private static List fgPreviousSearchPatterns= new ArrayList(20); private SearchPatternData fInitialData; private IStructuredSelection fStructuredSelection; private IJavaElement fJavaElement; private boolean fFirstTime= true; private IDialogSettings fDialogSettings; private boolean fIsCaseSensitive; private Combo fPattern; private ISearchPageContainer fContainer; private Button fCaseSensitive; private Button[] fSearchFor; private String[] fSearchForText= { SearchMessages.getString("SearchPage.searchFor.type"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.searchFor.method"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.searchFor.package"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.searchFor.constructor"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.searchFor.field")}; //$NON-NLS-1$ private Button[] fLimitTo; private String[] fLimitToText= { SearchMessages.getString("SearchPage.limitTo.declarations"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.limitTo.implementors"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.limitTo.references"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.limitTo.allOccurrences"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.limitTo.readReferences"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.limitTo.writeReferences")};//$NON-NLS-1$ private Button fSearchJRE; private static final int INDEX_REFERENCES= 2; private static final int INDEX_ALL= 3; //---- Action Handling ------------------------------------------------ public boolean performAction() { if (JavaPlugin.useNewSearch()) { return performNewSearch(); } else { return performOldSearch(); } } private boolean performOldSearch() { org.eclipse.search.ui.SearchUI.activateSearchResultView(); SearchPatternData data= getPatternData(); IWorkspace workspace= JavaPlugin.getWorkspace(); // Setup search scope IJavaSearchScope scope= null; String scopeDescription= ""; //$NON-NLS-1$ boolean includeJRE= false; switch (getContainer().getSelectedScope()) { case ISearchPageContainer.WORKSPACE_SCOPE: scopeDescription= SearchMessages.getString("WorkspaceScope"); //$NON-NLS-1$ scope= SearchEngine.createWorkspaceScope(); break; case ISearchPageContainer.SELECTION_SCOPE: scopeDescription= SearchMessages.getString("SelectionScope"); //$NON-NLS-1$ scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(fStructuredSelection, includeJRE); break; case ISearchPageContainer.SELECTED_PROJECTS_SCOPE: scope= JavaSearchScopeFactory.getInstance().createJavaProjectSearchScope(fStructuredSelection, includeJRE); IProject[] projects= JavaSearchScopeFactory.getInstance().getProjects(scope); if (projects.length > 1) scopeDescription= SearchMessages.getFormattedString("EnclosingProjectsScope", projects[0].getName()); //$NON-NLS-1$ else if (projects.length == 1) scopeDescription= SearchMessages.getFormattedString("EnclosingProjectScope", projects[0].getName()); //$NON-NLS-1$ else scopeDescription= SearchMessages.getFormattedString("EnclosingProjectScope", ""); //$NON-NLS-1$ //$NON-NLS-2$ break; case ISearchPageContainer.WORKING_SET_SCOPE: IWorkingSet[] workingSets= getContainer().getSelectedWorkingSets(); // should not happen - just to be sure if (workingSets == null || workingSets.length < 1) return false; scopeDescription= SearchMessages.getFormattedString("WorkingSetScope", SearchUtil.toString(workingSets)); //$NON-NLS-1$ scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(getContainer().getSelectedWorkingSets(), includeJRE); SearchUtil.updateLRUWorkingSets(getContainer().getSelectedWorkingSets()); } JavaSearchResultCollector collector= new JavaSearchResultCollector(); JavaSearchOperation op= null; if (data.getJavaElement() != null && getPattern().equals(fInitialData.getPattern())) { op= new JavaSearchOperation(workspace, data.getJavaElement(), data.getLimitTo(), scope, scopeDescription, collector); if (data.getLimitTo() == IJavaSearchConstants.REFERENCES) SearchUtil.warnIfBinaryConstant(data.getJavaElement(), getShell()); } else { data.setJavaElement(null); op= new JavaSearchOperation(workspace, data.getPattern(), data.isCaseSensitive(), data.getSearchFor(), data.getLimitTo(), scope, scopeDescription, collector); } Shell shell= getControl().getShell(); try { getContainer().getRunnableContext().run(true, true, op); } catch (InvocationTargetException ex) { ExceptionHandler.handle(ex, shell, SearchMessages.getString("Search.Error.search.title"), SearchMessages.getString("Search.Error.search.message")); //$NON-NLS-2$ //$NON-NLS-1$ return false; } catch (InterruptedException ex) { return false; } return true; } private boolean performNewSearch() { org.eclipse.search.ui.NewSearchUI.activateSearchResultView(); SearchPatternData data= getPatternData(); // Setup search scope IJavaSearchScope scope= null; String scopeDescription= ""; //$NON-NLS-1$ boolean includeJRE= getSearchJRE() || !mayExcludeJRE(); switch (getContainer().getSelectedScope()) { case ISearchPageContainer.WORKSPACE_SCOPE: scopeDescription= SearchMessages.getString("WorkspaceScope"); //$NON-NLS-1$ scope= ReferenceScopeFactory.createWorkspaceScope(includeJRE); break; case ISearchPageContainer.SELECTION_SCOPE: scopeDescription= SearchMessages.getString("SelectionScope"); //$NON-NLS-1$ scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(fStructuredSelection, includeJRE); break; case ISearchPageContainer.SELECTED_PROJECTS_SCOPE: scope= JavaSearchScopeFactory.getInstance().createJavaProjectSearchScope(fStructuredSelection, includeJRE); IProject[] projects= JavaSearchScopeFactory.getInstance().getProjects(scope); if (projects.length >= 1) { if (projects.length == 1) scopeDescription= SearchMessages.getFormattedString("EnclosingProjectScope", projects[0].getName()); //$NON-NLS-1$ else scopeDescription= SearchMessages.getFormattedString("EnclosingProjectsScope", projects[0].getName()); //$NON-NLS-1$ } else scopeDescription= SearchMessages.getFormattedString("EnclosingProjectScope", ""); //$NON-NLS-1$ //$NON-NLS-2$ break; case ISearchPageContainer.WORKING_SET_SCOPE: IWorkingSet[] workingSets= getContainer().getSelectedWorkingSets(); // should not happen - just to be sure if (workingSets == null || workingSets.length < 1) return false; scopeDescription= SearchMessages.getFormattedString("WorkingSetScope", SearchUtil.toString(workingSets)); //$NON-NLS-1$ scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(getContainer().getSelectedWorkingSets(), includeJRE); SearchUtil.updateLRUWorkingSets(getContainer().getSelectedWorkingSets()); } JavaSearchQuery textSearchJob= null; QuerySpecification querySpec= null; if (data.getJavaElement() != null && getPattern().equals(fInitialData.getPattern())) { if (data.getLimitTo() == IJavaSearchConstants.REFERENCES) SearchUtil.warnIfBinaryConstant(data.getJavaElement(), getShell()); querySpec= new ElementQuerySpecification(data.getJavaElement(), data.getLimitTo(), scope, scopeDescription); } else { querySpec= new PatternQuerySpecification(data.getPattern(), data.getSearchFor(), data.isCaseSensitive(), data.getLimitTo(), scope, scopeDescription); data.setJavaElement(null); } textSearchJob= new JavaSearchQuery(querySpec); new SearchResultUpdater((JavaSearchResult) textSearchJob.getSearchResult()); NewSearchUI.runQuery(textSearchJob); return true; } private int getLimitTo() { for (int i= 0; i < fLimitTo.length; i++) { if (fLimitTo[i].getSelection()) return i; } return -1; } private void setLimitTo(int searchFor) { fLimitTo[DECLARATIONS].setEnabled(true); fLimitTo[IMPLEMENTORS].setEnabled(false); fLimitTo[REFERENCES].setEnabled(true); fLimitTo[ALL_OCCURRENCES].setEnabled(true); fLimitTo[READ_ACCESSES].setEnabled(false); fLimitTo[WRITE_ACCESSES].setEnabled(false); if (!(searchFor == TYPE || searchFor == INTERFACE) && fLimitTo[IMPLEMENTORS].getSelection()) { fLimitTo[IMPLEMENTORS].setSelection(false); fLimitTo[REFERENCES].setSelection(true); } if (!(searchFor == FIELD) && (getLimitTo() == READ_ACCESSES || getLimitTo() == WRITE_ACCESSES)) { fLimitTo[getLimitTo()].setSelection(false); fLimitTo[REFERENCES].setSelection(true); } switch (searchFor) { case TYPE: case INTERFACE: fLimitTo[IMPLEMENTORS].setEnabled(true); break; case FIELD: fLimitTo[READ_ACCESSES].setEnabled(true); fLimitTo[WRITE_ACCESSES].setEnabled(true); break; default : break; } } private String[] getPreviousSearchPatterns() { // Search results are not persistent int patternCount= fgPreviousSearchPatterns.size(); String [] patterns= new String[patternCount]; for (int i= 0; i < patternCount; i++) patterns[i]= ((SearchPatternData) fgPreviousSearchPatterns.get(patternCount - 1 - i)).getPattern(); return patterns; } private int getSearchFor() { for (int i= 0; i < fSearchFor.length; i++) { if (fSearchFor[i].getSelection()) return i; } Assert.isTrue(false, "shouldNeverHappen"); //$NON-NLS-1$ return -1; } private String getPattern() { return fPattern.getText(); } /** * Return search pattern data and update previous searches. * An existing entry will be updated. */ private SearchPatternData getPatternData() { String pattern= getPattern(); SearchPatternData match= null; int i= 0; int size= fgPreviousSearchPatterns.size(); while (match == null && i < size) { match= (SearchPatternData) fgPreviousSearchPatterns.get(i); i++; if (!pattern.equals(match.getPattern())) match= null; } if (match == null) { match= new SearchPatternData( getSearchFor(), getLimitTo(), pattern, fCaseSensitive.getSelection(), fJavaElement, getContainer().getSelectedScope(), getContainer().getSelectedWorkingSets()); fgPreviousSearchPatterns.add(match); } else { match.setSearchFor(getSearchFor()); match.setLimitTo(getLimitTo()); match.setCaseSensitive(fCaseSensitive.getSelection()); match.setJavaElement(fJavaElement); match.setScope(getContainer().getSelectedScope()); match.setWorkingSets(getContainer().getSelectedWorkingSets()); } return match; } /* * Implements method from IDialogPage */ public void setVisible(boolean visible) { if (visible && fPattern != null) { if (fFirstTime) { fFirstTime= false; // Set item and text here to prevent page from resizing fPattern.setItems(getPreviousSearchPatterns()); initSelections(); } fPattern.setFocus(); getContainer().setPerformActionEnabled(fPattern.getText().length() > 0); } super.setVisible(visible); } public boolean isValid() { return true; } //---- Widget creation ------------------------------------------------ /** * Creates the page's content. */ public void createControl(Composite parent) { initializeDialogUnits(parent); readConfiguration(); GridData gd; Composite result= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(2, false); layout.horizontalSpacing= 10; result.setLayout(layout); result.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); RowLayouter layouter= new RowLayouter(layout.numColumns); gd= new GridData(); gd.horizontalAlignment= GridData.FILL; gd.verticalAlignment= GridData.VERTICAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_FILL; layouter.setDefaultGridData(gd, 0); layouter.setDefaultGridData(gd, 1); layouter.setDefaultSpan(); layouter.perform(createExpression(result)); Control searchFor= createSearchFor(result); gd= new GridData(GridData.FILL_HORIZONTAL); gd.verticalAlignment= GridData.FILL; searchFor.setLayoutData(gd); Control limitTo= createLimitTo(result); gd= new GridData(GridData.FILL_HORIZONTAL); gd.verticalAlignment= GridData.FILL; limitTo.setLayoutData(gd); //createParticipants(result); SelectionAdapter javaElementInitializer= new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { if (getSearchFor() == fInitialData.getSearchFor()) fJavaElement= fInitialData.getJavaElement(); else fJavaElement= null; setLimitTo(getSearchFor()); updateCaseSensitiveCheckbox(); } }; fSearchFor[TYPE].addSelectionListener(javaElementInitializer); fSearchFor[METHOD].addSelectionListener(javaElementInitializer); fSearchFor[FIELD].addSelectionListener(javaElementInitializer); fSearchFor[CONSTRUCTOR].addSelectionListener(javaElementInitializer); fSearchFor[PACKAGE].addSelectionListener(javaElementInitializer); setControl(result); Dialog.applyDialogFont(result); WorkbenchHelp.setHelp(result, IJavaHelpContextIds.JAVA_SEARCH_PAGE); initSelections(); } private Control createSearchJRE(Composite result) { fSearchJRE= new Button(result, SWT.CHECK); fSearchJRE.setText(SearchMessages.getString("SearchPage.searchJRE.label")); //$NON-NLS-1$ fSearchJRE.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { setSearchJRE(fSearchJRE.getSelection()); } }); return fSearchJRE; } public static boolean getSearchJRE() { return JavaPlugin.getDefault().getPreferenceStore().getBoolean(PREF_SEARCH_JRE); } public static void setSearchJRE(boolean value) { JavaPlugin.getDefault().getPreferenceStore().setValue(PREF_SEARCH_JRE, value); } /*private Control createParticipants(Composite result) { if (!SearchParticipantsPreferencePage.hasAnyParticipants()) return new Composite(result, SWT.NULL); Button selectParticipants= new Button(result, SWT.PUSH); selectParticipants.setText(SearchMessages.getString("SearchPage.select_participants.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.verticalAlignment= GridData.VERTICAL_ALIGN_BEGINNING; gd.horizontalAlignment= GridData.HORIZONTAL_ALIGN_END; gd.grabExcessHorizontalSpace= false; gd.horizontalAlignment= GridData.END; gd.horizontalSpan= 2; selectParticipants.setLayoutData(gd); selectParticipants.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { PreferencePageSupport.showPreferencePage(getShell(), "org.eclipse.jdt.ui.preferences.SearchParticipantsPreferencePage", new SearchParticipantsPreferencePage()); //$NON-NLS-1$ } }); return selectParticipants; }*/ private Control createExpression(Composite parent) { Composite result= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(2, false); result.setLayout(layout); GridData gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL); gd.horizontalSpan= 2; gd.horizontalIndent= 0; result.setLayoutData(gd); // Pattern text + info Label label= new Label(result, SWT.LEFT); label.setText(SearchMessages.getString("SearchPage.expression.label")); //$NON-NLS-1$ gd= new GridData(GridData.BEGINNING); gd.horizontalSpan= 2; // gd.horizontalIndent= -gd.horizontalIndent; label.setLayoutData(gd); // Pattern combo fPattern= new Combo(result, SWT.SINGLE | SWT.BORDER); fPattern.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { handlePatternSelected(); } }); fPattern.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { getContainer().setPerformActionEnabled(getPattern().length() > 0); updateCaseSensitiveCheckbox(); } }); gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL); // limit preferred size gd.widthHint= convertWidthInCharsToPixels(50); gd.horizontalIndent= -gd.horizontalIndent; fPattern.setLayoutData(gd); // Ignore case checkbox fCaseSensitive= new Button(result, SWT.CHECK); fCaseSensitive.setText(SearchMessages.getString("SearchPage.expression.caseSensitive")); //$NON-NLS-1$ gd= new GridData(); fCaseSensitive.setLayoutData(gd); fCaseSensitive.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { fIsCaseSensitive= fCaseSensitive.getSelection(); writeConfiguration(); } }); return result; } private void updateCaseSensitiveCheckbox() { if (fInitialData != null && getPattern().equals(fInitialData.getPattern()) && fJavaElement != null) { fCaseSensitive.setEnabled(false); fCaseSensitive.setSelection(true); } else { fCaseSensitive.setEnabled(true); fCaseSensitive.setSelection(fIsCaseSensitive); } } private void handlePatternSelected() { if (fPattern.getSelectionIndex() < 0) return; int index= fgPreviousSearchPatterns.size() - 1 - fPattern.getSelectionIndex(); fInitialData= (SearchPatternData) fgPreviousSearchPatterns.get(index); for (int i= 0; i < fSearchFor.length; i++) fSearchFor[i].setSelection(false); for (int i= 0; i < fLimitTo.length; i++) fLimitTo[i].setSelection(false); fSearchFor[fInitialData.getSearchFor()].setSelection(true); setLimitTo(fInitialData.getSearchFor()); fLimitTo[fInitialData.getLimitTo()].setSelection(true); fPattern.setText(fInitialData.getPattern()); fIsCaseSensitive= fInitialData.isCaseSensitive(); fJavaElement= fInitialData.getJavaElement(); fCaseSensitive.setEnabled(fJavaElement == null); fCaseSensitive.setSelection(fInitialData.isCaseSensitive()); if (fInitialData.getWorkingSets() != null) getContainer().setSelectedWorkingSets(fInitialData.getWorkingSets()); else getContainer().setSelectedScope(fInitialData.getScope()); } private Control createSearchFor(Composite parent) { Group result= new Group(parent, SWT.NONE); result.setText(SearchMessages.getString("SearchPage.searchFor.label")); //$NON-NLS-1$ GridLayout layout= new GridLayout(); layout.numColumns= 3; result.setLayout(layout); fSearchFor= new Button[fSearchForText.length]; for (int i= 0; i < fSearchForText.length; i++) { Button button= new Button(result, SWT.RADIO); button.setText(fSearchForText[i]); fSearchFor[i]= button; } // Fill with dummy radio buttons Button filler= new Button(result, SWT.RADIO); filler.setVisible(false); filler= new Button(result, SWT.RADIO); filler.setVisible(false); return result; } private Control createLimitTo(Composite parent) { Group result= new Group(parent, SWT.NONE); result.setText(SearchMessages.getString("SearchPage.limitTo.label")); //$NON-NLS-1$ GridLayout layout= new GridLayout(); layout.numColumns= 2; result.setLayout(layout); SelectionAdapter listener= new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updateUseJRE(); } }; fLimitTo= new Button[fLimitToText.length]; for (int i= 0; i < fLimitToText.length; i++) { Button button= new Button(result, SWT.RADIO); button.setText(fLimitToText[i]); fLimitTo[i]= button; button.addSelectionListener(listener); } createSearchJRE(result); return result; } private void initSelections() { fStructuredSelection= asStructuredSelection(); fInitialData= tryStructuredSelection(fStructuredSelection); if (fInitialData == null) fInitialData= trySimpleTextSelection(getContainer().getSelection()); if (fInitialData == null) fInitialData= getDefaultInitValues(); fJavaElement= fInitialData.getJavaElement(); fCaseSensitive.setSelection(fInitialData.isCaseSensitive()); fCaseSensitive.setEnabled(fInitialData.getJavaElement() == null); fSearchFor[fInitialData.getSearchFor()].setSelection(true); setLimitTo(fInitialData.getSearchFor()); fLimitTo[fInitialData.getLimitTo()].setSelection(true); fPattern.setText(fInitialData.getPattern()); updateUseJRE(); } private void updateUseJRE() { boolean shouldEnable= mayExcludeJRE(); if (shouldEnable) { fSearchJRE.setSelection(getSearchJRE()); fSearchJRE.setEnabled(true); } else { fSearchJRE.setEnabled(false); fSearchJRE.setSelection(true); } } private boolean mayExcludeJRE() { return getLimitTo() == INDEX_REFERENCES || getLimitTo() == INDEX_ALL; } private SearchPatternData tryStructuredSelection(IStructuredSelection selection) { if (selection == null || selection.size() > 1) return null; Object o= selection.getFirstElement(); if (o instanceof IJavaElement) { return determineInitValuesFrom((IJavaElement)o); } else if (o instanceof ISearchResultViewEntry) { IJavaElement element= SearchUtil.getJavaElement(((ISearchResultViewEntry)o).getSelectedMarker()); return determineInitValuesFrom(element); } else if (o instanceof LogicalPackage) { LogicalPackage lp= (LogicalPackage)o; return new SearchPatternData(PACKAGE, REFERENCES, fIsCaseSensitive, lp.getElementName(), null); } else if (o instanceof IAdaptable) { IJavaElement element= (IJavaElement)((IAdaptable)o).getAdapter(IJavaElement.class); if (element != null) { return determineInitValuesFrom(element); } else { IWorkbenchAdapter adapter= (IWorkbenchAdapter)((IAdaptable)o).getAdapter(IWorkbenchAdapter.class); if (adapter != null) return new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive, adapter.getLabel(o), null); } } return null; } private SearchPatternData determineInitValuesFrom(IJavaElement element) { if (element == null) return null; int searchFor= UNKNOWN; int limitTo= UNKNOWN; String pattern= null; switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT: searchFor= PACKAGE; limitTo= REFERENCES; pattern= element.getElementName(); break; case IJavaElement.PACKAGE_FRAGMENT_ROOT: searchFor= PACKAGE; limitTo= REFERENCES; pattern= element.getElementName(); break; case IJavaElement.PACKAGE_DECLARATION: searchFor= PACKAGE; limitTo= REFERENCES; pattern= element.getElementName(); break; case IJavaElement.IMPORT_DECLARATION: pattern= element.getElementName(); IImportDeclaration declaration= (IImportDeclaration)element; if (declaration.isOnDemand()) { searchFor= PACKAGE; int index= pattern.lastIndexOf('.'); pattern= pattern.substring(0, index); } else { searchFor= TYPE; } limitTo= DECLARATIONS; break; case IJavaElement.TYPE: searchFor= TYPE; limitTo= REFERENCES; pattern= JavaModelUtil.getFullyQualifiedName((IType)element); break; case IJavaElement.COMPILATION_UNIT: ICompilationUnit cu= (ICompilationUnit)element; String mainTypeName= element.getElementName().substring(0, element.getElementName().indexOf(".")); //$NON-NLS-1$ IType mainType= cu.getType(mainTypeName); mainTypeName= JavaModelUtil.getTypeQualifiedName(mainType); try { mainType= JavaModelUtil.findTypeInCompilationUnit(cu, mainTypeName); if (mainType == null) { // fetch type which is declared first in the file IType[] types= cu.getTypes(); if (types.length > 0) mainType= types[0]; else break; } } catch (JavaModelException ex) { ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$ break; } searchFor= TYPE; element= mainType; limitTo= REFERENCES; pattern= JavaModelUtil.getFullyQualifiedName(mainType); break; case IJavaElement.CLASS_FILE: IClassFile cf= (IClassFile)element; try { mainType= cf.getType(); } catch (JavaModelException ex) { ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$ break; } if (mainType == null) break; element= mainType; searchFor= TYPE; limitTo= REFERENCES; pattern= JavaModelUtil.getFullyQualifiedName(mainType); break; case IJavaElement.FIELD: searchFor= FIELD; limitTo= REFERENCES; IType type= ((IField)element).getDeclaringType(); StringBuffer buffer= new StringBuffer(); buffer.append(JavaModelUtil.getFullyQualifiedName(type)); buffer.append('.'); buffer.append(element.getElementName()); pattern= buffer.toString(); break; case IJavaElement.METHOD: searchFor= METHOD; try { IMethod method= (IMethod)element; if (method.isConstructor()) searchFor= CONSTRUCTOR; } catch (JavaModelException ex) { ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$ break; } limitTo= REFERENCES; pattern= PrettySignature.getMethodSignature((IMethod)element); break; } if (searchFor != UNKNOWN && limitTo != UNKNOWN && pattern != null) return new SearchPatternData(searchFor, limitTo, true, pattern, element); return null; } private SearchPatternData trySimpleTextSelection(ISelection selection) { SearchPatternData result= null; if (selection instanceof ITextSelection) { BufferedReader reader= new BufferedReader(new StringReader(((ITextSelection)selection).getText())); String text; try { text= reader.readLine(); if (text == null) text= ""; //$NON-NLS-1$ } catch (IOException ex) { text= ""; //$NON-NLS-1$ } result= new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive, text, null); } return result; } private SearchPatternData getDefaultInitValues() { return new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive, "", null); //$NON-NLS-1$ } /* * Implements method from ISearchPage */ public void setContainer(ISearchPageContainer container) { fContainer= container; } /** * Returns the search page's container. */ private ISearchPageContainer getContainer() { return fContainer; } /** * Returns the structured selection from the selection. */ private IStructuredSelection asStructuredSelection() { IWorkbenchWindow wbWindow= PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (wbWindow != null) { IWorkbenchPage page= wbWindow.getActivePage(); if (page != null) { IWorkbenchPart part= page.getActivePart(); if (part != null) try { return SelectionConverter.getStructuredSelection(part); } catch (JavaModelException ex) { // ignore handled by return } } } return StructuredSelection.EMPTY; } //--------------- Configuration handling -------------- /** * Returns the page settings for this Java search page. * * @return the page settings to be used */ private IDialogSettings getDialogSettings() { IDialogSettings settings= JavaPlugin.getDefault().getDialogSettings(); fDialogSettings= settings.getSection(PAGE_NAME); if (fDialogSettings == null) fDialogSettings= settings.addNewSection(PAGE_NAME); return fDialogSettings; } /** * Initializes itself from the stored page settings. */ private void readConfiguration() { IDialogSettings s= getDialogSettings(); fIsCaseSensitive= s.getBoolean(STORE_CASE_SENSITIVE); } private void collectConcernedProjects(Set projects, ISelection selection) { if (!(selection instanceof IStructuredSelection)) return; IStructuredSelection structuredSelection= (IStructuredSelection)selection; Iterator elements= structuredSelection.iterator(); while (elements.hasNext()) { IProject project= getProject(elements.next()); if (project != null) projects.add(project); } } /** * Stores it current configuration in the dialog store. */ private void writeConfiguration() { IDialogSettings s= getDialogSettings(); s.put(STORE_CASE_SENSITIVE, fIsCaseSensitive); } private void collectConcernedProjects(Set projects, IWorkingSet[] workingSets) { for (int i= 0; i < workingSets.length; i++) collectConcernedProjects(projects, workingSets[i]); } private void collectConcernedProjects(Set projects, IWorkingSet workingSet) { IAdaptable[] adaptables= workingSet.getElements(); for (int i= 0; i < adaptables.length; i++) { IProject project= getProject(adaptables[i]); if (project != null) projects.add(project); } } private void collectConcernedProjects(Set projects, IWorkspace workspace) { IProject[] allProjects= workspace.getRoot().getProjects(); for (int i= 0; i < allProjects.length; i++) { if (allProjects[i].isAccessible()) projects.add(allProjects[i]); } } private IProject getProject(Object element) { if (element instanceof ISearchResultViewEntry) element= ((ISearchResultViewEntry)element).getGroupByKey(); if (element instanceof IAdaptable) { IAdaptable adaptable= (IAdaptable)element; IProject project= (IProject) adaptable.getAdapter(IProject.class); if (project != null) return project; IResource resource= (IResource) adaptable.getAdapter(IResource.class); if (resource != null) project= resource.getProject(); if (project != null) return project; } return null; } }
60,415
Bug 60415 Should remove Search extension page
I20040428 We should remove the search extension page and should make sure that participants can't damage a search. If a participant generates an exception the participant should be disabled for the rest of the Eclipse sessions. This is consistent with Platform/UI and refactoring.
resolved fixed
b56f924
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-10T14:46:27Z
2004-04-29T14:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchQuery.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.search; import java.text.MessageFormat; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.core.search.SearchParticipant; import org.eclipse.jdt.core.search.SearchPattern; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.preferences.SearchParticipantsPreferencePage; import org.eclipse.jdt.ui.search.ElementQuerySpecification; import org.eclipse.jdt.ui.search.IMatchPresentation; import org.eclipse.jdt.ui.search.IQueryParticipant; import org.eclipse.jdt.ui.search.ISearchRequestor; import org.eclipse.jdt.ui.search.PatternQuerySpecification; import org.eclipse.jdt.ui.search.QuerySpecification; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.search.internal.ui.SearchPreferencePage; import org.eclipse.search.ui.ISearchQuery; import org.eclipse.search.ui.ISearchResult; import org.eclipse.search.ui.text.Match; public class JavaSearchQuery implements ISearchQuery { private ISearchResult fResult; private QuerySpecification fPatternData; public JavaSearchQuery(QuerySpecification data) { fPatternData= data; } private static class SearchRequestor implements ISearchRequestor { private IQueryParticipant fParticipant; private JavaSearchResult fSearchResult; public void reportMatch(Match match) { IMatchPresentation participant= fParticipant.getUIParticipant(); if (participant == null || match.getElement() instanceof IJavaElement || match.getElement() instanceof IResource) { fSearchResult.addMatch(match); } else { fSearchResult.addMatch(match, participant); } } protected SearchRequestor(IQueryParticipant participant, JavaSearchResult result) { super(); fParticipant= participant; fSearchResult= result; } } private IQueryParticipant[] getSearchParticipants(IProject[] concernedProjects) throws CoreException { Map participantMap= new HashMap(); collectParticipants(participantMap, concernedProjects); IQueryParticipant[] participants= new IQueryParticipant[participantMap.size()]; return (IQueryParticipant[]) participantMap.values().toArray(participants); } private void collectParticipants(Map participants, IProject[] projects) throws CoreException { Iterator activeParticipants= SearchParticipantsPreferencePage.readAllParticipants().values().iterator(); while (activeParticipants.hasNext()) { IConfigurationElement participant= (IConfigurationElement) activeParticipants.next(); String id= participant.getAttribute("id"); //$NON-NLS-1$ for (int i= 0; i < projects.length; i++) { if (participants.containsKey(id)) break; if (projects[i].hasNature(participant.getAttribute("nature"))) //$NON-NLS-1$ participants.put(id, participant.createExecutableExtension("class")); //$NON-NLS-1$ } } } public IStatus run(IProgressMonitor monitor) { final JavaSearchResult textResult= (JavaSearchResult) getSearchResult(); textResult.removeAll(); // Don't need to pass in working copies in 3.0 here SearchEngine engine= new SearchEngine(); try { int totalTicks= 1000; IProject[] projects= JavaSearchScopeFactory.getInstance().getProjects(fPatternData.getScope()); IQueryParticipant[] participants= getSearchParticipants(projects); int[] ticks= new int[participants.length]; for (int i= 0; i < participants.length; i++) { ticks[i]= participants[i].estimateTicks(fPatternData); totalTicks+= ticks[i]; } monitor.beginTask(SearchMessages.getString("JavaSearchQuery.task.label"), totalTicks); //$NON-NLS-1$ IProgressMonitor mainSearchPM= new SubProgressMonitor(monitor, 1000); boolean ignorePotentials= SearchPreferencePage.arePotentialMatchesIgnored(); NewSearchResultCollector collector= new NewSearchResultCollector(textResult, ignorePotentials); SearchPattern pattern; String stringPattern= null; if (fPatternData instanceof ElementQuerySpecification) { pattern= SearchPattern.createPattern(((ElementQuerySpecification)fPatternData).getElement(), fPatternData.getLimitTo()); stringPattern= ((ElementQuerySpecification)fPatternData).getElement().getElementName(); } else { PatternQuerySpecification patternSpec = (PatternQuerySpecification) fPatternData; stringPattern = patternSpec.getPattern(); int matchMode = stringPattern.indexOf('*') != -1 || stringPattern.indexOf('?') != -1 ? SearchPattern.R_PATTERN_MATCH : SearchPattern.R_EXACT_MATCH; if (patternSpec.isCaseSensitive()) matchMode |= SearchPattern.R_CASE_SENSITIVE; pattern = SearchPattern.createPattern(patternSpec.getPattern(), patternSpec.getSearchFor(), patternSpec.getLimitTo(), matchMode); } if (pattern == null) { return new Status(IStatus.ERROR, JavaPlugin.getPluginId(), 0, SearchMessages.getFormattedString("JavaSearchQuery.error.unsupported_pattern", stringPattern), null); //$NON-NLS-1$ } engine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, fPatternData.getScope(), collector, mainSearchPM); for (int i= 0; i < participants.length; i++) { ISearchRequestor requestor= new SearchRequestor(participants[i], textResult); IProgressMonitor participantPM= new SubProgressMonitor(monitor, ticks[i]); participants[i].search(requestor, fPatternData, participantPM); } } catch (CoreException e) { return e.getStatus(); } // TODO fix status message String message= SearchMessages.getString("JavaSearchQuery.status.ok.message"); //$NON-NLS-1$ MessageFormat.format(message, new Object[] { new Integer(textResult.getMatchCount()) }); return new Status(IStatus.OK, JavaPlugin.getPluginId(), 0, message, null); } public String getLabel() { if (fPatternData.getLimitTo() == IJavaSearchConstants.REFERENCES) return SearchMessages.getString("JavaSearchQuery.searchfor_references"); //$NON-NLS-1$ else if (fPatternData.getLimitTo() == IJavaSearchConstants.DECLARATIONS) return SearchMessages.getString("JavaSearchQuery.searchfor_declarations"); //$NON-NLS-1$ else if (fPatternData.getLimitTo() == IJavaSearchConstants.READ_ACCESSES) return SearchMessages.getString("JavaSearchQuery.searchfor_read_access"); //$NON-NLS-1$ else if (fPatternData.getLimitTo() == IJavaSearchConstants.WRITE_ACCESSES) return SearchMessages.getString("JavaSearchQuery.searchfor_write_access"); //$NON-NLS-1$ else if (fPatternData.getLimitTo() == IJavaSearchConstants.IMPLEMENTORS) return SearchMessages.getString("JavaSearchQuery.searchfor_implementors"); //$NON-NLS-1$ return SearchMessages.getString("JavaSearchQuery.search_label"); //$NON-NLS-1$ } String getSingularLabel() { String desc= null; if (fPatternData instanceof ElementQuerySpecification) { IJavaElement element= ((ElementQuerySpecification)fPatternData).getElement(); if (fPatternData.getLimitTo() == IJavaSearchConstants.REFERENCES && element.getElementType() == IJavaElement.METHOD) desc= PrettySignature.getUnqualifiedMethodSignature((IMethod)element); else desc= element.getElementName(); if ("".equals(desc) && element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) //$NON-NLS-1$ desc= SearchMessages.getString("JavaSearchOperation.default_package"); //$NON-NLS-1$ } else { desc= ((PatternQuerySpecification)fPatternData).getPattern(); } desc= "\""+desc+"\""; //$NON-NLS-1$ //$NON-NLS-2$ String[] args= new String[] {desc, fPatternData.getScopeDescription()}; //$NON-NLS-1$ switch (fPatternData.getLimitTo()) { case IJavaSearchConstants.IMPLEMENTORS: return SearchMessages.getFormattedString("JavaSearchOperation.singularImplementorsPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.DECLARATIONS: return SearchMessages.getFormattedString("JavaSearchOperation.singularDeclarationsPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.REFERENCES: return SearchMessages.getFormattedString("JavaSearchOperation.singularReferencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.ALL_OCCURRENCES: return SearchMessages.getFormattedString("JavaSearchOperation.singularOccurrencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.READ_ACCESSES: return SearchMessages.getFormattedString("JavaSearchOperation.singularReadReferencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.WRITE_ACCESSES: return SearchMessages.getFormattedString("JavaSearchOperation.singularWriteReferencesPostfix", args); //$NON-NLS-1$ default: return SearchMessages.getFormattedString("JavaSearchOperation.singularOccurrencesPostfix", args); //$NON-NLS-1$; } } String getPluralLabelPattern() { String desc= null; if (fPatternData instanceof ElementQuerySpecification) { IJavaElement element= ((ElementQuerySpecification)fPatternData).getElement(); if (fPatternData.getLimitTo() == IJavaSearchConstants.REFERENCES && element.getElementType() == IJavaElement.METHOD) desc= PrettySignature.getUnqualifiedMethodSignature((IMethod)element); else desc= element.getElementName(); if ("".equals(desc) && element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) //$NON-NLS-1$ desc= SearchMessages.getString("JavaSearchOperation.default_package"); //$NON-NLS-1$ } else { desc= ((PatternQuerySpecification)fPatternData).getPattern(); } desc= "\""+desc+"\""; //$NON-NLS-1$ //$NON-NLS-2$ String[] args= new String[] {desc, "{0}", fPatternData.getScopeDescription()}; //$NON-NLS-1$ switch (fPatternData.getLimitTo()) { case IJavaSearchConstants.IMPLEMENTORS: return SearchMessages.getFormattedString("JavaSearchOperation.pluralImplementorsPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.DECLARATIONS: return SearchMessages.getFormattedString("JavaSearchOperation.pluralDeclarationsPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.REFERENCES: return SearchMessages.getFormattedString("JavaSearchOperation.pluralReferencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.ALL_OCCURRENCES: return SearchMessages.getFormattedString("JavaSearchOperation.pluralOccurrencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.READ_ACCESSES: return SearchMessages.getFormattedString("JavaSearchOperation.pluralReadReferencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.WRITE_ACCESSES: return SearchMessages.getFormattedString("JavaSearchOperation.pluralWriteReferencesPostfix", args); //$NON-NLS-1$ default: return SearchMessages.getFormattedString("JavaSearchOperation.pluralOccurrencesPostfix", args); //$NON-NLS-1$; } } ImageDescriptor getImageDescriptor() { if (fPatternData.getLimitTo() == IJavaSearchConstants.IMPLEMENTORS || fPatternData.getLimitTo() == IJavaSearchConstants.DECLARATIONS) return JavaPluginImages.DESC_OBJS_SEARCH_DECL; else return JavaPluginImages.DESC_OBJS_SEARCH_REF; } public boolean canRerun() { return true; } public boolean canRunInBackground() { return true; } public ISearchResult getSearchResult() { if (fResult == null) fResult= new JavaSearchResult(this); return fResult; } QuerySpecification getSpecification() { return fPatternData; } }
60,415
Bug 60415 Should remove Search extension page
I20040428 We should remove the search extension page and should make sure that participants can't damage a search. If a participant generates an exception the participant should be disabled for the rest of the Eclipse sessions. This is consistent with Platform/UI and refactoring.
resolved fixed
b56f924
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-10T14:46:27Z
2004-04-29T14:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/SearchParticipantDescriptor.java
60,415
Bug 60415 Should remove Search extension page
I20040428 We should remove the search extension page and should make sure that participants can't damage a search. If a participant generates an exception the participant should be disabled for the rest of the Eclipse sessions. This is consistent with Platform/UI and refactoring.
resolved fixed
b56f924
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-10T14:46:27Z
2004-04-29T14:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/SearchParticipantRecord.java
60,415
Bug 60415 Should remove Search extension page
I20040428 We should remove the search extension page and should make sure that participants can't damage a search. If a participant generates an exception the participant should be disabled for the rest of the Eclipse sessions. This is consistent with Platform/UI and refactoring.
resolved fixed
b56f924
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-10T14:46:27Z
2004-04-29T14:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/SearchParticipantsExtensionPoint.java
60,415
Bug 60415 Should remove Search extension page
I20040428 We should remove the search extension page and should make sure that participants can't damage a search. If a participant generates an exception the participant should be disabled for the rest of the Eclipse sessions. This is consistent with Platform/UI and refactoring.
resolved fixed
b56f924
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-10T14:46:27Z
2004-04-29T14:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/SearchResultUpdater.java
61,699
Bug 61699 NPE When searching without text selection
I-2004-05-11 I had a case where the I had a NPE in JavaSearchPage.trySimpleTextSelection. Inspection of the code revealed that ITextSelection.getText() can return null, but we're not checking the condition.
resolved fixed
fc251fa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T08:48:53Z
2004-05-11T10:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchPage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.search; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.browsing.LogicalPackage; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.util.RowLayouter; import org.eclipse.jdt.ui.search.ElementQuerySpecification; import org.eclipse.jdt.ui.search.PatternQuerySpecification; import org.eclipse.jdt.ui.search.QuerySpecification; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.DialogPage; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.search.ui.ISearchPage; import org.eclipse.search.ui.ISearchPageContainer; import org.eclipse.search.ui.ISearchResultViewEntry; import org.eclipse.search.ui.NewSearchUI; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkingSet; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.IWorkbenchAdapter; public class JavaSearchPage extends DialogPage implements ISearchPage, IJavaSearchConstants { private static class SearchPatternData { private int searchFor; private int limitTo; private String pattern; private boolean isCaseSensitive; private IJavaElement javaElement; private int scope; private IWorkingSet[] workingSets; public SearchPatternData(int searchFor, int limitTo, boolean isCaseSensitive, String pattern, IJavaElement element) { this(searchFor, limitTo, pattern, isCaseSensitive, element, ISearchPageContainer.WORKSPACE_SCOPE, null); } public SearchPatternData(int s, int l, String p, boolean i, IJavaElement element, int scope, IWorkingSet[] workingSets) { setSearchFor(s); setLimitTo(l); setPattern(p); setCaseSensitive(i); setJavaElement(element); this.setScope(scope); this.setWorkingSets(workingSets); } public void setCaseSensitive(boolean isCaseSensitive) { this.isCaseSensitive= isCaseSensitive; } public boolean isCaseSensitive() { return isCaseSensitive; } public void setJavaElement(IJavaElement javaElement) { this.javaElement= javaElement; } public IJavaElement getJavaElement() { return javaElement; } public void setLimitTo(int limitTo) { this.limitTo= limitTo; } public int getLimitTo() { return limitTo; } public void setPattern(String pattern) { this.pattern= pattern; } public String getPattern() { return pattern; } public void setScope(int scope) { this.scope= scope; } public int getScope() { return scope; } public void setSearchFor(int searchFor) { this.searchFor= searchFor; } public int getSearchFor() { return searchFor; } public void setWorkingSets(IWorkingSet[] workingSets) { this.workingSets= workingSets; } public IWorkingSet[] getWorkingSets() { return workingSets; } } public static final String PARTICIPANT_EXTENSION_POINT= "org.eclipse.jdt.ui.queryParticipants"; //$NON-NLS-1$ public static final String EXTENSION_POINT_ID= "org.eclipse.jdt.ui.JavaSearchPage"; //$NON-NLS-1$ public static final String PREF_SEARCH_JRE= "org.eclipse.jdt.ui.searchJRE"; //$NON-NLS-1$ // Dialog store id constants private final static String PAGE_NAME= "JavaSearchPage"; //$NON-NLS-1$ private final static String STORE_CASE_SENSITIVE= PAGE_NAME + "CASE_SENSITIVE"; //$NON-NLS-1$ private static List fgPreviousSearchPatterns= new ArrayList(20); private SearchPatternData fInitialData; private IStructuredSelection fStructuredSelection; private IJavaElement fJavaElement; private boolean fFirstTime= true; private IDialogSettings fDialogSettings; private boolean fIsCaseSensitive; private Combo fPattern; private ISearchPageContainer fContainer; private Button fCaseSensitive; private Button[] fSearchFor; private String[] fSearchForText= { SearchMessages.getString("SearchPage.searchFor.type"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.searchFor.method"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.searchFor.package"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.searchFor.constructor"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.searchFor.field")}; //$NON-NLS-1$ private Button[] fLimitTo; private String[] fLimitToText= { SearchMessages.getString("SearchPage.limitTo.declarations"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.limitTo.implementors"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.limitTo.references"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.limitTo.allOccurrences"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.limitTo.readReferences"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.limitTo.writeReferences")};//$NON-NLS-1$ private Button fSearchJRE; private static final int INDEX_REFERENCES= 2; private static final int INDEX_ALL= 3; //---- Action Handling ------------------------------------------------ public boolean performAction() { if (JavaPlugin.useNewSearch()) { return performNewSearch(); } else { return performOldSearch(); } } private boolean performOldSearch() { org.eclipse.search.ui.SearchUI.activateSearchResultView(); SearchPatternData data= getPatternData(); IWorkspace workspace= JavaPlugin.getWorkspace(); // Setup search scope IJavaSearchScope scope= null; String scopeDescription= ""; //$NON-NLS-1$ boolean includeJRE= false; switch (getContainer().getSelectedScope()) { case ISearchPageContainer.WORKSPACE_SCOPE: scopeDescription= SearchMessages.getString("WorkspaceScope"); //$NON-NLS-1$ scope= SearchEngine.createWorkspaceScope(); break; case ISearchPageContainer.SELECTION_SCOPE: scopeDescription= SearchMessages.getString("SelectionScope"); //$NON-NLS-1$ scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(fStructuredSelection, includeJRE); break; case ISearchPageContainer.SELECTED_PROJECTS_SCOPE: scope= JavaSearchScopeFactory.getInstance().createJavaProjectSearchScope(fStructuredSelection, includeJRE); IProject[] projects= JavaSearchScopeFactory.getInstance().getProjects(scope); if (projects.length > 1) scopeDescription= SearchMessages.getFormattedString("EnclosingProjectsScope", projects[0].getName()); //$NON-NLS-1$ else if (projects.length == 1) scopeDescription= SearchMessages.getFormattedString("EnclosingProjectScope", projects[0].getName()); //$NON-NLS-1$ else scopeDescription= SearchMessages.getFormattedString("EnclosingProjectScope", ""); //$NON-NLS-1$ //$NON-NLS-2$ break; case ISearchPageContainer.WORKING_SET_SCOPE: IWorkingSet[] workingSets= getContainer().getSelectedWorkingSets(); // should not happen - just to be sure if (workingSets == null || workingSets.length < 1) return false; scopeDescription= SearchMessages.getFormattedString("WorkingSetScope", SearchUtil.toString(workingSets)); //$NON-NLS-1$ scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(getContainer().getSelectedWorkingSets(), includeJRE); SearchUtil.updateLRUWorkingSets(getContainer().getSelectedWorkingSets()); } JavaSearchResultCollector collector= new JavaSearchResultCollector(); JavaSearchOperation op= null; if (data.getJavaElement() != null && getPattern().equals(fInitialData.getPattern())) { op= new JavaSearchOperation(workspace, data.getJavaElement(), data.getLimitTo(), scope, scopeDescription, collector); if (data.getLimitTo() == IJavaSearchConstants.REFERENCES) SearchUtil.warnIfBinaryConstant(data.getJavaElement(), getShell()); } else { data.setJavaElement(null); op= new JavaSearchOperation(workspace, data.getPattern(), data.isCaseSensitive(), data.getSearchFor(), data.getLimitTo(), scope, scopeDescription, collector); } Shell shell= getControl().getShell(); try { getContainer().getRunnableContext().run(true, true, op); } catch (InvocationTargetException ex) { ExceptionHandler.handle(ex, shell, SearchMessages.getString("Search.Error.search.title"), SearchMessages.getString("Search.Error.search.message")); //$NON-NLS-2$ //$NON-NLS-1$ return false; } catch (InterruptedException ex) { return false; } return true; } private boolean performNewSearch() { org.eclipse.search.ui.NewSearchUI.activateSearchResultView(); SearchPatternData data= getPatternData(); // Setup search scope IJavaSearchScope scope= null; String scopeDescription= ""; //$NON-NLS-1$ boolean includeJRE= getSearchJRE() || !mayExcludeJRE(); switch (getContainer().getSelectedScope()) { case ISearchPageContainer.WORKSPACE_SCOPE: scopeDescription= SearchMessages.getString("WorkspaceScope"); //$NON-NLS-1$ scope= ReferenceScopeFactory.createWorkspaceScope(includeJRE); break; case ISearchPageContainer.SELECTION_SCOPE: scopeDescription= SearchMessages.getString("SelectionScope"); //$NON-NLS-1$ scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(fStructuredSelection, includeJRE); break; case ISearchPageContainer.SELECTED_PROJECTS_SCOPE: scope= JavaSearchScopeFactory.getInstance().createJavaProjectSearchScope(fStructuredSelection, includeJRE); IProject[] projects= JavaSearchScopeFactory.getInstance().getProjects(scope); if (projects.length >= 1) { if (projects.length == 1) scopeDescription= SearchMessages.getFormattedString("EnclosingProjectScope", projects[0].getName()); //$NON-NLS-1$ else scopeDescription= SearchMessages.getFormattedString("EnclosingProjectsScope", projects[0].getName()); //$NON-NLS-1$ } else scopeDescription= SearchMessages.getFormattedString("EnclosingProjectScope", ""); //$NON-NLS-1$ //$NON-NLS-2$ break; case ISearchPageContainer.WORKING_SET_SCOPE: IWorkingSet[] workingSets= getContainer().getSelectedWorkingSets(); // should not happen - just to be sure if (workingSets == null || workingSets.length < 1) return false; scopeDescription= SearchMessages.getFormattedString("WorkingSetScope", SearchUtil.toString(workingSets)); //$NON-NLS-1$ scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(getContainer().getSelectedWorkingSets(), includeJRE); SearchUtil.updateLRUWorkingSets(getContainer().getSelectedWorkingSets()); } JavaSearchQuery textSearchJob= null; QuerySpecification querySpec= null; if (data.getJavaElement() != null && getPattern().equals(fInitialData.getPattern())) { if (data.getLimitTo() == IJavaSearchConstants.REFERENCES) SearchUtil.warnIfBinaryConstant(data.getJavaElement(), getShell()); querySpec= new ElementQuerySpecification(data.getJavaElement(), data.getLimitTo(), scope, scopeDescription); } else { querySpec= new PatternQuerySpecification(data.getPattern(), data.getSearchFor(), data.isCaseSensitive(), data.getLimitTo(), scope, scopeDescription); data.setJavaElement(null); } textSearchJob= new JavaSearchQuery(querySpec); new SearchResultUpdater((JavaSearchResult) textSearchJob.getSearchResult()); NewSearchUI.runQuery(textSearchJob); return true; } private int getLimitTo() { for (int i= 0; i < fLimitTo.length; i++) { if (fLimitTo[i].getSelection()) return i; } return -1; } private void setLimitTo(int searchFor) { fLimitTo[DECLARATIONS].setEnabled(true); fLimitTo[IMPLEMENTORS].setEnabled(false); fLimitTo[REFERENCES].setEnabled(true); fLimitTo[ALL_OCCURRENCES].setEnabled(true); fLimitTo[READ_ACCESSES].setEnabled(false); fLimitTo[WRITE_ACCESSES].setEnabled(false); if (!(searchFor == TYPE || searchFor == INTERFACE) && fLimitTo[IMPLEMENTORS].getSelection()) { fLimitTo[IMPLEMENTORS].setSelection(false); fLimitTo[REFERENCES].setSelection(true); } if (!(searchFor == FIELD) && (getLimitTo() == READ_ACCESSES || getLimitTo() == WRITE_ACCESSES)) { fLimitTo[getLimitTo()].setSelection(false); fLimitTo[REFERENCES].setSelection(true); } switch (searchFor) { case TYPE: case INTERFACE: fLimitTo[IMPLEMENTORS].setEnabled(true); break; case FIELD: fLimitTo[READ_ACCESSES].setEnabled(true); fLimitTo[WRITE_ACCESSES].setEnabled(true); break; default : break; } } private String[] getPreviousSearchPatterns() { // Search results are not persistent int patternCount= fgPreviousSearchPatterns.size(); String [] patterns= new String[patternCount]; for (int i= 0; i < patternCount; i++) patterns[i]= ((SearchPatternData) fgPreviousSearchPatterns.get(patternCount - 1 - i)).getPattern(); return patterns; } private int getSearchFor() { for (int i= 0; i < fSearchFor.length; i++) { if (fSearchFor[i].getSelection()) return i; } Assert.isTrue(false, "shouldNeverHappen"); //$NON-NLS-1$ return -1; } private String getPattern() { return fPattern.getText(); } /** * Return search pattern data and update previous searches. * An existing entry will be updated. */ private SearchPatternData getPatternData() { String pattern= getPattern(); SearchPatternData match= null; int i= 0; int size= fgPreviousSearchPatterns.size(); while (match == null && i < size) { match= (SearchPatternData) fgPreviousSearchPatterns.get(i); i++; if (!pattern.equals(match.getPattern())) match= null; } if (match == null) { match= new SearchPatternData( getSearchFor(), getLimitTo(), pattern, fCaseSensitive.getSelection(), fJavaElement, getContainer().getSelectedScope(), getContainer().getSelectedWorkingSets()); fgPreviousSearchPatterns.add(match); } else { match.setSearchFor(getSearchFor()); match.setLimitTo(getLimitTo()); match.setCaseSensitive(fCaseSensitive.getSelection()); match.setJavaElement(fJavaElement); match.setScope(getContainer().getSelectedScope()); match.setWorkingSets(getContainer().getSelectedWorkingSets()); } return match; } /* * Implements method from IDialogPage */ public void setVisible(boolean visible) { if (visible && fPattern != null) { if (fFirstTime) { fFirstTime= false; // Set item and text here to prevent page from resizing fPattern.setItems(getPreviousSearchPatterns()); initSelections(); } fPattern.setFocus(); getContainer().setPerformActionEnabled(fPattern.getText().length() > 0); } super.setVisible(visible); } public boolean isValid() { return true; } //---- Widget creation ------------------------------------------------ /** * Creates the page's content. */ public void createControl(Composite parent) { initializeDialogUnits(parent); readConfiguration(); GridData gd; Composite result= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(2, false); layout.horizontalSpacing= 10; result.setLayout(layout); result.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); RowLayouter layouter= new RowLayouter(layout.numColumns); gd= new GridData(); gd.horizontalAlignment= GridData.FILL; gd.verticalAlignment= GridData.VERTICAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_FILL; layouter.setDefaultGridData(gd, 0); layouter.setDefaultGridData(gd, 1); layouter.setDefaultSpan(); layouter.perform(createExpression(result)); Control searchFor= createSearchFor(result); gd= new GridData(GridData.FILL_HORIZONTAL); gd.verticalAlignment= GridData.FILL; searchFor.setLayoutData(gd); Control limitTo= createLimitTo(result); gd= new GridData(GridData.FILL_HORIZONTAL); gd.verticalAlignment= GridData.FILL; limitTo.setLayoutData(gd); //createParticipants(result); SelectionAdapter javaElementInitializer= new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { if (getSearchFor() == fInitialData.getSearchFor()) fJavaElement= fInitialData.getJavaElement(); else fJavaElement= null; setLimitTo(getSearchFor()); updateCaseSensitiveCheckbox(); } }; fSearchFor[TYPE].addSelectionListener(javaElementInitializer); fSearchFor[METHOD].addSelectionListener(javaElementInitializer); fSearchFor[FIELD].addSelectionListener(javaElementInitializer); fSearchFor[CONSTRUCTOR].addSelectionListener(javaElementInitializer); fSearchFor[PACKAGE].addSelectionListener(javaElementInitializer); setControl(result); Dialog.applyDialogFont(result); WorkbenchHelp.setHelp(result, IJavaHelpContextIds.JAVA_SEARCH_PAGE); initSelections(); } private Control createSearchJRE(Composite result) { fSearchJRE= new Button(result, SWT.CHECK); fSearchJRE.setText(SearchMessages.getString("SearchPage.searchJRE.label")); //$NON-NLS-1$ fSearchJRE.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { setSearchJRE(fSearchJRE.getSelection()); } }); return fSearchJRE; } public static boolean getSearchJRE() { return JavaPlugin.getDefault().getPreferenceStore().getBoolean(PREF_SEARCH_JRE); } public static void setSearchJRE(boolean value) { JavaPlugin.getDefault().getPreferenceStore().setValue(PREF_SEARCH_JRE, value); } /*private Control createParticipants(Composite result) { if (!SearchParticipantsExtensionPoint.hasAnyParticipants()) return new Composite(result, SWT.NULL); Button selectParticipants= new Button(result, SWT.PUSH); selectParticipants.setText(SearchMessages.getString("SearchPage.select_participants.label")); //$NON-NLS-1$ GridData gd= new GridData(); gd.verticalAlignment= GridData.VERTICAL_ALIGN_BEGINNING; gd.horizontalAlignment= GridData.HORIZONTAL_ALIGN_END; gd.grabExcessHorizontalSpace= false; gd.horizontalAlignment= GridData.END; gd.horizontalSpan= 2; selectParticipants.setLayoutData(gd); selectParticipants.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { PreferencePageSupport.showPreferencePage(getShell(), "org.eclipse.jdt.ui.preferences.SearchParticipantsExtensionPoint", new SearchParticipantsExtensionPoint()); //$NON-NLS-1$ } }); return selectParticipants; }*/ private Control createExpression(Composite parent) { Composite result= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(2, false); result.setLayout(layout); GridData gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL); gd.horizontalSpan= 2; gd.horizontalIndent= 0; result.setLayoutData(gd); // Pattern text + info Label label= new Label(result, SWT.LEFT); label.setText(SearchMessages.getString("SearchPage.expression.label")); //$NON-NLS-1$ gd= new GridData(GridData.BEGINNING); gd.horizontalSpan= 2; // gd.horizontalIndent= -gd.horizontalIndent; label.setLayoutData(gd); // Pattern combo fPattern= new Combo(result, SWT.SINGLE | SWT.BORDER); fPattern.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { handlePatternSelected(); } }); fPattern.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { getContainer().setPerformActionEnabled(getPattern().length() > 0); updateCaseSensitiveCheckbox(); } }); gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL); // limit preferred size gd.widthHint= convertWidthInCharsToPixels(50); gd.horizontalIndent= -gd.horizontalIndent; fPattern.setLayoutData(gd); // Ignore case checkbox fCaseSensitive= new Button(result, SWT.CHECK); fCaseSensitive.setText(SearchMessages.getString("SearchPage.expression.caseSensitive")); //$NON-NLS-1$ gd= new GridData(); fCaseSensitive.setLayoutData(gd); fCaseSensitive.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { fIsCaseSensitive= fCaseSensitive.getSelection(); writeConfiguration(); } }); return result; } private void updateCaseSensitiveCheckbox() { if (fInitialData != null && getPattern().equals(fInitialData.getPattern()) && fJavaElement != null) { fCaseSensitive.setEnabled(false); fCaseSensitive.setSelection(true); } else { fCaseSensitive.setEnabled(true); fCaseSensitive.setSelection(fIsCaseSensitive); } } private void handlePatternSelected() { if (fPattern.getSelectionIndex() < 0) return; int index= fgPreviousSearchPatterns.size() - 1 - fPattern.getSelectionIndex(); fInitialData= (SearchPatternData) fgPreviousSearchPatterns.get(index); for (int i= 0; i < fSearchFor.length; i++) fSearchFor[i].setSelection(false); for (int i= 0; i < fLimitTo.length; i++) fLimitTo[i].setSelection(false); fSearchFor[fInitialData.getSearchFor()].setSelection(true); setLimitTo(fInitialData.getSearchFor()); fLimitTo[fInitialData.getLimitTo()].setSelection(true); fPattern.setText(fInitialData.getPattern()); fIsCaseSensitive= fInitialData.isCaseSensitive(); fJavaElement= fInitialData.getJavaElement(); fCaseSensitive.setEnabled(fJavaElement == null); fCaseSensitive.setSelection(fInitialData.isCaseSensitive()); if (fInitialData.getWorkingSets() != null) getContainer().setSelectedWorkingSets(fInitialData.getWorkingSets()); else getContainer().setSelectedScope(fInitialData.getScope()); } private Control createSearchFor(Composite parent) { Group result= new Group(parent, SWT.NONE); result.setText(SearchMessages.getString("SearchPage.searchFor.label")); //$NON-NLS-1$ GridLayout layout= new GridLayout(); layout.numColumns= 3; result.setLayout(layout); fSearchFor= new Button[fSearchForText.length]; for (int i= 0; i < fSearchForText.length; i++) { Button button= new Button(result, SWT.RADIO); button.setText(fSearchForText[i]); fSearchFor[i]= button; } // Fill with dummy radio buttons Button filler= new Button(result, SWT.RADIO); filler.setVisible(false); filler= new Button(result, SWT.RADIO); filler.setVisible(false); return result; } private Control createLimitTo(Composite parent) { Group result= new Group(parent, SWT.NONE); result.setText(SearchMessages.getString("SearchPage.limitTo.label")); //$NON-NLS-1$ GridLayout layout= new GridLayout(); layout.numColumns= 2; result.setLayout(layout); SelectionAdapter listener= new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updateUseJRE(); } }; fLimitTo= new Button[fLimitToText.length]; for (int i= 0; i < fLimitToText.length; i++) { Button button= new Button(result, SWT.RADIO); button.setText(fLimitToText[i]); fLimitTo[i]= button; button.addSelectionListener(listener); } createSearchJRE(result); return result; } private void initSelections() { fStructuredSelection= asStructuredSelection(); fInitialData= tryStructuredSelection(fStructuredSelection); if (fInitialData == null) fInitialData= trySimpleTextSelection(getContainer().getSelection()); if (fInitialData == null) fInitialData= getDefaultInitValues(); fJavaElement= fInitialData.getJavaElement(); fCaseSensitive.setSelection(fInitialData.isCaseSensitive()); fCaseSensitive.setEnabled(fInitialData.getJavaElement() == null); fSearchFor[fInitialData.getSearchFor()].setSelection(true); setLimitTo(fInitialData.getSearchFor()); fLimitTo[fInitialData.getLimitTo()].setSelection(true); fPattern.setText(fInitialData.getPattern()); updateUseJRE(); } private void updateUseJRE() { boolean shouldEnable= mayExcludeJRE(); if (shouldEnable) { fSearchJRE.setSelection(getSearchJRE()); fSearchJRE.setEnabled(true); } else { fSearchJRE.setEnabled(false); fSearchJRE.setSelection(true); } } private boolean mayExcludeJRE() { return getLimitTo() == INDEX_REFERENCES || getLimitTo() == INDEX_ALL; } private SearchPatternData tryStructuredSelection(IStructuredSelection selection) { if (selection == null || selection.size() > 1) return null; Object o= selection.getFirstElement(); if (o instanceof IJavaElement) { return determineInitValuesFrom((IJavaElement)o); } else if (o instanceof ISearchResultViewEntry) { IJavaElement element= SearchUtil.getJavaElement(((ISearchResultViewEntry)o).getSelectedMarker()); return determineInitValuesFrom(element); } else if (o instanceof LogicalPackage) { LogicalPackage lp= (LogicalPackage)o; return new SearchPatternData(PACKAGE, REFERENCES, fIsCaseSensitive, lp.getElementName(), null); } else if (o instanceof IAdaptable) { IJavaElement element= (IJavaElement)((IAdaptable)o).getAdapter(IJavaElement.class); if (element != null) { return determineInitValuesFrom(element); } else { IWorkbenchAdapter adapter= (IWorkbenchAdapter)((IAdaptable)o).getAdapter(IWorkbenchAdapter.class); if (adapter != null) return new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive, adapter.getLabel(o), null); } } return null; } private SearchPatternData determineInitValuesFrom(IJavaElement element) { if (element == null) return null; int searchFor= UNKNOWN; int limitTo= UNKNOWN; String pattern= null; switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT: searchFor= PACKAGE; limitTo= REFERENCES; pattern= element.getElementName(); break; case IJavaElement.PACKAGE_FRAGMENT_ROOT: searchFor= PACKAGE; limitTo= REFERENCES; pattern= element.getElementName(); break; case IJavaElement.PACKAGE_DECLARATION: searchFor= PACKAGE; limitTo= REFERENCES; pattern= element.getElementName(); break; case IJavaElement.IMPORT_DECLARATION: pattern= element.getElementName(); IImportDeclaration declaration= (IImportDeclaration)element; if (declaration.isOnDemand()) { searchFor= PACKAGE; int index= pattern.lastIndexOf('.'); pattern= pattern.substring(0, index); } else { searchFor= TYPE; } limitTo= DECLARATIONS; break; case IJavaElement.TYPE: searchFor= TYPE; limitTo= REFERENCES; pattern= JavaModelUtil.getFullyQualifiedName((IType)element); break; case IJavaElement.COMPILATION_UNIT: ICompilationUnit cu= (ICompilationUnit)element; String mainTypeName= element.getElementName().substring(0, element.getElementName().indexOf(".")); //$NON-NLS-1$ IType mainType= cu.getType(mainTypeName); mainTypeName= JavaModelUtil.getTypeQualifiedName(mainType); try { mainType= JavaModelUtil.findTypeInCompilationUnit(cu, mainTypeName); if (mainType == null) { // fetch type which is declared first in the file IType[] types= cu.getTypes(); if (types.length > 0) mainType= types[0]; else break; } } catch (JavaModelException ex) { ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$ break; } searchFor= TYPE; element= mainType; limitTo= REFERENCES; pattern= JavaModelUtil.getFullyQualifiedName(mainType); break; case IJavaElement.CLASS_FILE: IClassFile cf= (IClassFile)element; try { mainType= cf.getType(); } catch (JavaModelException ex) { ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$ break; } if (mainType == null) break; element= mainType; searchFor= TYPE; limitTo= REFERENCES; pattern= JavaModelUtil.getFullyQualifiedName(mainType); break; case IJavaElement.FIELD: searchFor= FIELD; limitTo= REFERENCES; IType type= ((IField)element).getDeclaringType(); StringBuffer buffer= new StringBuffer(); buffer.append(JavaModelUtil.getFullyQualifiedName(type)); buffer.append('.'); buffer.append(element.getElementName()); pattern= buffer.toString(); break; case IJavaElement.METHOD: searchFor= METHOD; try { IMethod method= (IMethod)element; if (method.isConstructor()) searchFor= CONSTRUCTOR; } catch (JavaModelException ex) { ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$ break; } limitTo= REFERENCES; pattern= PrettySignature.getMethodSignature((IMethod)element); break; } if (searchFor != UNKNOWN && limitTo != UNKNOWN && pattern != null) return new SearchPatternData(searchFor, limitTo, true, pattern, element); return null; } private SearchPatternData trySimpleTextSelection(ISelection selection) { SearchPatternData result= null; if (selection instanceof ITextSelection) { BufferedReader reader= new BufferedReader(new StringReader(((ITextSelection)selection).getText())); String text; try { text= reader.readLine(); if (text == null) text= ""; //$NON-NLS-1$ } catch (IOException ex) { text= ""; //$NON-NLS-1$ } result= new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive, text, null); } return result; } private SearchPatternData getDefaultInitValues() { return new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive, "", null); //$NON-NLS-1$ } /* * Implements method from ISearchPage */ public void setContainer(ISearchPageContainer container) { fContainer= container; } /** * Returns the search page's container. */ private ISearchPageContainer getContainer() { return fContainer; } /** * Returns the structured selection from the selection. */ private IStructuredSelection asStructuredSelection() { IWorkbenchWindow wbWindow= PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (wbWindow != null) { IWorkbenchPage page= wbWindow.getActivePage(); if (page != null) { IWorkbenchPart part= page.getActivePart(); if (part != null) try { return SelectionConverter.getStructuredSelection(part); } catch (JavaModelException ex) { // ignore handled by return } } } return StructuredSelection.EMPTY; } //--------------- Configuration handling -------------- /** * Returns the page settings for this Java search page. * * @return the page settings to be used */ private IDialogSettings getDialogSettings() { IDialogSettings settings= JavaPlugin.getDefault().getDialogSettings(); fDialogSettings= settings.getSection(PAGE_NAME); if (fDialogSettings == null) fDialogSettings= settings.addNewSection(PAGE_NAME); return fDialogSettings; } /** * Initializes itself from the stored page settings. */ private void readConfiguration() { IDialogSettings s= getDialogSettings(); fIsCaseSensitive= s.getBoolean(STORE_CASE_SENSITIVE); } private void collectConcernedProjects(Set projects, ISelection selection) { if (!(selection instanceof IStructuredSelection)) return; IStructuredSelection structuredSelection= (IStructuredSelection)selection; Iterator elements= structuredSelection.iterator(); while (elements.hasNext()) { IProject project= getProject(elements.next()); if (project != null) projects.add(project); } } /** * Stores it current configuration in the dialog store. */ private void writeConfiguration() { IDialogSettings s= getDialogSettings(); s.put(STORE_CASE_SENSITIVE, fIsCaseSensitive); } private void collectConcernedProjects(Set projects, IWorkingSet[] workingSets) { for (int i= 0; i < workingSets.length; i++) collectConcernedProjects(projects, workingSets[i]); } private void collectConcernedProjects(Set projects, IWorkingSet workingSet) { IAdaptable[] adaptables= workingSet.getElements(); for (int i= 0; i < adaptables.length; i++) { IProject project= getProject(adaptables[i]); if (project != null) projects.add(project); } } private void collectConcernedProjects(Set projects, IWorkspace workspace) { IProject[] allProjects= workspace.getRoot().getProjects(); for (int i= 0; i < allProjects.length; i++) { if (allProjects[i].isAccessible()) projects.add(allProjects[i]); } } private IProject getProject(Object element) { if (element instanceof ISearchResultViewEntry) element= ((ISearchResultViewEntry)element).getGroupByKey(); if (element instanceof IAdaptable) { IAdaptable adaptable= (IAdaptable)element; IProject project= (IProject) adaptable.getAdapter(IProject.class); if (project != null) return project; IResource resource= (IResource) adaptable.getAdapter(IResource.class); if (resource != null) project= resource.getProject(); if (project != null) return project; } return null; } }
12,144
Bug 12144 Re-format all files [code manipulation]
I could be nice to have the ability to re-format all Java files in one time. Beyond, to do all java file based actions on a selection of files (as for search for example).
resolved fixed
8fbc6aa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T09:51:40Z
2002-03-22T18:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/IJavaHelpContextIds.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Sebastian Davids <sdavids@gmx.de> bug 38692 *******************************************************************************/ package org.eclipse.jdt.internal.ui; import org.eclipse.jdt.ui.JavaUI; /** * Help context ids for the Java UI. * <p> * This interface contains constants only; it is not intended to be implemented * or extended. * </p> * */ public interface IJavaHelpContextIds { public static final String PREFIX= JavaUI.ID_PLUGIN + '.'; // Actions public static final String GETTERSETTER_ACTION= PREFIX + "getter_setter_action_context"; //$NON-NLS-1$ public static final String ADD_METHODSTUB_ACTION= PREFIX + "add_methodstub_action_context"; //$NON-NLS-1$ public static final String ADD_UNIMPLEMENTED_METHODS_ACTION= PREFIX + "add_unimplemented_methods_action_context"; //$NON-NLS-1$ public static final String ADD_UNIMPLEMENTED_CONSTRUCTORS_ACTION= PREFIX + "add_unimplemented_constructors_action_context"; //$NON-NLS-1$ public static final String CREATE_NEW_CONSTRUCTOR_ACTION= PREFIX + "create_new_constructor_action_context"; //$NON-NLS-1$ public static final String SHOW_IN_PACKAGEVIEW_ACTION= PREFIX + "show_in_packageview_action_context"; //$NON-NLS-1$ public static final String SHOW_IN_HIERARCHYVIEW_ACTION= PREFIX + "show_in_hierarchyview_action_context"; //$NON-NLS-1$ public static final String FOCUS_ON_SELECTION_ACTION= PREFIX + "focus_on_selection_action"; //$NON-NLS-1$ public static final String FOCUS_ON_TYPE_ACTION= PREFIX + "focus_on_type_action"; //$NON-NLS-1$ public static final String TYPEHIERARCHY_HISTORY_ACTION= PREFIX + "typehierarchy_history_action"; //$NON-NLS-1$ public static final String FILTER_PUBLIC_ACTION= PREFIX + "filter_public_action"; //$NON-NLS-1$ public static final String FILTER_FIELDS_ACTION= PREFIX + "filter_fields_action"; //$NON-NLS-1$ public static final String FILTER_STATIC_ACTION= PREFIX + "filter_static_action"; //$NON-NLS-1$ public static final String FILTER_LOCALTYPES_ACTION= PREFIX + "filter_localtypes_action"; //$NON-NLS-1$ public static final String SHOW_INHERITED_ACTION= PREFIX + "show_inherited_action"; //$NON-NLS-1$ public static final String SHOW_SUPERTYPES= PREFIX + "show_supertypes_action"; //$NON-NLS-1$ public static final String SHOW_SUBTYPES= PREFIX + "show_subtypes_action"; //$NON-NLS-1$ public static final String SHOW_HIERARCHY= PREFIX + "show_hierarchy_action"; //$NON-NLS-1$ public static final String ENABLE_METHODFILTER_ACTION= PREFIX + "enable_methodfilter_action"; //$NON-NLS-1$ public static final String ADD_IMPORT_ON_SELECTION_ACTION= PREFIX + "add_imports_on_selection_action_context"; //$NON-NLS-1$ public static final String ORGANIZE_IMPORTS_ACTION= PREFIX + "organize_imports_action_context"; //$NON-NLS-1$ public static final String ADD_TO_CLASSPATH_ACTION= PREFIX + "addjtoclasspath_action_context"; //$NON-NLS-1$ public static final String REMOVE_FROM_CLASSPATH_ACTION= PREFIX + "removefromclasspath_action_context"; //$NON-NLS-1$ public static final String TOGGLE_PRESENTATION_ACTION= PREFIX + "toggle_presentation_action_context"; //$NON-NLS-1$ public static final String TOGGLE_MARK_OCCURRENCES_ACTION= PREFIX + "toggle_mark_occurrences_action_context"; //$NON-NLS-1$ public static final String TOGGLE_TEXTHOVER_ACTION= PREFIX + "toggle_texthover_action_context"; //$NON-NLS-1$ public static final String OPEN_CLASS_WIZARD_ACTION= PREFIX + "open_class_wizard_action"; //$NON-NLS-1$ public static final String OPEN_INTERFACE_WIZARD_ACTION= PREFIX + "open_interface_wizard_action"; //$NON-NLS-1$ public static final String SORT_MEMBERS_ACTION= PREFIX + "sort_members_action"; //$NON-NLS-1$ public static final String OPEN_PACKAGE_WIZARD_ACTION= PREFIX + "open_package_wizard_action"; //$NON-NLS-1$ public static final String OPEN_PROJECT_WIZARD_ACTION= PREFIX + "open_project_wizard_action"; //$NON-NLS-1$ public static final String EDIT_WORKING_SET_ACTION= PREFIX + "edit_working_set_action"; //$NON-NLS-1$ public static final String CLEAR_WORKING_SET_ACTION= PREFIX + "clear_working_set_action"; //$NON-NLS-1$ public static final String GOTO_MARKER_ACTION= PREFIX + "goto_marker_action"; //$NON-NLS-1$ public static final String GOTO_PACKAGE_ACTION= PREFIX + "goto_package_action"; //$NON-NLS-1$ public static final String GOTO_TYPE_ACTION= PREFIX + "goto_type_action"; //$NON-NLS-1$ public static final String GOTO_MATCHING_BRACKET_ACTION= PREFIX + "goto_matching_bracket_action"; //$NON-NLS-1$ public static final String GOTO_NEXT_MEMBER_ACTION= PREFIX + "goto_next_member_action"; //$NON-NLS-1$ public static final String GOTO_PREVIOUS_MEMBER_ACTION= PREFIX + "goto_previous_member_action"; //$NON-NLS-1$ public static final String HISTORY_ACTION= PREFIX + "history_action"; //$NON-NLS-1$ public static final String HISTORY_LIST_ACTION= PREFIX + "history_list_action"; //$NON-NLS-1$ public static final String LEXICAL_SORTING_OUTLINE_ACTION= PREFIX + "lexical_sorting_outline_action"; //$NON-NLS-1$ public static final String LEXICAL_SORTING_BROWSING_ACTION= PREFIX + "lexical_sorting_browsing_action"; //$NON-NLS-1$ public static final String OPEN_JAVA_PERSPECTIVE_ACTION= PREFIX + "open_java_perspective_action"; //$NON-NLS-1$ public static final String ADD_DELEGATE_METHODS_ACTION= PREFIX + "add_delegate_methods_action"; //$NON-NLS-1$ public static final String OPEN_JAVA_BROWSING_PERSPECTIVE_ACTION= PREFIX + "open_java_browsing_perspective_action"; //$NON-NLS-1$ public static final String OPEN_PROJECT_ACTION= PREFIX + "open_project_action"; //$NON-NLS-1$ public static final String OPEN_TYPE_ACTION= PREFIX + "open_type_action"; //$NON-NLS-1$ public static final String OPEN_TYPE_IN_HIERARCHY_ACTION= PREFIX + "open_type_in_hierarchy_action"; //$NON-NLS-1$ /** * @since 3.0 */ public static final String CONFIG_CONTAINER_ACTION= PREFIX + "org.eclipse.jdt.ui.config_container_action"; //$NON-NLS-1$ public static final String ADD_JAVADOC_STUB_ACTION= PREFIX + "add_javadoc_stub_action"; //$NON-NLS-1$ public static final String ADD_TASK_ACTION= PREFIX + "add_task_action"; //$NON-NLS-1$ public static final String EXTERNALIZE_STRINGS_ACTION= PREFIX + "externalize_strings_action"; //$NON-NLS-1$ public static final String EXTRACT_METHOD_ACTION= PREFIX + "extract_method_action"; //$NON-NLS-1$ public static final String EXTRACT_TEMP_ACTION= PREFIX + "extract_temp_action"; //$NON-NLS-1$ public static final String PROMOTE_TEMP_TO_FIELD_ACTION= PREFIX + "promote_temp_to_field_action"; //$NON-NLS-1$ public static final String CONVERT_ANONYMOUS_TO_NESTED_ACTION= PREFIX + "convert_anonymous_to_nested_action"; //$NON-NLS-1$ public static final String EXTRACT_CONSTANT_ACTION= PREFIX + "extract_constant_action"; //$NON-NLS-1$ public static final String INTRODUCE_PARAMETER_ACTION= PREFIX + "introduce_parameter_action"; //$NON-NLS-1$ public static final String INTRODUCE_FACTORY_ACTION= PREFIX + "introduce_factory_action"; //$NON-NLS-1$ public static final String EXTRACT_INTERFACE_ACTION= PREFIX + "extract_interface_action"; //$NON-NLS-1$ public static final String CHANGE_TYPE_ACTION= PREFIX + "change_type_action"; //$NON-NLS-1$ public static final String MOVE_INNER_TO_TOP_ACTION= PREFIX + "move_inner_to_top_level_action"; //$NON-NLS-1$ public static final String USE_SUPERTYPE_ACTION= PREFIX + "use_supertype_action"; //$NON-NLS-1$ public static final String FIND_DECLARATIONS_IN_WORKSPACE_ACTION= PREFIX + "find_declarations_in_workspace_action"; //$NON-NLS-1$ public static final String FIND_DECLARATIONS_IN_PROJECT_ACTION= PREFIX + "find_declarations_in_project_action"; //$NON-NLS-1$ public static final String FIND_DECLARATIONS_IN_HIERARCHY_ACTION= PREFIX + "find_declarations_in_hierarchy_action"; //$NON-NLS-1$ public static final String FIND_DECLARATIONS_IN_WORKING_SET_ACTION= PREFIX + "find_declarations_in_working_set_action"; //$NON-NLS-1$ public static final String FIND_IMPLEMENTORS_IN_WORKSPACE_ACTION= PREFIX + "find_implementors_in_workspace_action"; //$NON-NLS-1$ public static final String FIND_IMPLEMENTORS_IN_PROJECT_ACTION= PREFIX + "find_implementors_in_project_action"; //$NON-NLS-1$ public static final String FIND_IMPLEMENTORS_IN_WORKING_SET_ACTION= PREFIX + "find_implementors_in_working_set_action"; //$NON-NLS-1$ public static final String FIND_REFERENCES_IN_WORKSPACE_ACTION= PREFIX + "find_references_in_workspace_action"; //$NON-NLS-1$ public static final String FIND_REFERENCES_IN_PROJECT_ACTION= PREFIX + "find_references_in_project_action"; //$NON-NLS-1$ public static final String FIND_REFERENCES_IN_HIERARCHY_ACTION= PREFIX + "find_references_in_hierarchy_action"; //$NON-NLS-1$ public static final String FIND_REFERENCES_IN_WORKING_SET_ACTION= PREFIX + "find_references_in_working_set_action"; //$NON-NLS-1$ public static final String FIND_READ_REFERENCES_IN_WORKSPACE_ACTION= PREFIX + "find_read_references_in_workspace_action"; //$NON-NLS-1$ public static final String FIND_READ_REFERENCES_IN_PROJECT_ACTION= PREFIX + "find_read_references_in_project_action"; //$NON-NLS-1$ public static final String FIND_READ_REFERENCES_IN_HIERARCHY_ACTION= PREFIX + "find_read_references_in_hierarchy_action"; //$NON-NLS-1$ public static final String FIND_READ_REFERENCES_IN_WORKING_SET_ACTION= PREFIX + "find_read_references_in_working_set_action"; //$NON-NLS-1$ public static final String FIND_WRITE_REFERENCES_IN_HIERARCHY_ACTION= PREFIX + "find_write_references_in_hierarchy_action"; //$NON-NLS-1$ public static final String FIND_WRITE_REFERENCES_IN_PROJECT_ACTION= PREFIX + "find_write_references_in_project_action"; //$NON-NLS-1$ public static final String FIND_WRITE_REFERENCES_IN_WORKING_SET_ACTION= PREFIX + "find_write_references_in_working_set_action"; //$NON-NLS-1$ public static final String FIND_WRITE_REFERENCES_IN_WORKSPACE_ACTION= PREFIX + "find_write_references_in_workspace_action"; //$NON-NLS-1$ public static final String FIND_OCCURRENCES_IN_FILE_ACTION= PREFIX + "find_occurrences_in_file_action"; //$NON-NLS-1$ public static final String FIND_EXCEPTION_OCCURRENCES= PREFIX + "find_exception_occurrences"; //$NON-NLS-1$ public static final String WORKING_SET_FIND_ACTION= PREFIX + "working_set_find_action"; //$NON-NLS-1$ public static final String FIND_STRINGS_TO_EXTERNALIZE_ACTION= PREFIX + "find_strings_to_externalize_action"; //$NON-NLS-1$ public static final String INLINE_ACTION= PREFIX + "inline_action"; //$NON-NLS-1$ public static final String MODIFY_PARAMETERS_ACTION= PREFIX + "modify_parameters_action"; //$NON-NLS-1$ public static final String MOVE_ACTION= PREFIX + "move_action"; //$NON-NLS-1$ public static final String OPEN_ACTION= PREFIX + "open_action"; //$NON-NLS-1$ public static final String OPEN_EXTERNAL_JAVADOC_ACTION= PREFIX + "open_external_javadoc_action"; //$NON-NLS-1$ public static final String OPEN_INPUT_ACTION= PREFIX + "open_input_action"; //$NON-NLS-1$ public static final String OPEN_SUPER_IMPLEMENTATION_ACTION= PREFIX + "open_super_implementation_action"; //$NON-NLS-1$ public static final String PULL_UP_ACTION= PREFIX + "pull_up_action"; //$NON-NLS-1$ public static final String PUSH_DOWN_ACTION= PREFIX + "push_down_action"; //$NON-NLS-1$ public static final String REFRESH_ACTION= PREFIX + "refresh_action"; //$NON-NLS-1$ public static final String RENAME_ACTION= PREFIX + "rename_action"; //$NON-NLS-1$ public static final String SELF_ENCAPSULATE_ACTION= PREFIX + "self_encapsulate_action"; //$NON-NLS-1$ public static final String SHOW_IN_NAVIGATOR_VIEW_ACTION= PREFIX + "show_in_navigator_action"; //$NON-NLS-1$ public static final String SURROUND_WITH_TRY_CATCH_ACTION= PREFIX + "surround_with_try_catch_action"; //$NON-NLS-1$ public static final String OPEN_RESOURCE_ACTION= PREFIX + "open_resource_action"; //$NON-NLS-1$ public static final String SELECT_WORKING_SET_ACTION= PREFIX + "select_working_set_action"; //$NON-NLS-1$ public static final String STRUCTURED_SELECTION_HISTORY_ACTION= PREFIX + "structured_selection_history_action"; //$NON-NLS-1$ public static final String STRUCTURED_SELECT_ENCLOSING_ACTION= PREFIX + "structured_select_enclosing_action"; //$NON-NLS-1$ public static final String STRUCTURED_SELECT_NEXT_ACTION= PREFIX + "structured_select_next_action"; //$NON-NLS-1$ public static final String STRUCTURED_SELECT_PREVIOUS_ACTION= PREFIX + "structured_select_previous_action"; //$NON-NLS-1$ public static final String TOGGLE_ORIENTATION_ACTION= PREFIX + "toggle_orientations_action"; //$NON-NLS-1$ public static final String CUT_ACTION= PREFIX + "cut_action"; //$NON-NLS-1$ public static final String COPY_ACTION= PREFIX + "copy_action"; //$NON-NLS-1$ public static final String PASTE_ACTION= PREFIX + "paste_action"; //$NON-NLS-1$ public static final String DELETE_ACTION= PREFIX + "delete_action"; //$NON-NLS-1$ public static final String SELECT_ALL_ACTION= PREFIX + "select_all_action"; //$NON-NLS-1$ public static final String OPEN_TYPE_HIERARCHY_ACTION= PREFIX + "open_type_hierarchy_action"; //$NON-NLS-1$ public static final String COLLAPSE_ALL_ACTION= PREFIX + "open_type_hierarchy_action"; //$NON-NLS-1$ public static final String GOTO_RESOURCE_ACTION= PREFIX + "goto_resource_action"; //$NON-NLS-1$ public static final String LINK_EDITOR_ACTION= PREFIX + "link_editor_action"; //$NON-NLS-1$ public static final String GO_INTO_TOP_LEVEL_TYPE_ACTION= PREFIX + "go_into_top_level_type_action"; //$NON-NLS-1$ public static final String COMPARE_WITH_HISTORY_ACTION= PREFIX + "compare_with_history_action"; //$NON-NLS-1$ public static final String REPLACE_WITH_PREVIOUS_FROM_HISTORY_ACTION= PREFIX + "replace_with_previous_from_history_action"; //$NON-NLS-1$ public static final String REPLACE_WITH_HISTORY_ACTION= PREFIX + "replace_with_history_action"; //$NON-NLS-1$ public static final String ADD_FROM_HISTORY_ACTION= PREFIX + "add_from_history_action"; //$NON-NLS-1$ public static final String LAYOUT_FLAT_ACTION= PREFIX + "layout_flat_action"; //$NON-NLS-1$ public static final String LAYOUT_HIERARCHICAL_ACTION= PREFIX + "layout_hierarchical_action"; //$NON-NLS-1$ // *** Don't delete this constants and the doc since it is still used in refactoring public static final String NEXT_CHANGE_ACTION= PREFIX + "next_change_action"; //$NON-NLS-1$ public static final String PREVIOUS_CHANGE_ACTION= PREFIX + "previous_change_action"; //$NON-NLS-1$ public static final String NEXT_PROBLEM_ACTION= PREFIX + "next_problem_action"; //$NON-NLS-1$ public static final String PREVIOUS_PROBLEM_ACTION= PREFIX + "previous_problem_action"; //$NON-NLS-1$ // *** end public static final String JAVA_SELECT_MARKER_RULER_ACTION= PREFIX + "java_select_marker_ruler_action"; //$NON-NLS-1$ public static final String GOTO_NEXT_ERROR_ACTION= PREFIX + "goto_next_error_action"; //$NON-NLS-1$ public static final String GOTO_PREVIOUS_ERROR_ACTION= PREFIX + "goto_previous_error_action"; //$NON-NLS-1$ public static final String SHOW_QUALIFIED_NAMES_ACTION= PREFIX + "show_qualified_names_action"; //$NON-NLS-1$ public static final String SORT_BY_DEFINING_TYPE_ACTION= PREFIX + "sort_by_defining_type_action"; //$NON-NLS-1$ public static final String FORMAT_ACTION= PREFIX + "format_action"; //$NON-NLS-1$ public static final String COMMENT_ACTION= PREFIX + "comment_action"; //$NON-NLS-1$ public static final String UNCOMMENT_ACTION= PREFIX + "uncomment_action"; //$NON-NLS-1$ /** * @since 3.0 */ public static final String TOGGLE_COMMENT_ACTION= PREFIX + "toggle_comment_action"; //$NON-NLS-1$ public static final String ADD_BLOCK_COMMENT_ACTION= PREFIX + "add_block_comment_action"; //$NON-NLS-1$ public static final String REMOVE_BLOCK_COMMENT_ACTION= PREFIX + "remove_block_comment_action"; //$NON-NLS-1$ public static final String QUICK_FIX_ACTION= PREFIX + "quick_fix_action"; //$NON-NLS-1$ public static final String CONTENT_ASSIST_ACTION= PREFIX + "content_assist_action"; //$NON-NLS-1$ public static final String PARAMETER_HINTS_ACTION= PREFIX + "parameter_hints_action"; //$NON-NLS-1$ public static final String SHOW_JAVADOC_ACTION= PREFIX + "show_javadoc_action"; //$NON-NLS-1$ public static final String SHOW_OUTLINE_ACTION= PREFIX + "show_outline_action"; //$NON-NLS-1$ public static final String OPEN_STRUCTURE_ACTION= PREFIX + "open_structure_action"; //$NON-NLS-1$ public static final String OPEN_HIERARCHY_ACTION= PREFIX + "open_hierarchy_action"; //$NON-NLS-1$ public static final String TOGGLE_SMART_TYPING_ACTION= PREFIX + "toggle_smart_typing_action"; //$NON-NLS-1$ public static final String INDENT_ACTION= PREFIX + "indent_action"; //$NON-NLS-1$ // Dialogs public static final String MAINTYPE_SELECTION_DIALOG= PREFIX + "maintype_selection_dialog_context"; //$NON-NLS-1$ public static final String OPEN_TYPE_DIALOG= PREFIX + "open_type_dialog_context"; //$NON-NLS-1$ public static final String OPEN_PACKAGE_DIALOG= PREFIX + "open_package_dialog_context"; //$NON-NLS-1$ public static final String SOURCE_ATTACHMENT_DIALOG= PREFIX + "source_attachment_dialog_context"; //$NON-NLS-1$ public static final String LIBRARIES_WORKBOOK_PAGE_ADVANCED_DIALOG= PREFIX + "advanced_dialog_context"; //$NON-NLS-1$ public static final String CONFIRM_SAVE_MODIFIED_RESOURCES_DIALOG= PREFIX + "confirm_save_modified_resources_dialog_context"; //$NON-NLS-1$ public static final String NEW_VARIABLE_ENTRY_DIALOG= PREFIX + "new_variable_dialog_context"; //$NON-NLS-1$ public static final String NONNLS_DIALOG= PREFIX + "nonnls_dialog_context"; //$NON-NLS-1$ public static final String MULTI_MAIN_TYPE_SELECTION_DIALOG= PREFIX + "multi_main_type_selection_dialog_context"; //$NON-NLS-1$ public static final String MULTI_TYPE_SELECTION_DIALOG= PREFIX + "multi_type_selection_dialog_context"; //$NON-NLS-1$ public static final String SUPER_INTERFACE_SELECTION_DIALOG= PREFIX + "super_interface_selection_dialog_context"; //$NON-NLS-1$ public static final String OVERRIDE_TREE_SELECTION_DIALOG= PREFIX + "override_tree_selection_dialog_context"; //$NON-NLS-1$ public static final String MOVE_DESTINATION_DIALOG= PREFIX + "move_destination_dialog_context"; //$NON-NLS-1$ public static final String CHOOSE_VARIABLE_DIALOG= PREFIX + "choose_variable_dialog_context"; //$NON-NLS-1$ public static final String EDIT_TEMPLATE_DIALOG= PREFIX + "edit_template_dialog_context"; //$NON-NLS-1$ public static final String HISTORY_LIST_DIALOG= PREFIX + "history_list_dialog_context"; //$NON-NLS-1$ public static final String IMPORT_ORGANIZE_INPUT_DIALOG= PREFIX + "import_organize_input_dialog_context"; //$NON-NLS-1$ public static final String TODO_TASK_INPUT_DIALOG= PREFIX + "todo_task_input_dialog_context"; //$NON-NLS-1$ public static final String JAVADOC_PROPERTY_DIALOG= PREFIX + "javadoc_property_dialog_context"; //$NON-NLS-1$ public static final String NEW_CONTAINER_DIALOG= PREFIX + "new_container_dialog_context"; //$NON-NLS-1$ public static final String EXCLUSION_PATTERN_DIALOG= PREFIX + "exclusion_pattern_dialog_context"; //$NON-NLS-1$ public static final String OUTPUT_LOCATION_DIALOG= PREFIX + "output_location_dialog_context"; //$NON-NLS-1$ public static final String VARIABLE_CREATION_DIALOG= PREFIX + "variable_creation_dialog_context"; //$NON-NLS-1$ public static final String JAVA_SEARCH_PAGE= PREFIX + "java_search_page_context"; //$NON-NLS-1$ public static final String NLS_SEARCH_PAGE= PREFIX + "nls_search_page_context"; //$NON-NLS-1$ public static final String JAVA_EDITOR= PREFIX + "java_editor_context"; //$NON-NLS-1$ public static final String GOTO_RESOURCE_DIALOG= PREFIX + "goto_resource_dialog"; //$NON-NLS-1$ public static final String COMPARE_DIALOG= PREFIX + "compare_dialog_context"; //$NON-NLS-1$ public static final String ADD_ELEMENT_FROM_HISTORY_DIALOG= PREFIX + "add_element_from_history_dialog_context"; //$NON-NLS-1$ public static final String COMPARE_ELEMENT_WITH_HISTORY_DIALOG= PREFIX + "compare_element_with_history_dialog_context"; //$NON-NLS-1$ public static final String REPLACE_ELEMENT_WITH_HISTORY_DIALOG= PREFIX + "replace_element_with_history_dialog_context"; //$NON-NLS-1$ // view parts public static final String TYPE_HIERARCHY_VIEW= PREFIX + "type_hierarchy_view_context"; //$NON-NLS-1$ public static final String PACKAGES_VIEW= PREFIX + "package_view_context"; //$NON-NLS-1$ public static final String PROJECTS_VIEW= PREFIX + "projects_view_context"; //$NON-NLS-1$ public static final String PACKAGES_BROWSING_VIEW= PREFIX + "packages_browsing_view_context"; //$NON-NLS-1$ public static final String TYPES_VIEW= PREFIX + "types_view_context"; //$NON-NLS-1$ public static final String MEMBERS_VIEW= PREFIX + "members_view_context"; //$NON-NLS-1$ // Preference/Property pages public static final String APPEARANCE_PREFERENCE_PAGE= PREFIX + "appearance_preference_page_context"; //$NON-NLS-1$ public static final String SORT_ORDER_PREFERENCE_PAGE= PREFIX + "sort_order_preference_page_context"; //$NON-NLS-1$ public static final String BUILD_PATH_PROPERTY_PAGE= PREFIX + "build_path_property_page_context"; //$NON-NLS-1$ public static final String CP_VARIABLES_PREFERENCE_PAGE= PREFIX + "cp_variables_preference_page_context"; //$NON-NLS-1$ /** * @since 3.0 */ public static final String CP_USERLIBRARIES_PREFERENCE_PAGE= PREFIX + "cp_userlibraries_preference_page_context"; //$NON-NLS-1$ public static final String CODEFORMATTER_PREFERENCE_PAGE= PREFIX + "codeformatter_preference_page_context"; //$NON-NLS-1$ public static final String SOURCE_ATTACHMENT_PROPERTY_PAGE= PREFIX + "source_attachment_property_page_context"; //$NON-NLS-1$ public static final String COMPILER_PROPERTY_PAGE= PREFIX + "compiler_property_page_context"; //$NON-NLS-1$ public static final String TODOTASK_PROPERTY_PAGE= PREFIX + "tasktags_property_page_context"; //$NON-NLS-1$ /** * @since 3.0 */ public static final String CODE_TEMPLATES_PREFERENCE_PAGE= PREFIX + "code_templates_preference_context"; //$NON-NLS-1$ public static final String CODE_MANIPULATION_PREFERENCE_PAGE= PREFIX + "code_manipulation_preference_context"; //$NON-NLS-1$ public static final String ORGANIZE_IMPORTS_PREFERENCE_PAGE= PREFIX + "organizeimports_preference_page_context"; //$NON-NLS-1$ public static final String JAVA_BASE_PREFERENCE_PAGE= PREFIX + "java_base_preference_page_context"; //$NON-NLS-1$ public static final String REFACTORING_PREFERENCE_PAGE= PREFIX + "refactoring_preference_page_context"; //$NON-NLS-1$ public static final String JAVA_EDITOR_PREFERENCE_PAGE= PREFIX + "java_editor_preference_page_context"; //$NON-NLS-1$ public static final String COMPILER_PREFERENCE_PAGE= PREFIX + "compiler_preference_page_context"; //$NON-NLS-1$ public static final String TODOTASK_PREFERENCE_PAGE= PREFIX + "tasktags_preference_page_context"; //$NON-NLS-1$ public static final String TEMPLATE_PREFERENCE_PAGE= PREFIX + "template_preference_page_context"; //$NON-NLS-1$ public static final String NEW_JAVA_PROJECT_PREFERENCE_PAGE= PREFIX + "new_java_project_preference_page_context"; //$NON-NLS-1$ public static final String JAVADOC_CONFIGURATION_PROPERTY_PAGE= PREFIX + "new_java_project_preference_page_context"; //$NON-NLS-1$ public static final String JAVA_ELEMENT_INFO_PAGE= PREFIX + "java_element_info_page_context"; //$NON-NLS-1$ // Wizard pages public static final String NEW_JAVAPROJECT_WIZARD_PAGE= PREFIX + "new_javaproject_wizard_page_context"; //$NON-NLS-1$ public static final String NEW_PACKAGE_WIZARD_PAGE= PREFIX + "new_package_wizard_page_context"; //$NON-NLS-1$ public static final String NEW_CLASS_WIZARD_PAGE= PREFIX + "new_class_wizard_page_context"; //$NON-NLS-1$ public static final String NEW_INTERFACE_WIZARD_PAGE= PREFIX + "new_interface_wizard_page_context"; //$NON-NLS-1$ public static final String NEW_PACKAGEROOT_WIZARD_PAGE= PREFIX + "new_packageroot_wizard_page_context"; //$NON-NLS-1$ public static final String JARPACKAGER_WIZARD_PAGE= PREFIX + "jar_packager_wizard_page_context"; //$NON-NLS-1$ public static final String JARMANIFEST_WIZARD_PAGE= PREFIX + "jar_manifest_wizard_page_context"; //$NON-NLS-1$ public static final String JAROPTIONS_WIZARD_PAGE= PREFIX + "jar_options_wizard_page_context"; //$NON-NLS-1$ public static final String JAVA_WORKING_SET_PAGE= PREFIX + "java_working_set_page_context"; //$NON-NLS-1$ public static final String CLASSPATH_CONTAINER_DEFAULT_PAGE= PREFIX + "classpath_container_default_page_context"; //$NON-NLS-1$ public static final String JAVADOC_STANDARD_PAGE= PREFIX + "javadoc_standard_page_context"; //$NON-NLS-1$ public static final String JAVADOC_SPECIFICS_PAGE= PREFIX + "javadoc_specifics_page_context"; //$NON-NLS-1$ public static final String JAVADOC_TREE_PAGE= PREFIX + "javadoc_tree_page_context"; //$NON-NLS-1$ public static final String JAVADOC_COMMAND_PAGE= PREFIX + "javadoc_command_page_context"; //$NON-NLS-1$ // Same help for all refactoring error pages. Indidivual help can // be provided per a single refactoring status. // *** Don't delete this constants and the doc since it is still used in refactoring public static final String REFACTORING_ERROR_WIZARD_PAGE= PREFIX + "refactoring_error_wizard_page_context"; //$NON-NLS-1$ // same help for all refactoring preview pages // *** Don't delete this constants and the doc since it is still used in refactoring public static final String REFACTORING_PREVIEW_WIZARD_PAGE= PREFIX + "refactoring_preview_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_PARAMS_WIZARD_PAGE= PREFIX + "rename_params_wizard_page"; //$NON-NLS-1$ public static final String EXTERNALIZE_WIZARD_KEYVALUE_PAGE= PREFIX + "externalize_wizard_keyvalue_page_context"; //$NON-NLS-1$ public static final String EXTERNALIZE_WIZARD_PROPERTIES_FILE_PAGE= PREFIX + "externalize_wizard_properties_file_page_context"; //$NON-NLS-1$ public static final String EXTRACT_INTERFACE_WIZARD_PAGE= PREFIX + "extract_interface_temp_page_context"; //$NON-NLS-1$ public static final String EXTRACT_METHOD_WIZARD_PAGE= PREFIX + "extract_method_wizard_page_context"; //$NON-NLS-1$ public static final String EXTRACT_TEMP_WIZARD_PAGE= PREFIX + "extract_temp_page_context"; //$NON-NLS-1$ public static final String EXTRACT_CONSTANT_WIZARD_PAGE= PREFIX + "extract_constant_page_context"; //$NON-NLS-1$ public static final String INTRODUCE_PARAMETER_WIZARD_PAGE= PREFIX + "introduce_parameter_page_context"; //$NON-NLS-1$ public static final String INTRODUCE_FACTORY_WIZARD_PAGE= PREFIX + "introduce_factory_wizard_page_context"; //$NON-NLS-1$ public static final String PROMOTE_TEMP_TO_FIELD_WIZARD_PAGE= PREFIX + "promote_temp_to_field_page_context"; //$NON-NLS-1$ public static final String CONVERT_ANONYMOUS_TO_NESTED_WIZARD_PAGE= PREFIX + "convert_anonymous_to_nested_page_context"; //$NON-NLS-1$ public static final String MODIFY_PARAMETERS_WIZARD_PAGE= PREFIX + "modify_parameters_wizard_page_context"; //$NON-NLS-1$ public static final String MOVE_MEMBERS_WIZARD_PAGE= PREFIX + "move_members_wizard_page_context"; //$NON-NLS-1$ public static final String MOVE_INNER_TO_TOP_WIZARD_PAGE= PREFIX + "move_inner_to_top_wizard_page_context"; //$NON-NLS-1$ public static final String PULL_UP_WIZARD_PAGE= PREFIX + "pull_up_wizard_page_context"; //$NON-NLS-1$ public static final String PUSH_DOWN_WIZARD_PAGE= PREFIX + "push_down_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_PACKAGE_WIZARD_PAGE= PREFIX + "rename_package_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_TEMP_WIZARD_PAGE= PREFIX + "rename_local_variable_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_CU_WIZARD_PAGE= PREFIX + "rename_cu_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_METHOD_WIZARD_PAGE= PREFIX + "rename_method_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_TYPE_WIZARD_PAGE= PREFIX + "rename_type_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_FIELD_WIZARD_PAGE= PREFIX + "rename_field_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_RESOURCE_WIZARD_PAGE= PREFIX + "rename_resource_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_JAVA_PROJECT_WIZARD_PAGE= PREFIX + "rename_java_project_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_SOURCE_FOLDER_WIZARD_PAGE= PREFIX + "rename_source_folder_wizard_page_context"; //$NON-NLS-1$ public static final String SEF_WIZARD_PAGE= PREFIX + "self_encapsulate_field_wizard_page_context"; //$NON-NLS-1$ public static final String USE_SUPERTYPE_WIZARD_PAGE= PREFIX + "use_supertype_wizard_page_context"; //$NON-NLS-1$ public static final String INLINE_METHOD_WIZARD_PAGE= PREFIX + "inline_method_wizard_page_context"; //$NON-NLS-1$ public static final String INLINE_CONSTANT_WIZARD_PAGE= PREFIX + "inline_constant_wizard_page_context"; //$NON-NLS-1$ // reused ui-blocks public static final String BUILD_PATH_BLOCK= PREFIX + "build_paths_context"; //$NON-NLS-1$ public static final String SOURCE_ATTACHMENT_BLOCK= PREFIX + "source_attachment_context"; //$NON-NLS-1$ // Custom Filters public static final String CUSTOM_FILTERS_DIALOG= PREFIX + "open_custom_filters_dialog_context"; //$NON-NLS-1$ // Call Hierarchy public static final String CALL_HIERARCHY_VIEW= PREFIX + "call_hierarchy_view_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_FILTERS_DIALOG= PREFIX + "call_hierarchy_filters_dialog_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_FOCUS_ON_SELECTION_ACTION= PREFIX + "call_hierarchy_focus_on_selection_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_HISTORY_ACTION= PREFIX + "call_hierarchy_history_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_HISTORY_DROP_DOWN_ACTION= PREFIX + "call_hierarchy_history_drop_down_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_REFRESH_ACTION= PREFIX + "call_hierarchy_refresh_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_SEARCH_SCOPE_ACTION= PREFIX + "call_hierarchy_search_scope_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_TOGGLE_CALL_MODE_ACTION= PREFIX + "call_hierarchy_toggle_call_mode_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_TOGGLE_JAVA_LABEL_FORMAT_ACTION= PREFIX + "call_hierarchy_toggle_java_label_format_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_TOGGLE_ORIENTATION_ACTION= PREFIX + "call_hierarchy_toggle_call_mode_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_COPY_ACTION= PREFIX + "call_hierarchy_copy_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_TOGGLE_IMPLEMENTORS_ACTION= PREFIX + "call_hierarchy_toggle_implementors_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_OPEN_ACTION= PREFIX + "call_hierarchy_open_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_CANCEL_SEARCH_ACTION= PREFIX + "call_hierarchy_cancel_search_action_context"; //$NON-NLS-1$ }
12,144
Bug 12144 Re-format all files [code manipulation]
I could be nice to have the ability to re-format all Java files in one time. Beyond, to do all java file based actions on a selection of files (as for search for example).
resolved fixed
8fbc6aa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T09:51:40Z
2002-03-22T18:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/FormatAllAction.java
12,144
Bug 12144 Re-format all files [code manipulation]
I could be nice to have the ability to re-format all Java files in one time. Beyond, to do all java file based actions on a selection of files (as for search for example).
resolved fixed
8fbc6aa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T09:51:40Z
2002-03-22T18:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/GenerateActionGroup.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui.actions; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IKeyBindingService; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.AddBookmarkAction; import org.eclipse.ui.ide.IDEActionFactory; import org.eclipse.ui.part.Page; import org.eclipse.ui.texteditor.ConvertLineDelimitersAction; import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds; import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; import org.eclipse.ui.texteditor.IUpdate; import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds; import org.eclipse.jdt.internal.ui.actions.ActionMessages; import org.eclipse.jdt.internal.ui.actions.AddTaskAction; import org.eclipse.jdt.internal.ui.actions.JDTQuickMenuAction; import org.eclipse.jdt.internal.ui.javaeditor.AddImportOnSelectionAction; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.ui.IContextMenuConstants; /** * Action group that adds the source and generate actions to a part's context * menu and installs handlers for the corresponding global menu actions. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class GenerateActionGroup extends ActionGroup { private CompilationUnitEditor fEditor; private IWorkbenchSite fSite; private String fGroupName= IContextMenuConstants.GROUP_REORGANIZE; private List fRegisteredSelectionListeners; private AddImportOnSelectionAction fAddImport; private OverrideMethodsAction fOverrideMethods; private AddGetterSetterAction fAddGetterSetter; private AddDelegateMethodsAction fAddDelegateMethods; private AddUnimplementedConstructorsAction fAddUnimplementedConstructors; private GenerateNewConstructorUsingFieldsAction fGenerateConstructorUsingFields; private AddJavaDocStubAction fAddJavaDocStub; private AddBookmarkAction fAddBookmark; private AddTaskAction fAddTaskAction; private ExternalizeStringsAction fExternalizeStrings; private FindStringsToExternalizeAction fFindStringsToExternalize; private SurroundWithTryCatchAction fSurroundWithTryCatch; private AddToClasspathAction fAddToClasspathAction; private RemoveFromClasspathAction fRemoveFromClasspathAction; private OrganizeImportsAction fOrganizeImports; private SortMembersAction fSortMembers; private ConvertLineDelimitersAction fConvertToWindows; private ConvertLineDelimitersAction fConvertToUNIX; private ConvertLineDelimitersAction fConvertToMac; private static final String QUICK_MENU_ID= "org.eclipse.jdt.ui.edit.text.java.source.quickMenu"; //$NON-NLS-1$ private class RefactorQuickAccessAction extends JDTQuickMenuAction { public RefactorQuickAccessAction(CompilationUnitEditor editor) { super(editor, QUICK_MENU_ID); //$NON-NLS-1$ } protected void fillMenu(IMenuManager menu) { fillQuickMenu(menu); } } private RefactorQuickAccessAction fQuickAccessAction; private IKeyBindingService fKeyBindingService; /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public GenerateActionGroup(CompilationUnitEditor editor, String groupName) { fSite= editor.getSite(); fEditor= editor; fGroupName= groupName; ISelectionProvider provider= fSite.getSelectionProvider(); ISelection selection= provider.getSelection(); fAddImport= new AddImportOnSelectionAction(editor); fAddImport.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_IMPORT); fAddImport.update(); editor.setAction("AddImport", fAddImport); //$NON-NLS-1$ fOrganizeImports= new OrganizeImportsAction(editor); fOrganizeImports.setActionDefinitionId(IJavaEditorActionDefinitionIds.ORGANIZE_IMPORTS); editor.setAction("OrganizeImports", fOrganizeImports); //$NON-NLS-1$ fSortMembers= new SortMembersAction(editor); fSortMembers.setActionDefinitionId(IJavaEditorActionDefinitionIds.SORT_MEMBERS); editor.setAction("SortMembers", fSortMembers); //$NON-NLS-1$ fOverrideMethods= new OverrideMethodsAction(editor); fOverrideMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.OVERRIDE_METHODS); editor.setAction("OverrideMethods", fOverrideMethods); //$NON-NLS-1$ fAddGetterSetter= new AddGetterSetterAction(editor); fAddGetterSetter.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_GETTER_SETTER); editor.setAction("AddGetterSetter", fAddGetterSetter); //$NON-NLS-1$ fAddDelegateMethods= new AddDelegateMethodsAction(editor); fAddDelegateMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_DELEGATE_METHODS); editor.setAction("AddDelegateMethods", fAddDelegateMethods); //$NON-NLS-1$ fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(editor); fAddUnimplementedConstructors.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_UNIMPLEMENTED_CONTRUCTORS); editor.setAction("AddUnimplementedConstructors", fAddUnimplementedConstructors); //$NON-NLS-1$ fGenerateConstructorUsingFields= new GenerateNewConstructorUsingFieldsAction(editor); fGenerateConstructorUsingFields.setActionDefinitionId(IJavaEditorActionDefinitionIds.GENERATE_CONSTRUCTOR_USING_FIELDS); editor.setAction("GenerateConstructorUsingFields", fGenerateConstructorUsingFields); //$NON-NLS-1$ fAddJavaDocStub= new AddJavaDocStubAction(editor); fAddJavaDocStub.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_JAVADOC_COMMENT); editor.setAction("AddJavadocComment", fAddJavaDocStub); //$NON-NLS-1$ fSurroundWithTryCatch= new SurroundWithTryCatchAction(editor); fSurroundWithTryCatch.setActionDefinitionId(IJavaEditorActionDefinitionIds.SURROUND_WITH_TRY_CATCH); fSurroundWithTryCatch.update(selection); provider.addSelectionChangedListener(fSurroundWithTryCatch); editor.setAction("SurroundWithTryCatch", fSurroundWithTryCatch); //$NON-NLS-1$ fExternalizeStrings= new ExternalizeStringsAction(editor); fExternalizeStrings.setActionDefinitionId(IJavaEditorActionDefinitionIds.EXTERNALIZE_STRINGS); editor.setAction("ExternalizeStrings", fExternalizeStrings); //$NON-NLS-1$ fConvertToWindows= new ConvertLineDelimitersAction(editor, "\r\n"); //$NON-NLS-1$ fConvertToWindows.setActionDefinitionId(ITextEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_WINDOWS); fConvertToWindows.setHelpContextId(IAbstractTextEditorHelpContextIds.CONVERT_LINE_DELIMITERS_TO_WINDOWS); editor.setAction("ConvertLineDelimitersToWindows", fConvertToWindows); //$NON-NLS-1$ fConvertToUNIX= new ConvertLineDelimitersAction(editor, "\n"); //$NON-NLS-1$ fConvertToUNIX.setActionDefinitionId(ITextEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_UNIX); fConvertToUNIX.setHelpContextId(IAbstractTextEditorHelpContextIds.CONVERT_LINE_DELIMITERS_TO_UNIX); editor.setAction("ConvertLineDelimitersToUNIX", fConvertToUNIX); //$NON-NLS-1$ fConvertToMac= new ConvertLineDelimitersAction(editor, "\r"); //$NON-NLS-1$ fConvertToMac.setActionDefinitionId(ITextEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_MAC); fConvertToMac.setHelpContextId(IAbstractTextEditorHelpContextIds.CONVERT_LINE_DELIMITERS_TO_MAC); editor.setAction("ConvertLineDelimitersToMac", fConvertToMac); //$NON-NLS-1$ fQuickAccessAction= new RefactorQuickAccessAction(editor); fKeyBindingService= editor.getEditorSite().getKeyBindingService(); fKeyBindingService.registerAction(fQuickAccessAction); } /** * Creates a new <code>GenerateActionGroup</code>. The group * requires that the selection provided by the page's selection provider * is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param page the page that owns this action group */ public GenerateActionGroup(Page page) { this(page.getSite(), null); } /** * Creates a new <code>GenerateActionGroup</code>. The group * requires that the selection provided by the part's selection provider * is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param part the view part that owns this action group */ public GenerateActionGroup(IViewPart part) { this(part.getSite(), part.getSite().getKeyBindingService()); } private GenerateActionGroup(IWorkbenchSite site, IKeyBindingService keyBindingService) { fSite= site; ISelectionProvider provider= fSite.getSelectionProvider(); ISelection selection= provider.getSelection(); fOverrideMethods= new OverrideMethodsAction(site); fOverrideMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.OVERRIDE_METHODS); fAddGetterSetter= new AddGetterSetterAction(site); fAddGetterSetter.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_GETTER_SETTER); fAddDelegateMethods= new AddDelegateMethodsAction(site); fAddDelegateMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_DELEGATE_METHODS); fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(site); fAddUnimplementedConstructors.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_UNIMPLEMENTED_CONTRUCTORS); fGenerateConstructorUsingFields= new GenerateNewConstructorUsingFieldsAction(site); fGenerateConstructorUsingFields.setActionDefinitionId(IJavaEditorActionDefinitionIds.GENERATE_CONSTRUCTOR_USING_FIELDS); fAddJavaDocStub= new AddJavaDocStubAction(site); fAddJavaDocStub.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_JAVADOC_COMMENT); fAddBookmark= new AddBookmarkAction(site.getShell()); fAddBookmark.setActionDefinitionId(IWorkbenchActionDefinitionIds.ADD_BOOKMARK); fAddToClasspathAction= new AddToClasspathAction(site); fRemoveFromClasspathAction= new RemoveFromClasspathAction(site); // context-menu only -> no action definition ids fAddTaskAction= new AddTaskAction(site); fAddTaskAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.ADD_TASK); fExternalizeStrings= new ExternalizeStringsAction(site); fExternalizeStrings.setActionDefinitionId(IJavaEditorActionDefinitionIds.EXTERNALIZE_STRINGS); fFindStringsToExternalize= new FindStringsToExternalizeAction(site); fFindStringsToExternalize.setActionDefinitionId(IJavaEditorActionDefinitionIds.FIND_STRINGS_TO_EXTERNALIZE); fOrganizeImports= new OrganizeImportsAction(site); fOrganizeImports.setActionDefinitionId(IJavaEditorActionDefinitionIds.ORGANIZE_IMPORTS); fSortMembers= new SortMembersAction(site); fSortMembers.setActionDefinitionId(IJavaEditorActionDefinitionIds.SORT_MEMBERS); fOverrideMethods.update(selection); fAddGetterSetter.update(selection); fAddDelegateMethods.update(selection); fAddUnimplementedConstructors.update(selection); fGenerateConstructorUsingFields.update(selection); fAddJavaDocStub.update(selection); fAddToClasspathAction.update(selection); fRemoveFromClasspathAction.update(selection); fExternalizeStrings.update(selection); fFindStringsToExternalize.update(selection); fAddTaskAction.update(selection); fOrganizeImports.update(selection); fSortMembers.update(selection); if (selection instanceof IStructuredSelection) { IStructuredSelection ss= (IStructuredSelection)selection; fAddBookmark.selectionChanged(ss); } else { fAddBookmark.setEnabled(false); } registerSelectionListener(provider, fOverrideMethods); registerSelectionListener(provider, fAddGetterSetter); registerSelectionListener(provider, fAddDelegateMethods); registerSelectionListener(provider, fAddUnimplementedConstructors); registerSelectionListener(provider, fGenerateConstructorUsingFields); registerSelectionListener(provider, fAddJavaDocStub); registerSelectionListener(provider, fAddBookmark); registerSelectionListener(provider, fAddToClasspathAction); registerSelectionListener(provider, fRemoveFromClasspathAction); registerSelectionListener(provider, fExternalizeStrings); registerSelectionListener(provider, fFindStringsToExternalize); registerSelectionListener(provider, fOrganizeImports); registerSelectionListener(provider, fSortMembers); registerSelectionListener(provider, fAddTaskAction); fKeyBindingService= keyBindingService; if (fKeyBindingService != null) { fQuickAccessAction= new RefactorQuickAccessAction(null); fKeyBindingService.registerAction(fQuickAccessAction); } } private void registerSelectionListener(ISelectionProvider provider, ISelectionChangedListener listener) { if (fRegisteredSelectionListeners == null) fRegisteredSelectionListeners= new ArrayList(20); provider.addSelectionChangedListener(listener); fRegisteredSelectionListeners.add(listener); } /* * The state of the editor owning this action group has changed. * This method does nothing if the group's owner isn't an * editor. */ /** * Note: This method is for internal use only. Clients should not call this method. */ public void editorStateChanged() { Assert.isTrue(isEditorOwner()); // http://dev.eclipse.org/bugs/show_bug.cgi?id=17709 fConvertToMac.update(); fConvertToUNIX.update(); fConvertToWindows.update(); } /* (non-Javadoc) * Method declared in ActionGroup */ public void fillActionBars(IActionBars actionBar) { super.fillActionBars(actionBar); setGlobalActionHandlers(actionBar); } /* (non-Javadoc) * Method declared in ActionGroup */ public void fillContextMenu(IMenuManager menu) { super.fillContextMenu(menu); String shortCut= null; //$NON-NLS-1$ if (fQuickAccessAction != null) { shortCut= fQuickAccessAction.getShortCutString(); //$NON-NLS-1$ } IMenuManager subMenu= new MenuManager( ActionMessages.getString("SourceMenu.label") + (shortCut != null ? "\t" + shortCut : "")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ int added= 0; if (isEditorOwner()) { added= fillEditorSubMenu(subMenu); } else { added= fillViewSubMenu(subMenu); } if (added > 0) menu.appendToGroup(fGroupName, subMenu); } private void fillQuickMenu(IMenuManager menu) { if (isEditorOwner()) { fillEditorSubMenu(menu); } else { fillViewSubMenu(menu); } } private int fillEditorSubMenu(IMenuManager source) { int added= 0; added+= addEditorAction(source, "ToggleComment"); //$NON-NLS-1$ added+= addEditorAction(source, "AddBlockComment"); //$NON-NLS-1$ added+= addEditorAction(source, "RemoveBlockComment"); //$NON-NLS-1$ added+= addEditorAction(source, "Format"); //$NON-NLS-1$ added+= addEditorAction(source, "Indent"); //$NON-NLS-1$ source.add(new Separator()); added+= addAction(source, fOrganizeImports); added+= addAction(source, fAddImport); source.add(new Separator()); added+= addAction(source, fOverrideMethods); added+= addAction(source, fAddGetterSetter); added+= addAction(source, fAddDelegateMethods); added+= addAction(source, fAddUnimplementedConstructors); added+= addAction(source, fGenerateConstructorUsingFields); added+= addAction(source, fAddJavaDocStub); source.add(new Separator()); added+= addAction(source, fSurroundWithTryCatch); added+= addAction(source, fExternalizeStrings); return added; } private int fillViewSubMenu(IMenuManager source) { int added= 0; added+= addAction(source, fSortMembers); source.add(new Separator()); added+= addAction(source, fOrganizeImports); added+= addAction(source, fAddImport); source.add(new Separator()); added+= addAction(source, fOverrideMethods); added+= addAction(source, fAddGetterSetter); added+= addAction(source, fAddDelegateMethods); added+= addAction(source, fAddUnimplementedConstructors); added+= addAction(source, fGenerateConstructorUsingFields); added+= addAction(source, fAddJavaDocStub); added+= addAction(source, fAddToClasspathAction); added+= addAction(source, fRemoveFromClasspathAction); source.add(new Separator()); added+= addAction(source, fSurroundWithTryCatch); added+= addAction(source, fExternalizeStrings); added+= addAction(source, fFindStringsToExternalize); return added; } /* (non-Javadoc) * Method declared in ActionGroup */ public void dispose() { if (fRegisteredSelectionListeners != null) { ISelectionProvider provider= fSite.getSelectionProvider(); for (Iterator iter= fRegisteredSelectionListeners.iterator(); iter.hasNext();) { ISelectionChangedListener listener= (ISelectionChangedListener) iter.next(); provider.removeSelectionChangedListener(listener); } } if (fQuickAccessAction != null && fKeyBindingService != null) { fKeyBindingService.unregisterAction(fQuickAccessAction); } fEditor= null; super.dispose(); } private void setGlobalActionHandlers(IActionBars actionBar) { actionBar.setGlobalActionHandler(JdtActionConstants.ADD_IMPORT, fAddImport); actionBar.setGlobalActionHandler(JdtActionConstants.SURROUND_WITH_TRY_CATCH, fSurroundWithTryCatch); actionBar.setGlobalActionHandler(JdtActionConstants.OVERRIDE_METHODS, fOverrideMethods); actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_GETTER_SETTER, fAddGetterSetter); actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_DELEGATE_METHODS, fAddDelegateMethods); actionBar.setGlobalActionHandler(JdtActionConstants.ADD_CONSTRUCTOR_FROM_SUPERCLASS, fAddUnimplementedConstructors); actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_CONSTRUCTOR_USING_FIELDS, fGenerateConstructorUsingFields); actionBar.setGlobalActionHandler(JdtActionConstants.ADD_JAVA_DOC_COMMENT, fAddJavaDocStub); actionBar.setGlobalActionHandler(JdtActionConstants.EXTERNALIZE_STRINGS, fExternalizeStrings); actionBar.setGlobalActionHandler(JdtActionConstants.FIND_STRINGS_TO_EXTERNALIZE, fFindStringsToExternalize); actionBar.setGlobalActionHandler(JdtActionConstants.ORGANIZE_IMPORTS, fOrganizeImports); actionBar.setGlobalActionHandler(JdtActionConstants.SORT_MEMBERS, fSortMembers); actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_WINDOWS, fConvertToWindows); actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_UNIX, fConvertToUNIX); actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_MAC, fConvertToMac); if (!isEditorOwner()) { // editor provides its own implementation of these actions. actionBar.setGlobalActionHandler(IDEActionFactory.BOOKMARK.getId(), fAddBookmark); actionBar.setGlobalActionHandler(IDEActionFactory.ADD_TASK.getId(), fAddTaskAction); } } private int addAction(IMenuManager menu, IAction action) { if (action != null && action.isEnabled()) { menu.add(action); return 1; } return 0; } private int addEditorAction(IMenuManager menu, String actionID) { if (fEditor == null) return 0; IAction action= fEditor.getAction(actionID); if (action == null) return 0; if (action instanceof IUpdate) ((IUpdate)action).update(); if (action.isEnabled()) { menu.add(action); return 1; } return 0; } private boolean isEditorOwner() { return fEditor != null; } }
58,817
Bug 58817 UI no longer responsive when sorting search matches
Build 20040413 I searched for references to type: java.lang.System in org.eclipse.jdt.core project. This found over 4000 matches. I attempted to sort them by parent name, and my IDE locked for about 5 minutes to do the work, with no progress indication, no refresh and 100% CPU usage. Clearly something to improve on UI responsiveness front.
resolved fixed
b4e2a8b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T13:22:01Z
2004-04-16T12:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchResultPage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.search; import java.text.MessageFormat; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.search.IMatchPresentation; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.viewers.DecoratingLabelProvider; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.search.ui.IContextMenuConstants; import org.eclipse.search.ui.ISearchResult; import org.eclipse.search.ui.ISearchResultViewPart; import org.eclipse.search.ui.NewSearchUI; import org.eclipse.search.ui.SearchUI; import org.eclipse.search.ui.text.AbstractTextSearchResult; import org.eclipse.search.ui.text.AbstractTextSearchViewPage; import org.eclipse.search.ui.text.Match; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Widget; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IMemento; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.part.IPageSite; import org.eclipse.ui.part.IShowInTargetList; import org.eclipse.ui.texteditor.ITextEditor; public class JavaSearchResultPage extends AbstractTextSearchViewPage implements IAdaptable { private static final String KEY_GROUPING= "org.eclipse.jdt.search.resultpage.grouping"; //$NON-NLS-1$ private static final String KEY_SORTING= "org.eclipse.jdt.search.resultpage.sorting"; //$NON-NLS-1$ private static final String KEY_FILTERS= "org.eclipse.jdt.search.resultpage.filters"; //$NON-NLS-1$ private static final String GROUP_GROUPING= "org.eclipse.jdt.search.resultpage.grouping"; //$NON-NLS-1$ private NewSearchViewActionGroup fActionGroup; private JavaSearchContentProvider fContentProvider; private int fCurrentSortOrder; private SortAction fSortByNameAction; private SortAction fSortByParentName; private SortAction fSortByPathAction; private GroupAction fGroupTypeAction; private GroupAction fGroupFileAction; private GroupAction fGroupPackageAction; private GroupAction fGroupProjectAction; private int fCurrentGrouping; private Set fMatchFilters= new HashSet(); private FilterAction[] fFilterActions; private static final String[] SHOW_IN_TARGETS= new String[] { JavaUI.ID_PACKAGES , IPageLayout.ID_RES_NAV }; public static final IShowInTargetList SHOW_IN_TARGET_LIST= new IShowInTargetList() { public String[] getShowInTargetIds() { return SHOW_IN_TARGETS; } }; private JavaSearchEditorOpener fEditorOpener= new JavaSearchEditorOpener(); public JavaSearchResultPage() { initSortActions(); initGroupingActions(); initFilterActions(); } private void initFilterActions() { MatchFilter[] allFilters= MatchFilter.allFilters(); fFilterActions= new FilterAction[allFilters.length]; for (int i= 0; i < fFilterActions.length; i++) { fFilterActions[i]= new FilterAction(this, allFilters[i]); } } private void initSortActions() { fSortByNameAction= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByName"), this, SortingLabelProvider.SHOW_ELEMENT_CONTAINER); //$NON-NLS-1$ fSortByPathAction= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByPath"), this, SortingLabelProvider.SHOW_PATH); //$NON-NLS-1$ fSortByParentName= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByParentName"), this, SortingLabelProvider.SHOW_CONTAINER_ELEMENT); //$NON-NLS-1$ } private void initGroupingActions() { fGroupProjectAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_project"), SearchMessages.getString("JavaSearchResultPage.groupby_project.tooltip"), this, LevelTreeContentProvider.LEVEL_PROJECT); //$NON-NLS-1$ //$NON-NLS-2$ JavaPluginImages.setLocalImageDescriptors(fGroupProjectAction, "prj_mode.gif"); //$NON-NLS-1$ fGroupPackageAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_package"), SearchMessages.getString("JavaSearchResultPage.groupby_package.tooltip"), this, LevelTreeContentProvider.LEVEL_PACKAGE); //$NON-NLS-1$ //$NON-NLS-2$ JavaPluginImages.setLocalImageDescriptors(fGroupPackageAction, "package_mode.gif"); //$NON-NLS-1$ fGroupFileAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_file"), SearchMessages.getString("JavaSearchResultPage.groupby_file.tooltip"), this, LevelTreeContentProvider.LEVEL_FILE); //$NON-NLS-1$ //$NON-NLS-2$ JavaPluginImages.setLocalImageDescriptors(fGroupFileAction, "file_mode.gif"); //$NON-NLS-1$ fGroupTypeAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_type"), SearchMessages.getString("JavaSearchResultPage.groupby_type.tooltip"), this, LevelTreeContentProvider.LEVEL_TYPE); //$NON-NLS-1$ //$NON-NLS-2$ JavaPluginImages.setLocalImageDescriptors(fGroupTypeAction, "type_mode.gif"); //$NON-NLS-1$ } public void setViewPart(ISearchResultViewPart part) { super.setViewPart(part); fActionGroup= new NewSearchViewActionGroup(part); } public void showMatch(Match match, int offset, int length, boolean activate) throws PartInitException { IEditorPart editor; try { editor= fEditorOpener.open(match); } catch (JavaModelException e) { throw new PartInitException(e.getStatus()); } if (editor != null && activate) editor.getEditorSite().getPage().activate(editor); Object element= match.getElement(); if (editor instanceof ITextEditor) { ITextEditor textEditor= (ITextEditor) editor; textEditor.selectAndReveal(offset, length); } else if (editor != null){ if (element instanceof IFile) { IFile file= (IFile) element; showWithMarker(editor, file, offset, length); } } else { JavaSearchResult result= (JavaSearchResult) getInput(); IMatchPresentation participant= result.getSearchParticpant(element); if (participant != null) participant.showMatch(match, offset, length, activate); } } private void showWithMarker(IEditorPart editor, IFile file, int offset, int length) throws PartInitException { try { IMarker marker= file.createMarker(SearchUI.SEARCH_MARKER); HashMap attributes= new HashMap(4); attributes.put(IMarker.CHAR_START, new Integer(offset)); attributes.put(IMarker.CHAR_END, new Integer(offset + length)); marker.setAttributes(attributes); IDE.gotoMarker(editor, marker); marker.delete(); } catch (CoreException e) { throw new PartInitException(SearchMessages.getString("JavaSearchResultPage.error.marker"), e); //$NON-NLS-1$ } } protected void fillContextMenu(IMenuManager mgr) { super.fillContextMenu(mgr); addSortActions(mgr); fActionGroup.setContext(new ActionContext(getSite().getSelectionProvider().getSelection())); fActionGroup.fillContextMenu(mgr); } private void addFilterActions(IMenuManager viewMenu) { String filteringGroup= "Filtering"; //$NON-NLS-1$ viewMenu.add(new Separator(filteringGroup)); MenuManager mgr= new MenuManager(SearchMessages.getString("JavaSearchResultPage.filter.submenu")); //$NON-NLS-1$ for (int i= 0; i < fFilterActions.length; i++) { mgr.add(fFilterActions[i]); } viewMenu.appendToGroup(filteringGroup, mgr); } private void addSortActions(IMenuManager mgr) { if (getLayout() != FLAG_LAYOUT_FLAT) return; MenuManager sortMenu= new MenuManager(SearchMessages.getString("JavaSearchResultPage.sortBylabel")); //$NON-NLS-1$ sortMenu.add(fSortByNameAction); sortMenu.add(fSortByPathAction); sortMenu.add(fSortByParentName); fSortByNameAction.setChecked(fCurrentSortOrder == fSortByNameAction.getSortOrder()); fSortByPathAction.setChecked(fCurrentSortOrder == fSortByPathAction.getSortOrder()); fSortByParentName.setChecked(fCurrentSortOrder == fSortByParentName.getSortOrder()); mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, sortMenu); } protected void fillToolbar(IToolBarManager tbm) { super.fillToolbar(tbm); if (getLayout() != FLAG_LAYOUT_FLAT) addGroupActions(tbm); } private void addGroupActions(IToolBarManager mgr) { mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, new Separator(GROUP_GROUPING)); mgr.appendToGroup(GROUP_GROUPING, fGroupProjectAction); mgr.appendToGroup(GROUP_GROUPING, fGroupPackageAction); mgr.appendToGroup(GROUP_GROUPING, fGroupFileAction); mgr.appendToGroup(GROUP_GROUPING, fGroupTypeAction); updateGroupingActions(); } private void updateGroupingActions() { fGroupProjectAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_PROJECT); fGroupPackageAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_PACKAGE); fGroupFileAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_FILE); fGroupTypeAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_TYPE); } public void dispose() { fActionGroup.dispose(); super.dispose(); } protected void elementsChanged(Object[] objects) { if (fContentProvider != null) fContentProvider.elementsChanged(objects); } protected void clear() { if (fContentProvider != null) fContentProvider.clear(); } protected void configureTableViewer(TableViewer viewer) { viewer.setUseHashlookup(true); viewer.setLabelProvider(new DecoratingLabelProvider(new SortingLabelProvider(this), PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator())); fContentProvider=new JavaSearchTableContentProvider(this); viewer.setContentProvider(fContentProvider); setSortOrder(fCurrentSortOrder); } protected void configureTreeViewer(TreeViewer viewer) { viewer.setUseHashlookup(true); viewer.setSorter(new ViewerSorter()); viewer.setLabelProvider(new DecoratingLabelProvider(new PostfixLabelProvider(this), PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator())); fContentProvider= new LevelTreeContentProvider(this, fCurrentGrouping); viewer.setContentProvider(fContentProvider); } protected TreeViewer createTreeViewer(Composite parent) { return new ProblemTreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); } class MyProblemTable extends ProblemTableViewer { MyProblemTable(Composite parent, int flags) { super(parent, flags); } protected void internalRefresh(Object element, boolean updateLabels) { if (element == null || equals(element, getRoot())) { // the parent // in the code below, it is important to do all disassociates // before any associates, since a later disassociate can undo an earlier associate // e.g. if (a, b) is replaced by (b, a), the disassociate of b to item 1 could undo // the associate of b to item 0. Object[] children = getSortedChildren(getRoot()); getTable().removeAll(); // add any remaining elements for (int i = 0; i < children.length; ++i) { updateItem(new TableItem(getTable(), SWT.NONE, i), children[i]); } } else { Widget w = findItem(element); if (w != null) { updateItem(w, element); } } } } protected TableViewer createTableViewer(Composite parent) { return new ProblemTableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); } void setSortOrder(int order) { fCurrentSortOrder= order; StructuredViewer viewer= getViewer(); viewer.getControl().setRedraw(false); DecoratingLabelProvider dlp= (DecoratingLabelProvider) viewer.getLabelProvider(); ((SortingLabelProvider)dlp.getLabelProvider()).setOrder(order); if (order == SortingLabelProvider.SHOW_ELEMENT_CONTAINER) { viewer.setSorter(new NameSorter()); } else if (order == SortingLabelProvider.SHOW_PATH) { viewer.setSorter(new PathSorter()); } else viewer.setSorter(new ParentSorter()); viewer.getControl().setRedraw(true); getSettings().put(KEY_SORTING, fCurrentSortOrder); } public void init(IPageSite site) { super.init(site); fActionGroup.fillActionBars(site.getActionBars()); addFilterActions(site.getActionBars().getMenuManager()); } /** * Precondition here: the viewer must be showing a tree with a LevelContentProvider. * @param order */ void setGrouping(int grouping) { fCurrentGrouping= grouping; StructuredViewer viewer= getViewer(); LevelTreeContentProvider cp= (LevelTreeContentProvider) viewer.getContentProvider(); cp.setLevel(grouping); updateGroupingActions(); getSettings().put(KEY_GROUPING, fCurrentGrouping); } protected StructuredViewer getViewer() { // override so that it's visible in the package. return super.getViewer(); } /* (non-Javadoc) * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#restoreState(org.eclipse.ui.IMemento) */ public void restoreState(IMemento memento) { super.restoreState(memento); try { fCurrentSortOrder= getSettings().getInt(KEY_SORTING); } catch (NumberFormatException e) { fCurrentSortOrder= SortingLabelProvider.SHOW_ELEMENT_CONTAINER; } try { fCurrentGrouping= getSettings().getInt(KEY_GROUPING); } catch (NumberFormatException e) { fCurrentGrouping= LevelTreeContentProvider.LEVEL_PACKAGE; } String encodedFilters= getSettings().get(KEY_FILTERS); restoreFilters(encodedFilters); if (memento != null) { Integer value= memento.getInteger(KEY_GROUPING); if (value != null) fCurrentGrouping= value.intValue(); value= memento.getInteger(KEY_SORTING); if (value != null) fCurrentSortOrder= value.intValue(); encodedFilters= memento.getString(KEY_FILTERS); restoreFilters(encodedFilters); } } private void restoreFilters(String encodedFilters) { if (encodedFilters != null) { fMatchFilters.clear(); String[] decodedFilters= decodeFiltersString(encodedFilters); for (int i= 0; i < decodedFilters.length; i++) { MatchFilter filter= findMatchFilter(decodedFilters[i]); if (filter != null) fMatchFilters.add(filter); } } updateFilterActions(); } private MatchFilter findMatchFilter(String id) { MatchFilter[] allFilters= MatchFilter.allFilters(); for (int i= 0; i < allFilters.length; i++) { if (allFilters[i].getID().equals(id)) return allFilters[i]; } return null; } /* (non-Javadoc) * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#saveState(org.eclipse.ui.IMemento) */ public void saveState(IMemento memento) { super.saveState(memento); memento.putInteger(KEY_GROUPING, fCurrentGrouping); memento.putInteger(KEY_SORTING, fCurrentSortOrder); memento.putString(KEY_FILTERS, encodeFilters()); } void addMatchFilter(MatchFilter filter) { fMatchFilters.add(filter); filtersChanged(); } void removeMatchFilter(MatchFilter filter) { fMatchFilters.remove(filter); filtersChanged(); } private void filtersChanged() { StructuredViewer viewer= getViewer(); JavaSearchContentProvider cp= (JavaSearchContentProvider) viewer.getContentProvider(); cp.filtersChanged(getMatchFilters()); updateFilterActions(); getViewPart().updateLabel(); getSettings().put(KEY_FILTERS, encodeFilters()); } private void updateFilterActions() { for (int i= 0; i < fFilterActions.length; i++) { fFilterActions[i].updateCheckState(); } getSite().getActionBars().updateActionBars(); getSite().getActionBars().getMenuManager().updateAll(true); } private String encodeFilters() { StringBuffer buf= new StringBuffer(); MatchFilter[] enabledFilters= getMatchFilters(); buf.append(enabledFilters.length); for (int i= 0; i < enabledFilters.length; i++) { buf.append(';'); buf.append(enabledFilters[i].getID()); } return buf.toString(); } private String[] decodeFiltersString(String encodedString) { StringTokenizer tokenizer= new StringTokenizer(encodedString, ";"); //$NON-NLS-1$ int count= Integer.valueOf(tokenizer.nextToken()).intValue(); String[] ids= new String[count]; for (int i= 0; i < count; i++) { ids[i]= tokenizer.nextToken(); } return ids; } boolean hasMatchFilter(MatchFilter filter) { return fMatchFilters.contains(filter); } MatchFilter[] getMatchFilters() { MatchFilter[] filters= new MatchFilter[fMatchFilters.size()]; return (MatchFilter[]) fMatchFilters.toArray(filters); } public int getDisplayedMatchCount(Object element) { if (getMatchFilters().length == 0) return super.getDisplayedMatchCount(element); Match[] matches= super.getDisplayedMatches(element); int count= 0; for (int i= 0; i < matches.length; i++) { if (!isFiltered(matches[i])) count++; } return count; } public Match[] getDisplayedMatches(Object element) { if (getMatchFilters().length == 0) return super.getDisplayedMatches(element); Match[] matches= super.getDisplayedMatches(element); int count= 0; for (int i= 0; i < matches.length; i++) { if (isFiltered(matches[i])) matches[i]= null; else count++; } Match[] filteredMatches= new Match[count]; int writeIndex= 0; for (int i= 0; i < matches.length; i++) { if (matches[i] != null) filteredMatches[writeIndex++]= matches[i]; } return filteredMatches; } private boolean isFiltered(Match match) { MatchFilter[] filters= getMatchFilters(); for (int j= 0; j < filters.length; j++) { if ((match instanceof JavaElementMatch) && filters[j].filters((JavaElementMatch) match)) return true; } return false; } public void setInput(ISearchResult search, Object viewState) { updateFilterEnablement((JavaSearchResult)search); super.setInput(search, viewState); } private void updateFilterEnablement(JavaSearchResult result) { for (int i= 0; i < fFilterActions.length; i++) { fFilterActions[i].setEnabled(shouldEnable(result, fFilterActions[i])); } } private boolean shouldEnable(JavaSearchResult result, FilterAction filterAction) { if (result == null) { return false; } JavaSearchQuery query= (JavaSearchQuery) result.getQuery(); if (query == null) return false; return filterAction.getFilter().isApplicable(query); } private boolean isQueryRunning() { AbstractTextSearchResult result= getInput(); if (result != null) { return NewSearchUI.isQueryRunning(result.getQuery()); } return false; } public String getLabel() { String label= super.getLabel(); int matchFilterCount= getMatchFiltersCount(); if (matchFilterCount > 0) { if (isQueryRunning()) { String message= SearchMessages.getString("JavaSearchResultPage.filtered.message"); //$NON-NLS-1$ return MessageFormat.format(message, new Object[] { label }); } else { String message= SearchMessages.getString("JavaSearchResultPage.filteredWithCount.message"); //$NON-NLS-1$ return MessageFormat.format(message, new Object[] { label, new Integer(getFilteredMatchCount()) }); } } return label; } private int getMatchFiltersCount() { MatchFilter[] filters= getMatchFilters(); AbstractTextSearchResult result= getInput(); if (result == null) return 0; int filterCount= 0; for (int i= 0; i < filters.length; i++) { if (filters[i].isApplicable((JavaSearchQuery) result.getQuery())) filterCount++; } return filterCount; } private int getFilteredMatchCount() { AbstractTextSearchResult result= getInput(); if (result == null) return 0; Object[] elements= result.getElements(); int count= 0; for (int i= 0; i < elements.length; i++) { count+= getDisplayedMatchCount(elements[i]); } return count; } /* (non-Javadoc) * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) */ public Object getAdapter(Class adapter) { if (IShowInTargetList.class.equals(adapter)) { return SHOW_IN_TARGET_LIST; } return null; } }
61,723
Bug 61723 NPE when opening GetterSetterDialog
20040511 java.lang.NullPointerException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at java.lang.NullPointerException.<init>(NullPointerException.java:60) at org.eclipse.jface.resource.StringConverter.asBoolean(StringConverter.java:137) at org.eclipse.jface.resource.StringConverter.asBoolean(StringConverter.java:155) at org.eclipse.jdt.internal.ui.dialogs.SourceActionDialog.<init>(SourceActionDialog.java:118) at org.eclipse.jdt.ui.actions.AddGetterSetterAction$GetterSetterTreeSelectionDialog.<init>(AddGetterSetterAction.java:808) at org.eclipse.jdt.ui.actions.AddGetterSetterAction.run(AddGetterSetterAction.java:238) at org.eclipse.jdt.ui.actions.AddGetterSetterAction.run(AddGetterSetterAction.java:495) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:216) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:188) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:612) at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:563) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:482) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1353) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1324) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:243) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:140) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:90) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:283) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:242) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:119) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:79) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:41) at java.lang.reflect.Method.invoke(Method.java:386) at org.eclipse.core.launcher.Main.basicRun(Main.java:269) at org.eclipse.core.launcher.Main.run(Main.java:700) at org.eclipse.core.launcher.Main.main(Main.java:684)
verified fixed
ec52839
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T13:22:03Z
2004-05-11T12:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/SourceActionDialog.java
/******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.dialogs; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.resource.StringConverter; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.CheckboxTreeViewer; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.ui.dialogs.CheckedTreeSelectionDialog; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.ActionMessages; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.refactoring.IVisibilityChangeListener; import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; /** * An advanced version of CheckedTreeSelectionDialog with right-side button layout and * extra buttons and composites. */ public class SourceActionDialog extends CheckedTreeSelectionDialog { private List fInsertPositions; private List fLabels; private int fCurrentPositionIndex; private IDialogSettings fSettings; private CompilationUnitEditor fEditor; private ITreeContentProvider fContentProvider; private boolean fGenerateComment; private IType fType; private int fWidth, fHeight; private String fCommentString; private int fVisibilityModifier; private boolean fFinal; private boolean fSynchronized; private final String SETTINGS_SECTION_METHODS= "SourceActionDialog.methods"; //$NON-NLS-1$ private final String SETTINGS_SECTION_CONSTRUCTORS= "SourceActionDialog.constructors"; //$NON-NLS-1$ private final String SETTINGS_INSERTPOSITION= "InsertPosition"; //$NON-NLS-1$ private final String SETTINGS_VISIBILITY_MODIFIER= "VisibilityModifier"; //$NON-NLS-1$ private final String SETTINGS_FINAL_MODIFIER= "FinalModifier"; //$NON-NLS-1$ private final String SETTINGS_SYNCHRONIZED_MODIFIER= "SynchronizedModifier"; //$NON-NLS-1$ private final String SETTINGS_COMMENTS= "Comments"; //$NON-NLS-1$ public SourceActionDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider, CompilationUnitEditor editor, IType type, boolean isConstructor) throws JavaModelException { super(parent, labelProvider, contentProvider); fEditor= editor; fContentProvider= contentProvider; fType= type; fCommentString= ActionMessages.getString("SourceActionDialog.createMethodComment"); //$NON-NLS-1$ fWidth= 60; fHeight= 18; int insertionDefault= isConstructor ? 0 : 1; boolean generateCommentsDefault= JavaPreferencesSettings.getCodeGenerationSettings().createComments; IDialogSettings dialogSettings= JavaPlugin.getDefault().getDialogSettings(); String sectionId= isConstructor ? SETTINGS_SECTION_CONSTRUCTORS : SETTINGS_SECTION_METHODS; fSettings= dialogSettings.getSection(sectionId); if (fSettings == null) { fSettings= dialogSettings.addNewSection(sectionId); fSettings.put(SETTINGS_VISIBILITY_MODIFIER, StringConverter.asString(Modifier.PUBLIC)); fSettings.put(SETTINGS_FINAL_MODIFIER, StringConverter.asString(false)); fSettings.put(SETTINGS_SYNCHRONIZED_MODIFIER, StringConverter.asString(false)); fSettings.put(SETTINGS_INSERTPOSITION, insertionDefault); fSettings.put(SETTINGS_COMMENTS, generateCommentsDefault); } fVisibilityModifier= StringConverter.asInt(fSettings.get(SETTINGS_VISIBILITY_MODIFIER), Modifier.PUBLIC); fFinal= StringConverter.asBoolean(fSettings.get(SETTINGS_FINAL_MODIFIER), false); fSynchronized= StringConverter.asBoolean(fSettings.get(SETTINGS_SYNCHRONIZED_MODIFIER), false); fCurrentPositionIndex= StringConverter.asInt(fSettings.get(SETTINGS_INSERTPOSITION), insertionDefault); fGenerateComment= StringConverter.asBoolean(fSettings.get(SETTINGS_COMMENTS), generateCommentsDefault); fInsertPositions= new ArrayList(); fLabels= new ArrayList(); IJavaElement[] members= fType.getChildren(); IMethod[] methods= fType.getMethods(); fInsertPositions.add(methods.length > 0 ? methods[0]: null); // first fInsertPositions.add(null); // last fLabels.add(ActionMessages.getString("SourceActionDialog.first_method")); //$NON-NLS-1$ fLabels.add(ActionMessages.getString("SourceActionDialog.last_method")); //$NON-NLS-1$ if (hasCursorPositionElement(fEditor, members, fInsertPositions)) { fLabels.add(ActionMessages.getString("SourceActionDialog.cursor")); //$NON-NLS-1$ fCurrentPositionIndex= 2; } for (int i = 0; i < methods.length; i++) { IMethod curr= methods[i]; String methodLabel= JavaElementLabels.getElementLabel(curr, JavaElementLabels.M_PARAMETER_TYPES); fLabels.add(ActionMessages.getFormattedString("SourceActionDialog.after", methodLabel)); //$NON-NLS-1$ fInsertPositions.add(findSibling(curr, members)); } fInsertPositions.add(null); } private IJavaElement findSibling(IMethod curr, IJavaElement[] members) throws JavaModelException { IJavaElement res= null; int methodStart= curr.getSourceRange().getOffset(); for (int i= members.length-1; i >= 0; i--) { IMember member= (IMember) members[i]; if (methodStart < member.getSourceRange().getOffset()) { return res; } res= member; } return null; } private boolean hasCursorPositionElement(CompilationUnitEditor editor, IJavaElement[] members, List insertPositions) throws JavaModelException { if (editor == null) { return false; } int offset= ((ITextSelection) editor.getSelectionProvider().getSelection()).getOffset(); for (int i= 0; i < members.length; i++) { IMember curr= (IMember) members[i]; ISourceRange range= curr.getSourceRange(); if (offset < range.getOffset()) { insertPositions.add(curr); return true; } else if (offset < range.getOffset() + range.getLength()) { return false; // in the middle of a member } } insertPositions.add(null); return true; } /* (non-Javadoc) * @see org.eclipse.jface.dialogs.Dialog#close() */ public boolean close() { fSettings.put(SETTINGS_VISIBILITY_MODIFIER, StringConverter.asString(fVisibilityModifier)); fSettings.put(SETTINGS_FINAL_MODIFIER, StringConverter.asString(fFinal)); fSettings.put(SETTINGS_SYNCHRONIZED_MODIFIER, StringConverter.asString(fSynchronized)); if (fCurrentPositionIndex == 0 || fCurrentPositionIndex == 1) { fSettings.put(SETTINGS_INSERTPOSITION, StringConverter.asString(fCurrentPositionIndex)); } fSettings.put(SETTINGS_COMMENTS, fGenerateComment); return super.close(); } /** * Sets the size of the tree in unit of characters. * @param width the width of the tree. * @param height the height of the tree. */ public void setSize(int width, int height) { fWidth = width; fHeight = height; } /*** * Set insert position valid input is 0 for the first position, 1 for the last position, > 1 for all else. */ private void setInsertPosition(int insert) { fCurrentPositionIndex= insert; fSettings.put(SETTINGS_INSERTPOSITION, insert); } public void setCommentString(String string) { fCommentString= string; } protected ITreeContentProvider getContentProvider() { return fContentProvider; } public boolean getGenerateComment() { return fGenerateComment; } public int getVisibilityModifier() { return fVisibilityModifier; } public void setGenerateComment(boolean comment) { fGenerateComment= comment; } private void setVisibility(int visibility) { fVisibilityModifier= visibility; } private void setFinal(boolean value) { fFinal= value; } private void setSynchronized(boolean value) { fSynchronized= value; } protected Composite createSelectionButtons(Composite composite) { Composite buttonComposite= super.createSelectionButtons(composite); GridLayout layout = new GridLayout(); buttonComposite.setLayout(layout); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 1; return buttonComposite; } protected void buttonPressed(int buttonId) { switch (buttonId) { case IDialogConstants.OK_ID: { okPressed(); break; } case IDialogConstants.CANCEL_ID: { cancelPressed(); break; } } } /** * Returns a composite containing the label created at the top of the dialog. Returns null if there is the * message for the label is null. */ protected Label createMessageArea(Composite composite) { if (getMessage() != null) { Label label = new Label(composite,SWT.NONE); label.setText(getMessage()); label.setFont(composite.getFont()); return label; } return null; } /* * @see Dialog#createDialogArea(Composite) */ protected Control createDialogArea(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); GridData gd= null; layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); composite.setLayout(layout); Label messageLabel = createMessageArea(composite); if (messageLabel != null) { gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; messageLabel.setLayoutData(gd); } Composite inner= new Composite(composite, SWT.NONE); GridLayout innerLayout = new GridLayout(); innerLayout.numColumns= 2; innerLayout.marginHeight= 0; innerLayout.marginWidth= 0; inner.setLayout(innerLayout); inner.setFont(parent.getFont()); CheckboxTreeViewer treeViewer= createTreeViewer(inner); gd= new GridData(GridData.FILL_BOTH); gd.widthHint = convertWidthInCharsToPixels(fWidth); gd.heightHint = convertHeightInCharsToPixels(fHeight); treeViewer.getControl().setLayoutData(gd); Composite buttonComposite= createSelectionButtons(inner); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL); buttonComposite.setLayoutData(gd); gd= new GridData(GridData.FILL_BOTH); inner.setLayoutData(gd); Composite entryComposite= createEntryPtCombo(composite); entryComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Composite commentComposite= createCommentSelection(composite); commentComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); gd= new GridData(GridData.FILL_BOTH); composite.setLayoutData(gd); applyDialogFont(composite); return composite; } protected Composite createCommentSelection(Composite composite) { Composite commentComposite = new Composite(composite, SWT.NONE); GridLayout layout = new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; commentComposite.setLayout(layout); commentComposite.setFont(composite.getFont()); Button commentButton= new Button(commentComposite, SWT.CHECK); commentButton.setText(fCommentString); //$NON-NLS-1$ commentButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); commentButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { boolean isSelected= (((Button) e.widget).getSelection()); setGenerateComment(isSelected); } public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); commentButton.setSelection(getGenerateComment()); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; commentButton.setLayoutData(gd); return commentComposite; } protected Composite addVisibilityAndModifiersChoices(Composite buttonComposite) { // Add visibility and modifiers buttons: http://bugs.eclipse.org/bugs/show_bug.cgi?id=35870 // Add persistence of options: http://bugs.eclipse.org/bugs/show_bug.cgi?id=38400 IVisibilityChangeListener visibilityChangeListener= new IVisibilityChangeListener(){ public void visibilityChanged(int newVisibility) { setVisibility(newVisibility); } public void modifierChanged(int modifier, boolean isChecked) { switch (modifier) { case Modifier.FINAL: { setFinal(isChecked); return; } case Modifier.SYNCHRONIZED: { setSynchronized(isChecked); return; } default: return; } } }; int initialVisibility= getVisibilityModifier(); int[] availableVisibilities= new int[]{Modifier.PUBLIC, Modifier.PROTECTED, Modifier.PRIVATE, Modifier.NONE}; Composite visibilityComposite= createVisibilityControlAndModifiers(buttonComposite, visibilityChangeListener, availableVisibilities, initialVisibility); return visibilityComposite; } private List convertToIntegerList(int[] array) { List result= new ArrayList(array.length); for (int i= 0; i < array.length; i++) { result.add(new Integer(array[i])); } return result; } protected Composite createVisibilityControl(Composite parent, final IVisibilityChangeListener visibilityChangeListener, int[] availableVisibilities, int correctVisibility) { List allowedVisibilities= convertToIntegerList(availableVisibilities); if (allowedVisibilities.size() == 1) return null; Group group= new Group(parent, SWT.NONE); group.setText(RefactoringMessages.getString("VisibilityControlUtil.Access_modifier")); //$NON-NLS-1$ GridData gd= new GridData(GridData.FILL_BOTH); group.setLayoutData(gd); GridLayout layout= new GridLayout(); layout.makeColumnsEqualWidth= true; layout.numColumns= 4; group.setLayout(layout); String[] labels= new String[] { "&public", //$NON-NLS-1$ "pro&tected", //$NON-NLS-1$ RefactoringMessages.getString("VisibilityControlUtil.defa&ult_4"), //$NON-NLS-1$ "pri&vate" //$NON-NLS-1$ }; Integer[] data= new Integer[] { new Integer(Modifier.PUBLIC), new Integer(Modifier.PROTECTED), new Integer(Modifier.NONE), new Integer(Modifier.PRIVATE)}; Integer initialVisibility= new Integer(correctVisibility); for (int i= 0; i < labels.length; i++) { Button radio= new Button(group, SWT.RADIO); Integer visibilityCode= data[i]; radio.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); radio.setText(labels[i]); radio.setData(visibilityCode); radio.setSelection(visibilityCode.equals(initialVisibility)); radio.setEnabled(allowedVisibilities.contains(visibilityCode)); radio.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { visibilityChangeListener.visibilityChanged(((Integer)event.widget.getData()).intValue()); } }); } return group; } protected Composite createVisibilityControlAndModifiers(Composite parent, final IVisibilityChangeListener visibilityChangeListener, int[] availableVisibilities, int correctVisibility) { Composite visibilityComposite= createVisibilityControl(parent, visibilityChangeListener, availableVisibilities, correctVisibility); Button finalCheckboxButton= new Button(visibilityComposite, SWT.CHECK); finalCheckboxButton.setText(RefactoringMessages.getString("VisibilityControlUtil.final")); //$NON-NLS-1$ GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); finalCheckboxButton.setLayoutData(gd); finalCheckboxButton.setData(new Integer(Modifier.FINAL)); finalCheckboxButton.setEnabled(true); finalCheckboxButton.setSelection(isFinal()); finalCheckboxButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent event) { visibilityChangeListener.modifierChanged(((Integer)event.widget.getData()).intValue(), ((Button) event.widget).getSelection()); } public void widgetDefaultSelected(SelectionEvent event) { widgetSelected(event); } }); Button syncCheckboxButton= new Button(visibilityComposite, SWT.CHECK); syncCheckboxButton.setText(RefactoringMessages.getString("VisibilityControlUtil.synchronized")); //$NON-NLS-1$ gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); syncCheckboxButton.setLayoutData(gd); syncCheckboxButton.setData(new Integer(Modifier.SYNCHRONIZED)); syncCheckboxButton.setEnabled(true); syncCheckboxButton.setSelection(isSynchronized()); syncCheckboxButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent event) { visibilityChangeListener.modifierChanged(((Integer)event.widget.getData()).intValue(), ((Button) event.widget).getSelection()); } public void widgetDefaultSelected(SelectionEvent event) { widgetSelected(event); } }); return visibilityComposite; } protected Composite createEntryPtCombo(Composite composite) { Composite selectionComposite = new Composite(composite, SWT.NONE); GridLayout layout = new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; selectionComposite.setLayout(layout); addOrderEntryChoices(selectionComposite); return selectionComposite; } private Composite addOrderEntryChoices(Composite buttonComposite) { Label enterLabel= new Label(buttonComposite, SWT.NONE); enterLabel.setText(ActionMessages.getString("SourceActionDialog.enterAt_label")); //$NON-NLS-1$ GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); enterLabel.setLayoutData(gd); final Combo enterCombo= new Combo(buttonComposite, SWT.READ_ONLY); fillWithPossibleInsertPositions(enterCombo); gd= new GridData(GridData.FILL_BOTH); gd.widthHint= convertWidthInCharsToPixels(fWidth); enterCombo.setLayoutData(gd); enterCombo.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { int index= enterCombo.getSelectionIndex(); // Add persistence only if first or last method: http://bugs.eclipse.org/bugs/show_bug.cgi?id=38400 setInsertPosition(index); } }); return buttonComposite; } private void fillWithPossibleInsertPositions(Combo combo) { combo.setItems((String[]) fLabels.toArray(new String[fLabels.size()])); combo.select(fCurrentPositionIndex); } public boolean getFinal() { return fFinal; } public boolean getSynchronized() { return fSynchronized; } public boolean isFinal() { return fFinal; } public boolean isSynchronized() { return fSynchronized; } /* * Determine where in the file to enter the newly created methods. */ public IJavaElement getElementPosition() { return (IJavaElement) fInsertPositions.get(fCurrentPositionIndex); } }
49,772
Bug 49772 Change method signature: remove unused imports [refactoring]
M6 package org.eclipse.jdt.internal.corext.refactoring.base; import org.eclipse.core.runtime.IAdaptable; /** * A <code>RefactoringStatusContext<code> can be used to annotate a * {@link RefactoringStatusEntry} with additional information * typically presented in the UI. * * @since 3.0 */ public class RefactoringStatusContext { /** * Returns the element that corresponds directly to this context, * or <code>null</code> if there is no corresponding element. * <p> * For example, the corresponding element of a context for a problem * detected in an <code>IResource</code> would the the resource itself. * <p> * * @return the corresponding element, or <code>null</code> if none */ public IAdaptable getCorrespondingElement() { return null; } } Consider the code from above and change the signature of getCorrespondingElement to return Object. If you press preview you get an refactoring error telling me that the import isn't used. Since we already detect this case we should remove the import. I know that this might introduce inconsistencies with other refactorings but getting this error message is even worse.
resolved fixed
905fdb3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T13:48:47Z
2004-01-09T14:53:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testAll60_out.java
package p; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; class A { /** * @param tho {@link #getList} * @param tho * @param l TODO * @param to 1st param of {@link A#getList(long, List, int) me} * @param to 2nd * @version throwaway * @throws Exception TODO * @see #getList(long, List, int) * @see #getList(long tho, List l, int to) * @return the list */ public List getList(long tho, List l, int to) throws Exception { //change to: java.util.List getList(long tho, List l, int to) throws Exception // (swap parameters, insert new in between, change return type, change Ex.) return new ArrayList((int)tho-to); } } interface I { public List getList(long tho, List l, int to) throws Exception; } interface J { /** Doc: @param t t * @param l TODO * @throws Exception TODO*/ public List getList(long t, List l, int f) throws FileNotFoundException, Exception; } class B extends A implements I, J { /** * @return {@inheritDoc} * @see p.A#getList(long, List, int) */ public List getList(long tho, List l, int to) throws FileNotFoundException, Exception { return new ArrayList() {}; } }
49,772
Bug 49772 Change method signature: remove unused imports [refactoring]
M6 package org.eclipse.jdt.internal.corext.refactoring.base; import org.eclipse.core.runtime.IAdaptable; /** * A <code>RefactoringStatusContext<code> can be used to annotate a * {@link RefactoringStatusEntry} with additional information * typically presented in the UI. * * @since 3.0 */ public class RefactoringStatusContext { /** * Returns the element that corresponds directly to this context, * or <code>null</code> if there is no corresponding element. * <p> * For example, the corresponding element of a context for a problem * detected in an <code>IResource</code> would the the resource itself. * <p> * * @return the corresponding element, or <code>null</code> if none */ public IAdaptable getCorrespondingElement() { return null; } } Consider the code from above and change the signature of getCorrespondingElement to return Object. If you press preview you get an refactoring error telling me that the import isn't used. Since we already detect this case we should remove the import. I know that this might introduce inconsistencies with other refactorings but getting this error message is even worse.
resolved fixed
905fdb3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T13:48:47Z
2004-01-09T14:53:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testImport07_out.java
package p; class A { void m() { } void use() { m(); } }
49,772
Bug 49772 Change method signature: remove unused imports [refactoring]
M6 package org.eclipse.jdt.internal.corext.refactoring.base; import org.eclipse.core.runtime.IAdaptable; /** * A <code>RefactoringStatusContext<code> can be used to annotate a * {@link RefactoringStatusEntry} with additional information * typically presented in the UI. * * @since 3.0 */ public class RefactoringStatusContext { /** * Returns the element that corresponds directly to this context, * or <code>null</code> if there is no corresponding element. * <p> * For example, the corresponding element of a context for a problem * detected in an <code>IResource</code> would the the resource itself. * <p> * * @return the corresponding element, or <code>null</code> if none */ public IAdaptable getCorrespondingElement() { return null; } } Consider the code from above and change the signature of getCorrespondingElement to return Object. If you press preview you get an refactoring error telling me that the import isn't used. Since we already detect this case we should remove the import. I know that this might introduce inconsistencies with other refactorings but getting this error message is even worse.
resolved fixed
905fdb3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T13:48:47Z
2004-01-09T14:53:20Z
org.eclipse.jdt.ui.tests.refactoring/test
49,772
Bug 49772 Change method signature: remove unused imports [refactoring]
M6 package org.eclipse.jdt.internal.corext.refactoring.base; import org.eclipse.core.runtime.IAdaptable; /** * A <code>RefactoringStatusContext<code> can be used to annotate a * {@link RefactoringStatusEntry} with additional information * typically presented in the UI. * * @since 3.0 */ public class RefactoringStatusContext { /** * Returns the element that corresponds directly to this context, * or <code>null</code> if there is no corresponding element. * <p> * For example, the corresponding element of a context for a problem * detected in an <code>IResource</code> would the the resource itself. * <p> * * @return the corresponding element, or <code>null</code> if none */ public IAdaptable getCorrespondingElement() { return null; } } Consider the code from above and change the signature of getCorrespondingElement to return Object. If you press preview you get an refactoring error telling me that the import isn't used. Since we already detect this case we should remove the import. I know that this might introduce inconsistencies with other refactorings but getting this error message is even worse.
resolved fixed
905fdb3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T13:48:47Z
2004-01-09T14:53:20Z
cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java
49,772
Bug 49772 Change method signature: remove unused imports [refactoring]
M6 package org.eclipse.jdt.internal.corext.refactoring.base; import org.eclipse.core.runtime.IAdaptable; /** * A <code>RefactoringStatusContext<code> can be used to annotate a * {@link RefactoringStatusEntry} with additional information * typically presented in the UI. * * @since 3.0 */ public class RefactoringStatusContext { /** * Returns the element that corresponds directly to this context, * or <code>null</code> if there is no corresponding element. * <p> * For example, the corresponding element of a context for a problem * detected in an <code>IResource</code> would the the resource itself. * <p> * * @return the corresponding element, or <code>null</code> if none */ public IAdaptable getCorrespondingElement() { return null; } } Consider the code from above and change the signature of getCorrespondingElement to return Object. If you press preview you get an refactoring error telling me that the import isn't used. Since we already detect this case we should remove the import. I know that this might introduce inconsistencies with other refactorings but getting this error message is even worse.
resolved fixed
905fdb3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T13:48:47Z
2004-01-09T14:53:20Z
org.eclipse.jdt.ui/core
49,772
Bug 49772 Change method signature: remove unused imports [refactoring]
M6 package org.eclipse.jdt.internal.corext.refactoring.base; import org.eclipse.core.runtime.IAdaptable; /** * A <code>RefactoringStatusContext<code> can be used to annotate a * {@link RefactoringStatusEntry} with additional information * typically presented in the UI. * * @since 3.0 */ public class RefactoringStatusContext { /** * Returns the element that corresponds directly to this context, * or <code>null</code> if there is no corresponding element. * <p> * For example, the corresponding element of a context for a problem * detected in an <code>IResource</code> would the the resource itself. * <p> * * @return the corresponding element, or <code>null</code> if none */ public IAdaptable getCorrespondingElement() { return null; } } Consider the code from above and change the signature of getCorrespondingElement to return Object. If you press preview you get an refactoring error telling me that the import isn't used. Since we already detect this case we should remove the import. I know that this might introduce inconsistencies with other refactorings but getting this error message is even worse.
resolved fixed
905fdb3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T13:48:47Z
2004-01-09T14:53:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureRefactoring.java
49,772
Bug 49772 Change method signature: remove unused imports [refactoring]
M6 package org.eclipse.jdt.internal.corext.refactoring.base; import org.eclipse.core.runtime.IAdaptable; /** * A <code>RefactoringStatusContext<code> can be used to annotate a * {@link RefactoringStatusEntry} with additional information * typically presented in the UI. * * @since 3.0 */ public class RefactoringStatusContext { /** * Returns the element that corresponds directly to this context, * or <code>null</code> if there is no corresponding element. * <p> * For example, the corresponding element of a context for a problem * detected in an <code>IResource</code> would the the resource itself. * <p> * * @return the corresponding element, or <code>null</code> if none */ public IAdaptable getCorrespondingElement() { return null; } } Consider the code from above and change the signature of getCorrespondingElement to return Object. If you press preview you get an refactoring error telling me that the import isn't used. Since we already detect this case we should remove the import. I know that this might introduce inconsistencies with other refactorings but getting this error message is even worse.
resolved fixed
905fdb3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T13:48:47Z
2004-01-09T14:53:20Z
org.eclipse.jdt.ui/core
49,772
Bug 49772 Change method signature: remove unused imports [refactoring]
M6 package org.eclipse.jdt.internal.corext.refactoring.base; import org.eclipse.core.runtime.IAdaptable; /** * A <code>RefactoringStatusContext<code> can be used to annotate a * {@link RefactoringStatusEntry} with additional information * typically presented in the UI. * * @since 3.0 */ public class RefactoringStatusContext { /** * Returns the element that corresponds directly to this context, * or <code>null</code> if there is no corresponding element. * <p> * For example, the corresponding element of a context for a problem * detected in an <code>IResource</code> would the the resource itself. * <p> * * @return the corresponding element, or <code>null</code> if none */ public IAdaptable getCorrespondingElement() { return null; } } Consider the code from above and change the signature of getCorrespondingElement to return Object. If you press preview you get an refactoring error telling me that the import isn't used. Since we already detect this case we should remove the import. I know that this might introduce inconsistencies with other refactorings but getting this error message is even worse.
resolved fixed
905fdb3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T13:48:47Z
2004-01-09T14:53:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/CompilationUnitRewrite.java
49,772
Bug 49772 Change method signature: remove unused imports [refactoring]
M6 package org.eclipse.jdt.internal.corext.refactoring.base; import org.eclipse.core.runtime.IAdaptable; /** * A <code>RefactoringStatusContext<code> can be used to annotate a * {@link RefactoringStatusEntry} with additional information * typically presented in the UI. * * @since 3.0 */ public class RefactoringStatusContext { /** * Returns the element that corresponds directly to this context, * or <code>null</code> if there is no corresponding element. * <p> * For example, the corresponding element of a context for a problem * detected in an <code>IResource</code> would the the resource itself. * <p> * * @return the corresponding element, or <code>null</code> if none */ public IAdaptable getCorrespondingElement() { return null; } } Consider the code from above and change the signature of getCorrespondingElement to return Object. If you press preview you get an refactoring error telling me that the import isn't used. Since we already detect this case we should remove the import. I know that this might introduce inconsistencies with other refactorings but getting this error message is even worse.
resolved fixed
905fdb3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T13:48:47Z
2004-01-09T14:53:20Z
org.eclipse.jdt.ui/core
49,772
Bug 49772 Change method signature: remove unused imports [refactoring]
M6 package org.eclipse.jdt.internal.corext.refactoring.base; import org.eclipse.core.runtime.IAdaptable; /** * A <code>RefactoringStatusContext<code> can be used to annotate a * {@link RefactoringStatusEntry} with additional information * typically presented in the UI. * * @since 3.0 */ public class RefactoringStatusContext { /** * Returns the element that corresponds directly to this context, * or <code>null</code> if there is no corresponding element. * <p> * For example, the corresponding element of a context for a problem * detected in an <code>IResource</code> would the the resource itself. * <p> * * @return the corresponding element, or <code>null</code> if none */ public IAdaptable getCorrespondingElement() { return null; } } Consider the code from above and change the signature of getCorrespondingElement to return Object. If you press preview you get an refactoring error telling me that the import isn't used. Since we already detect this case we should remove the import. I know that this might introduce inconsistencies with other refactorings but getting this error message is even worse.
resolved fixed
905fdb3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T13:48:47Z
2004-01-09T14:53:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ImportRemover.java
61,366
Bug 61366 Hierarchical (java) search results: Matches in parents not visible
I20040507 Steps: - Have a jdk with source - Search for java.util.Random -> There are matches in class files (in import statements) as well as matches in method bodies. In the hierarchical search results view mode, I cannot see whether there are search results in the class file or not. Two solutions come to mind: a) Render parent items witout matches "disabled" (grey-white icon, grey label) b) Show match count on parent labels also for count == 1
resolved fixed
5c70218
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T16:08:36Z
2004-05-07T08:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/PostfixLabelProvider.java
/******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.search; import java.text.MessageFormat; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.swt.graphics.Image; public class PostfixLabelProvider extends SearchLabelProvider { private ITreeContentProvider fContentProvider; public PostfixLabelProvider(JavaSearchResultPage page) { super(page, new AppearanceAwareLabelProvider(AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.P_COMPRESSED, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS)); fContentProvider= new LevelTreeContentProvider.FastJavaElementProvider(); } public Image getImage(Object element) { Image image= getLabelProvider().getImage(element); if (image != null) return image; return getParticipantImage(element); } public String getText(Object element) { ITreeContentProvider provider= (ITreeContentProvider) fPage.getViewer().getContentProvider(); Object visibleParent= provider.getParent(element); Object realParent= fContentProvider.getParent(element); Object lastElement= element; StringBuffer postfix= new StringBuffer(); while (realParent != null && !(realParent instanceof IJavaModel) && !realParent.equals(visibleParent)) { if (!isSameInformation(realParent, lastElement)) { postfix.append(" - "); //$NON-NLS-1$ postfix.append(internalGetText(realParent)); } lastElement= realParent; realParent= fContentProvider.getParent(realParent); } int matchCount= fPage.getDisplayedMatchCount(element); String text=internalGetText(element); if (matchCount < 2) { String label= getSingularLabel(element); return MessageFormat.format(label, new String[] { text, postfix.toString() }); } String label= getPluralLabel(element); return MessageFormat.format(label, new Object[] { text, new Integer(matchCount), postfix.toString() }); } private String getSingularLabel(Object element) { if (hasPotentialMatches(element)) return SearchMessages.getString("PostfixLabelProvider.potential_singluar"); //$NON-NLS-1$ return SearchMessages.getString("PostfixLabelProvider.exact_singular"); //$NON-NLS-1$ } private String getPluralLabel(Object element) { if (hasPotentialMatches(element)) return SearchMessages.getString("PostfixLabelProvider.potential_plural"); //$NON-NLS-1$ return SearchMessages.getString("PostfixLabelProvider.exact_plural"); //$NON-NLS-1$ } private String internalGetText(Object element) { String text= getLabelProvider().getText(element); if (text != null && !"".equals(text)) //$NON-NLS-1$ return text; return getParticipantText(element); } private boolean isSameInformation(Object realParent, Object lastElement) { if (lastElement instanceof IType) { IType type= (IType)lastElement; if (realParent instanceof IClassFile) { if (type.getClassFile().equals(realParent)) return true; } else if (realParent instanceof ICompilationUnit) { if (type.getCompilationUnit().equals(realParent)) return true; } } return false; } }
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
org.eclipse.jdt.ui/core
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/CopyRefactoring.java
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
org.eclipse.jdt.ui/core
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/IReorgDestinationValidator.java
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
org.eclipse.jdt.ui/core
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/IReorgPolicy.java
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
org.eclipse.jdt.ui/core
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/JavaMoveProcessor.java
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
org.eclipse.jdt.ui/core
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/ReorgPolicyFactory.java
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
org.eclipse.jdt.ui/ui
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/reorg/DestinationContentProvider.java
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
org.eclipse.jdt.ui/ui
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/reorg/ReorgCopyWizard.java
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
org.eclipse.jdt.ui/ui
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/reorg/ReorgMoveWizard.java
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
org.eclipse.jdt.ui/ui
48,970
Bug 48970 Move dialog shows too many possible destinations
I20031216-2000 - Select a CU in the Package Explorer - Refactoring > Move... - observe: can select way too many targets (e.g. import declarations, methods, ...). If I select a method, the refactoring silently changes the target to be the enclosing package! - expected: only applicable targets are shown in the tree
resolved fixed
fa8f39e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:06:58Z
2003-12-17T11:20:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/reorg/ReorgUserInputPage.java
61,176
Bug 61176 Need better dialog when change type isn't supported
I20040505 - run change method signature on the return type of foo: public void virtualMethod() { class Local { String foo() { return null; } } } The dialog that comes up tells !ChangeTypeAction.exception!. First there seems to be an NLS error. The String isn't NLS correctly. Second, this isn't an exception. The dialog should say something like: The operation isn't supported inside local types.
resolved fixed
51a5e0b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:30:13Z
2004-05-06T07:53:20Z
org.eclipse.jdt.ui/core
61,176
Bug 61176 Need better dialog when change type isn't supported
I20040505 - run change method signature on the return type of foo: public void virtualMethod() { class Local { String foo() { return null; } } } The dialog that comes up tells !ChangeTypeAction.exception!. First there seems to be an NLS error. The String isn't NLS correctly. Second, this isn't an exception. The dialog should say something like: The operation isn't supported inside local types.
resolved fixed
51a5e0b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T17:30:13Z
2004-05-06T07:53:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeTypeRefactoring.java
61,759
Bug 61759 [typing] Smart semicolon does not work at end of string literal
I20040506 0. smart semicolon is on, smart typing mode 1. have this code: String s= "asdfasdf<caret>" 2. press SEMICOLON -> expected: semicolon gets inserted after the closing quotation mark -> real: the semicolon is inserted at the caret position -> note that it works if the caret position is not before the closing quotation mark.
resolved fixed
c828717
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-11T18:24:14Z
2004-05-11T15:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/SmartSemicolonAutoEditStrategy.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.java; import java.util.Arrays; import org.eclipse.text.edits.DeleteEdit; import org.eclipse.text.edits.MalformedTreeException; import org.eclipse.text.edits.ReplaceEdit; import org.eclipse.text.edits.TextEdit; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IAutoEditStrategy; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.text.TextUtilities; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.texteditor.ITextEditorExtension2; import org.eclipse.ui.texteditor.ITextEditorExtension3; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.core.Assert; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.SmartBackspaceManager; import org.eclipse.jdt.internal.ui.text.SmartBackspaceManager.UndoSpec; /** * Modifies <code>DocumentCommand</code>s inserting semicolons and opening braces to place them * smartly, i.e. moving them to the end of a line if that is what the user expects. * * <p>In practice, semicolons and braces (and the caret) are moved to the end of the line if they are typed * anywhere except for semicolons in a <code>for</code> statements definition. If the line contains a semicolon * or brace after the current caret position, the cursor is moved after it.</p> * * @see org.eclipse.jface.text.DocumentCommand * @since 3.0 */ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { /** String representation of a semicolon. */ private static final String SEMICOLON= ";"; //$NON-NLS-1$ /** Char representation of a semicolon. */ private static final char SEMICHAR= ';'; /** String represenattion of a opening brace. */ private static final String BRACE= "{"; //$NON-NLS-1$ /** Char representation of a opening brace */ private static final char BRACECHAR= '{'; private char fCharacter; private String fPartitioning; /** * Creates a new SmartSemicolonAutoEditStrategy. * * @param partitioning the document partitioning */ public SmartSemicolonAutoEditStrategy(String partitioning) { fPartitioning= partitioning; } /* * @see org.eclipse.jface.text.IAutoEditStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand) */ public void customizeDocumentCommand(IDocument document, DocumentCommand command) { // 0: early pruning // also customize if <code>doit</code> is false (so it works in code completion situations) // if (!command.doit) // return; if (command.text == null) return; if (command.text.equals(SEMICOLON)) fCharacter= SEMICHAR; else if (command.text.equals(BRACE)) fCharacter= BRACECHAR; else return; IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); if (fCharacter == SEMICHAR && !store.getBoolean(PreferenceConstants.EDITOR_SMART_SEMICOLON)) return; if (fCharacter == BRACECHAR && !store.getBoolean(PreferenceConstants.EDITOR_SMART_OPENING_BRACE)) return; IWorkbenchPage page= JavaPlugin.getActivePage(); if (page == null) return; IEditorPart part= page.getActiveEditor(); if (!(part instanceof CompilationUnitEditor)) return; CompilationUnitEditor editor= (CompilationUnitEditor)part; if (editor.getInsertMode() != ITextEditorExtension3.SMART_INSERT || !editor.isEditable()) return; ITextEditorExtension2 extension= (ITextEditorExtension2)editor.getAdapter(ITextEditorExtension2.class); if (extension != null && !extension.validateEditorInputState()) return; if (isMultilineSelection(document, command)) return; // 1: find concerned line / position in java code, location in statement int pos= command.offset; ITextSelection line; try { IRegion l= document.getLineInformationOfOffset(pos); line= new TextSelection(document, l.getOffset(), l.getLength()); } catch (BadLocationException e) { return; } // 2: choose action based on findings (is for-Statement?) // for now: compute the best position to insert the new character int positionInLine= computeCharacterPosition(document, line, pos - line.getOffset(), fCharacter, fPartitioning); int position= positionInLine + line.getOffset(); // never position before the current position! if (position < pos) return; // never double already existing content if (alreadyPresent(document, fCharacter, position)) return; // don't do special processing if what we do is actually the normal behaviour String insertion= adjustSpacing(document, position, fCharacter); if (command.offset == position && insertion.equals(command.text)) return; try { final SmartBackspaceManager manager= (SmartBackspaceManager) editor.getAdapter(SmartBackspaceManager.class); if (manager != null && JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_BACKSPACE)) { TextEdit e1= new ReplaceEdit(command.offset, command.text.length(), document.get(command.offset, command.length)); UndoSpec s1= new UndoSpec(command.offset + command.text.length(), new Region(command.offset, 0), new TextEdit[] {e1}, 0, null); DeleteEdit smart= new DeleteEdit(position, insertion.length()); ReplaceEdit raw= new ReplaceEdit(command.offset, command.length, command.text); UndoSpec s2= new UndoSpec(position + insertion.length(), new Region(command.offset + command.text.length(), 0), new TextEdit[] {smart, raw}, 2, s1); manager.register(s2); } // 3: modify command command.offset= position; command.length= 0; command.caretOffset= position; command.text= insertion; command.doit= true; command.owner= null; } catch (MalformedTreeException e) { JavaPlugin.log(e); } catch (BadLocationException e) { JavaPlugin.log(e); } } /** * Returns <code>true</code> if the document command is applied on a multi * line selection, <code>false</code> otherwise. * * @param document the document * @param command the command * @return <code>true</code> if <code>command</code> is a multiline command */ private boolean isMultilineSelection(IDocument document, DocumentCommand command) { try { return document.getNumberOfLines(command.offset, command.length) > 1; } catch (BadLocationException e) { // ignore return false; } } /** * Adds a space before a brace if it is inserted after a parenthesis, equal sign, or one * of the keywords <code>try, else, do</code>. * * @param document the document we are working on * @param position the insert position of <code>character</code> * @param character the character to be inserted * @return a <code>String</code> consisting of <code>character</code> plus any additional spacing */ private String adjustSpacing(IDocument doc, int position, char character) { if (character == BRACECHAR) { if (position > 0 && position <= doc.getLength()) { int pos= position - 1; if (looksLike(doc, pos, ")") //$NON-NLS-1$ || looksLike(doc, pos, "=") //$NON-NLS-1$ || looksLike(doc, pos, "]") //$NON-NLS-1$ || looksLike(doc, pos, "try") //$NON-NLS-1$ || looksLike(doc, pos, "else") //$NON-NLS-1$ || looksLike(doc, pos, "synchronized") //$NON-NLS-1$ || looksLike(doc, pos, "static") //$NON-NLS-1$ || looksLike(doc, pos, "finally") //$NON-NLS-1$ || looksLike(doc, pos, "do")) //$NON-NLS-1$ return new String(new char[] { ' ', character }); } } return new String(new char[] { character }); } /** * Checks whether a character to be inserted is already present at the insert location (perhaps * separated by some whitespace from <code>position</code>. * * @param document the document we are working on * @param position the insert position of <code>ch</code> * @param character the character to be inserted * @return <code>true</code> if <code>ch</code> is already present at <code>location</code>, <code>false</code> otherwise */ private boolean alreadyPresent(IDocument document, char ch, int position) { int pos= firstNonWhitespaceForward(document, position, fPartitioning, document.getLength()); try { if (pos != -1 && document.getChar(pos) == ch) return true; } catch (BadLocationException e) { } return false; } /** * Computes the next insert position of the given character in the current line. * * @param document the document we are working on * @param line the line where the change is being made * @param offset the position of the caret in the line when <code>character</code> was typed * @param character the character to look for * @param partitioning the document partitioning * @return the position where <code>character</code> should be inserted / replaced */ protected static int computeCharacterPosition(IDocument document, ITextSelection line, int offset, char character, String partitioning) { String text= line.getText(); if (text == null) return 0; int insertPos; if (character == BRACECHAR) { insertPos= computeArrayInitializationPos(document, line, offset, partitioning); if (insertPos == -1) { insertPos= computeAfterTryDoElse(document, line, offset); } if (insertPos == -1) { insertPos= computeAfterParenthesis(document, line, offset, partitioning); } } else if (character == SEMICHAR) { if (isForStatement(text, offset)) { insertPos= -1; // don't do anything in for statements, as semis are vital part of these } else { int nextPartitionPos= nextPartitionOrLineEnd(document, line, offset, partitioning); insertPos= startOfWhitespaceBeforeOffset(text, nextPartitionPos); // if there is a semi present, return its location as alreadyPresent() will take it out this way. if (insertPos > 0 && text.charAt(insertPos - 1) == character) insertPos= insertPos - 1; } } else { Assert.isTrue(false); return -1; } return insertPos; } /** * Computes an insert position for an opening brace if <code>offset</code> maps to a position in * <code>document</code> that looks like being the RHS of an assignment or like an array definition. * * @param document the document being modified * @param line the current line under investigation * @param offset the offset of the caret position, relative to the line start. * @param partitioning the document partitioning * @return an insert position relative to the line start if <code>line</code> looks like being an array initialization at <code>offset</code>, -1 otherwise */ private static int computeArrayInitializationPos(IDocument document, ITextSelection line, int offset, String partitioning) { // search backward while WS, find = (not != <= >= ==) in default partition int pos= offset + line.getOffset(); if (pos == 0) return -1; int p= firstNonWhitespaceBackward(document, pos - 1, partitioning, -1); if (p == -1) return -1; try { char ch= document.getChar(p); if (ch != '=' && ch != ']') return -1; if (p == 0) return offset; p= firstNonWhitespaceBackward(document, p - 1, partitioning, -1); if (p == -1) return -1; ch= document.getChar(p); if (Character.isJavaIdentifierPart(ch) || ch == ']' || ch == '[') return offset; } catch (BadLocationException e) { } return -1; } /** * Computes an insert position for an opening brace if <code>offset</code> maps to a position in * <code>document</code> involving a keyword taking a block after it. These are: <code>try</code>, * <code>do</code>, <code>synchronized</code>, <code>static</code>, <code>finally</code>, or <code>else</code>. * * @param document the document being modified * @param line the current line under investigation * @param offset the offset of the caret position, relative to the line start. * @return an insert position relative to the line start if <code>line</code> contains one of the above keywords at or before <code>offset</code>, -1 otherwise */ private static int computeAfterTryDoElse(IDocument doc, ITextSelection line, int offset) { // search backward while WS, find 'try', 'do', 'else' in default partition int p= offset + line.getOffset(); p= firstWhitespaceToRight(doc, p); if (p == -1) return -1; p--; if (looksLike(doc, p, "try") //$NON-NLS-1$ || looksLike(doc, p, "do") //$NON-NLS-1$ || looksLike(doc, p, "synchronized") //$NON-NLS-1$ || looksLike(doc, p, "static") //$NON-NLS-1$ || looksLike(doc, p, "finally") //$NON-NLS-1$ || looksLike(doc, p, "else")) //$NON-NLS-1$ return p + 1 - line.getOffset(); return -1; } /** * Computes an insert position for an opening brace if <code>offset</code> maps to a position in * <code>document</code> with a expression in parenthesis that will take a block after the closing parenthesis. * * @param document the document being modified * @param line the current line under investigation * @param offset the offset of the caret position, relative to the line start. * @param partitioning the document partitioning * @return an insert position relative to the line start if <code>line</code> contains a parenthesized expression that can be followed by a block, -1 otherwise */ private static int computeAfterParenthesis(IDocument document, ITextSelection line, int offset, String partitioning) { // find the opening parenthesis for every closing parenthesis on the current line after offset // return the position behind the closing parenthesis if it looks like a method declaration // or an expression for an if, while, for, catch statement int pos= offset + line.getOffset(); int length= line.getOffset() + line.getLength(); int scanTo= scanForward(document, pos, partitioning, length, '}'); if (scanTo == -1) scanTo= length; int closingParen= findClosingParenToLeft(document, pos, partitioning) - 1; while (true) { int startScan= closingParen + 1; closingParen= scanForward(document, startScan, partitioning, scanTo, ')'); if (closingParen == -1) break; int openingParen= findOpeningParenMatch(document, closingParen, partitioning); // no way an expression at the beginning of the document can mean anything if (openingParen < 1) break; // only select insert positions for parenthesis currently embracing the caret if (openingParen > pos) continue; if (looksLikeAnonymousClassDef(document, openingParen - 1, partitioning)) return closingParen + 1 - line.getOffset(); if (looksLikeIfWhileForCatch(document, openingParen - 1, partitioning)) return closingParen + 1 - line.getOffset(); if (looksLikeMethodDecl(document, openingParen - 1, partitioning)) return closingParen + 1 - line.getOffset(); } return -1; } /** * Finds a closing parenthesis to the left of <code>position</code> in document, where that parenthesis is only * separated by whitespace from <code>position</code>. If no such parenthesis can be found, <code>position</code> is returned. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param partitioning the document partitioning * @return the position of a closing parenthesis left to <code>position</code> separated only by whitespace, or <code>position</code> if no parenthesis can be found */ private static int findClosingParenToLeft(IDocument document, int position, String partitioning) { final char CLOSING_PAREN= ')'; try { if (position < 1) return position; int nonWS= firstNonWhitespaceBackward(document, position - 1, partitioning, -1); if (nonWS != -1 && document.getChar(nonWS) == CLOSING_PAREN) return nonWS; } catch (BadLocationException e1) { } return position; } /** * Finds the first whitespace character position to the right of (and including) <code>position</code>. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @return the position of a whitespace character greater or equal than <code>position</code> separated only by whitespace, or -1 if none found */ private static int firstWhitespaceToRight(IDocument document, int position) { int length= document.getLength(); Assert.isTrue(position >= 0); Assert.isTrue(position <= length); try { while (position < length) { char ch= document.getChar(position); if (Character.isWhitespace(ch)) return position; position++; } return position; } catch (BadLocationException e) { } return -1; } /** * Finds the highest position in <code>document</code> such that the position is &lt;= <code>position</code> * and &gt; <code>bound</code> and <code>Character.isWhitespace(document.getChar(pos))</code> evaluates to <code>false</code> * and the position is in the default partition. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param partitioning the document partitioning * @param bound the first position in <code>document</code> to not consider any more, with <code>bound</code> &gt; <code>position</code> * @return the highest position of one element in <code>chars</code> in [<code>position</code>, <code>scanTo</code>) that resides in a Java partition, or <code>-1</code> if none can be found */ private static int firstNonWhitespaceBackward(IDocument document, int position, String partitioning, int bound) { Assert.isTrue(position < document.getLength()); Assert.isTrue(bound >= -1); try { while (position > bound) { char ch= document.getChar(position); if (!Character.isWhitespace(ch) && isDefaultPartition(document, position, partitioning)) return position; position--; } } catch (BadLocationException e) { } return -1; } /** * Finds the smallest position in <code>document</code> such that the position is &gt;= <code>position</code> * and &lt; <code>bound</code> and <code>Character.isWhitespace(document.getChar(pos))</code> evaluates to <code>false</code> * and the position is in the default partition. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param partitioning the document partitioning * @param bound the first position in <code>document</code> to not consider any more, with <code>bound</code> &gt; <code>position</code> * @return the smallest position of one element in <code>chars</code> in [<code>position</code>, <code>scanTo</code>) that resides in a Java partition, or <code>-1</code> if none can be found */ private static int firstNonWhitespaceForward(IDocument document, int position, String partitioning, int bound) { Assert.isTrue(position >= 0); Assert.isTrue(bound <= document.getLength()); try { while (position < bound) { char ch= document.getChar(position); if (!Character.isWhitespace(ch) && isDefaultPartition(document, position, partitioning)) return position; position++; } } catch (BadLocationException e) { } return -1; } /** * Finds the highest position in <code>document</code> such that the position is &lt;= <code>position</code> * and &gt; <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code> for at least one * ch in <code>chars</code> and the position is in the default partition. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param partitioning the document partitioning * @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> &gt; <code>position</code> * @param chars an array of <code>char</code> to search for * @return the highest position of one element in <code>chars</code> in (<code>bound</code>, <code>position</code>] that resides in a Java partition, or <code>-1</code> if none can be found */ private static int scanBackward(IDocument document, int position, String partitioning, int bound, char[] chars) { Assert.isTrue(bound >= -1); Assert.isTrue(position < document.getLength() ); Arrays.sort(chars); try { while (position > bound) { if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 && isDefaultPartition(document, position, partitioning)) return position; position--; } } catch (BadLocationException e) { } return -1; } // /** // * Finds the highest position in <code>document</code> such that the position is &lt;= <code>position</code> // * and &gt; <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code> // * and the position is in the default partition. // * // * @param document the document being modified // * @param position the first character position in <code>document</code> to be considered // * @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> &gt; <code>position</code> // * @param chars an array of <code>char</code> to search for // * @return the highest position of one element in <code>chars</code> in [<code>position</code>, <code>scanTo</code>) that resides in a Java partition, or <code>-1</code> if none can be found // */ // private static int scanBackward(IDocument document, int position, int bound, char ch) { // return scanBackward(document, position, bound, new char[] {ch}); // } // /** * Finds the lowest position in <code>document</code> such that the position is &gt;= <code>position</code> * and &lt; <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code> for at least one * ch in <code>chars</code> and the position is in the default partition. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param partitioning the document partitioning * @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> &gt; <code>position</code> * @param chars an array of <code>char</code> to search for * @return the lowest position of one element in <code>chars</code> in [<code>position</code>, <code>bound</code>) that resides in a Java partition, or <code>-1</code> if none can be found */ private static int scanForward(IDocument document, int position, String partitioning, int bound, char[] chars) { Assert.isTrue(position >= 0); Assert.isTrue(bound <= document.getLength()); Arrays.sort(chars); try { while (position < bound) { if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 && isDefaultPartition(document, position, partitioning)) return position; position++; } } catch (BadLocationException e) { } return -1; } /** * Finds the lowest position in <code>document</code> such that the position is &gt;= <code>position</code> * and &lt; <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code> * and the position is in the default partition. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param partitioning the document partitioning * @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> &gt; <code>position</code> * @param chars an array of <code>char</code> to search for * @return the lowest position of one element in <code>chars</code> in [<code>position</code>, <code>bound</code>) that resides in a Java partition, or <code>-1</code> if none can be found */ private static int scanForward(IDocument document, int position, String partitioning, int bound, char ch) { return scanForward(document, position, partitioning, bound, new char[] {ch}); } /** * Checks whether the content of <code>document</code> in the range (<code>offset</code>, <code>length</code>) * contains the <code>new</code> keyword. * * @param document the document being modified * @param offset the first character position in <code>document</code> to be considered * @param length the length of the character range to be considered * @param partitioning the document partitioning * @return <code>true</code> if the specified character range contains a <code>new</code> keyword, <code>false</code> otherwise. */ private static boolean isNewMatch(IDocument document, int offset, int length, String partitioning) { Assert.isTrue(length >= 0); Assert.isTrue(offset >= 0); Assert.isTrue(offset + length < document.getLength() + 1); try { String text= document.get(offset, length); int pos= text.indexOf("new"); //$NON-NLS-1$ while (pos != -1 && !isDefaultPartition(document, pos + offset, partitioning)) pos= text.indexOf("new", pos + 2); //$NON-NLS-1$ if (pos < 0) return false; if (pos != 0 && Character.isJavaIdentifierPart(text.charAt(pos - 1))) return false; if (pos + 3 < length && Character.isJavaIdentifierPart(text.charAt(pos + 3))) return false; return true; } catch (BadLocationException e) { } return false; } /** * Checks whether the content of <code>document</code> at <code>position</code> looks like an * anonymous class definition. <code>position</code> must be to the left of the opening * parenthesis of the definition's parameter list. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param partitioning the document partitioning * @return <code>true</code> if the content of <code>document</code> looks like an anonymous class definition, <code>false</code> otherwise */ private static boolean looksLikeAnonymousClassDef(IDocument document, int position, String partitioning) { int previousCommaOrParen= scanBackward(document, position - 1, partitioning, -1, new char[] {',', '('}); if (previousCommaOrParen == -1 || position < previousCommaOrParen + 5) // 2 for borders, 3 for "new" return false; if (isNewMatch(document, previousCommaOrParen + 1, position - previousCommaOrParen - 2, partitioning)) return true; return false; } /** * Checks whether <code>position</code> resides in a default (Java) partition of <code>document</code>. * * @param document the document being modified * @param position the position to be checked * @param partitioning the document partitioning * @return <code>true</code> if <code>position</code> is in the default partition of <code>document</code>, <code>false</code> otherwise */ private static boolean isDefaultPartition(IDocument document, int position, String partitioning) { Assert.isTrue(position >= 0); Assert.isTrue(position <= document.getLength()); try { // don't use getPartition2 since we're interested in the scanned character's partition ITypedRegion region= TextUtilities.getPartition(document, partitioning, position, false); return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE); } catch (BadLocationException e) { } return false; } /** * Finds the position of the parenthesis matching the closing parenthesis at <code>position</code>. * * @param document the document being modified * @param position the position in <code>document</code> of a closing parenthesis * @param partitioning the document partitioning * @return the position in <code>document</code> of the matching parenthesis, or -1 if none can be found */ private static int findOpeningParenMatch(IDocument document, int position, String partitioning) { final char CLOSING_PAREN= ')'; final char OPENING_PAREN= '('; Assert.isTrue(position < document.getLength()); Assert.isTrue(position >= 0); Assert.isTrue(isDefaultPartition(document, position, partitioning)); try { Assert.isTrue(document.getChar(position) == CLOSING_PAREN); int depth= 1; while (true) { position= scanBackward(document, position - 1, partitioning, -1, new char[] {CLOSING_PAREN, OPENING_PAREN}); if (position == -1) return -1; if (document.getChar(position) == CLOSING_PAREN) depth++; else depth--; if (depth == 0) return position; } } catch (BadLocationException e) { return -1; } } /** * Checks whether, to the left of <code>position</code> and separated only by whitespace, * <code>document</code> contains a keyword taking a parameter list and a block after it. * These are: <code>if</code>, <code>while</code>, <code>catch</code>, <code>for</code>, <code>synchronized</code>, <code>switch</code>. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param partitioning the document partitioning * @return <code>true</code> if <code>document</code> contains any of the above keywords to the left of <code>position</code>, <code>false</code> otherwise */ private static boolean looksLikeIfWhileForCatch(IDocument document, int position, String partitioning) { position= firstNonWhitespaceBackward(document, position, partitioning, -1); if (position == -1) return false; return looksLike(document, position, "if") //$NON-NLS-1$ || looksLike(document, position, "while") //$NON-NLS-1$ || looksLike(document, position, "catch") //$NON-NLS-1$ || looksLike(document, position, "synchronized") //$NON-NLS-1$ || looksLike(document, position, "switch") //$NON-NLS-1$ || looksLike(document, position, "for"); //$NON-NLS-1$ } /** * Checks whether code>document</code> contains the <code>String</code> <code>like</code> such * that its last character is at <code>position</code>. If <code>like</code> starts with a * identifier part (as determined by {@link Character#isJavaIdentifier(char)}), it is also made * sure that <code>like</code> is preceded by some non-identifier character or stands at the * document start. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param like the <code>String</code> to look for. * @return <code>true</code> if <code>document</code> contains <code>like</code> such that it ends at <code>position</code>, <code>false</code> otherwise */ private static boolean looksLike(IDocument document, int position, String like) { int length= like.length(); if (position < length - 1) return false; try { if (!like.equals(document.get(position - length + 1, length))) return false; if (position >= length && Character.isJavaIdentifierPart(like.charAt(0)) && Character.isJavaIdentifierPart(document.getChar(position - length))) return false; } catch (BadLocationException e) { return false; } return true; } /** * Checks whether the content of <code>document</code> at <code>position</code> looks like a * method declaration header (i.e. only the return type and method name). <code>position</code> * must be just left of the opening parenthesis of the parameter list. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param partitioning the document partitioning * @return <code>true</code> if the content of <code>document</code> looks like a method definition, <code>false</code> otherwise */ private static boolean looksLikeMethodDecl(IDocument document, int position, String partitioning) { // method name position= eatIdentToLeft(document, position, partitioning); if (position < 1) return false; position= eatBrackets(document, position - 1, partitioning); if (position < 1) return false; position= eatIdentToLeft(document, position - 1, partitioning); return position != -1; } /** * From <code>position</code> to the left, eats any whitespace and then a pair of brackets * as used to declare an array return type like <pre>String [ ]</pre>. * The return value is either the position of the opening bracket or <code>position</code> if no * pair of brackets can be parsed. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param partitioning the document partitioning * @return the smallest character position of bracket pair or <code>position</code> */ private static int eatBrackets(IDocument document, int position, String partitioning) { // accept array return type int pos= firstNonWhitespaceBackward(document, position, partitioning, -1); try { if (pos > 1 && document.getChar(pos) == ']') { pos= firstNonWhitespaceBackward(document, pos - 1, partitioning, -1); if (pos > 0 && document.getChar(pos) == '[') return pos; } } catch (BadLocationException e) { // won't happen } return position; } /** * From <code>position</code> to the left, eats any whitespace and the first identifier, returning * the position of the first identifier character (in normal read order). * <p>When called on a document with content <code>" some string "</code> and positionition 13, the * return value will be 6 (the first letter in <code>string</code>). * </p> * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param partitioning the document partitioning * @return the smallest character position of an identifier or -1 if none can be found; always &lt;= <code>position</code> */ private static int eatIdentToLeft(IDocument document, int position, String partitioning) { if (position < 0) return -1; Assert.isTrue(position < document.getLength()); int p= firstNonWhitespaceBackward(document, position, partitioning, -1); if (p == -1) return -1; try { while (p >= 0) { char ch= document.getChar(p); if (Character.isJavaIdentifierPart(ch)) { p--; continue; } // length must be > 0 if (Character.isWhitespace(ch) && p != position) return p + 1; else return -1; } // start of document reached return 0; } catch (BadLocationException e) { } return -1; } /** * Returns a position in the first java partition after the last non-empty and non-comment partition. * There is no non-whitespace from the returned position to the end of the partition it is contained in. * * @param document the document being modified * @param line the line under investigation * @param offset the caret offset into <code>line</code> * @param partitioning the document partitioning * @return the position of the next Java partition, or the end of <code>line</code> */ private static int nextPartitionOrLineEnd(IDocument document, ITextSelection line, int offset, String partitioning) { // run relative to document final int docOffset= offset + line.getOffset(); final int eol= line.getOffset() + line.getLength(); int nextPartitionPos= eol; // init with line end int validPosition= docOffset; try { ITypedRegion partition= TextUtilities.getPartition(document, partitioning, nextPartitionPos, true); validPosition= getValidPositionForPartition(document, partition, eol); while (validPosition == -1) { nextPartitionPos= partition.getOffset() - 1; if (nextPartitionPos <= docOffset) { validPosition= docOffset; break; } partition= TextUtilities.getPartition(document, partitioning, nextPartitionPos, false); validPosition= getValidPositionForPartition(document, partition, eol); } } catch (BadLocationException e) { } validPosition= Math.max(validPosition, docOffset); // make relative to line validPosition -= line.getOffset(); return validPosition; } /** * Returns a valid insert location (except for whitespace) in <code>partition</code> or -1 if * there is no valid insert location. * An valid insert location is right after any java string or character partition, or at the end * of a java default partition, but never behind <code>maxOffset</code>. Comment partitions or * empty java partitions do never yield valid insert positions. * * @param doc the document being modified * @param partition the current partition * @param maxOffset the maximum offset to consider * @return a valid insert location in <code>partition</code>, or -1 if there is no valid insert location */ private static int getValidPositionForPartition(IDocument doc, ITypedRegion partition, int maxOffset) { final int INVALID= -1; if (IJavaPartitions.JAVA_DOC.equals(partition.getType())) return INVALID; if (IJavaPartitions.JAVA_MULTI_LINE_COMMENT.equals(partition.getType())) return INVALID; if (IJavaPartitions.JAVA_SINGLE_LINE_COMMENT.equals(partition.getType())) return INVALID; int endOffset= Math.min(maxOffset, partition.getOffset() + partition.getLength()); if (IJavaPartitions.JAVA_CHARACTER.equals(partition.getType())) return endOffset; if (IJavaPartitions.JAVA_STRING.equals(partition.getType())) return endOffset; if (IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())) { try { if (doc.get(partition.getOffset(), endOffset - partition.getOffset()).trim().length() == 0) return INVALID; else return endOffset; } catch (BadLocationException e) { return INVALID; } } // default: we don't know anything about the partition - assume valid return endOffset; } /** * Determines whether the current line contains a for statement. * Algorithm: any "for" word in the line is a positive, "for" contained in a string literal will * produce a false positive. * * @param line the line where the change is being made * @param offset the position of the caret * @return <code>true</code> if <code>line</code> contains <code>for</code>, <code>false</code> otherwise */ private static boolean isForStatement(String line, int offset) { /* searching for (^|\s)for(\s|$) */ int forPos= line.indexOf("for"); //$NON-NLS-1$ if (forPos != -1) { if ((forPos == 0 || !Character.isJavaIdentifierPart(line.charAt(forPos - 1))) && (line.length() == forPos + 3 || !Character.isJavaIdentifierPart(line.charAt(forPos + 3)))) return true; } return false; } /** * Returns the position in <code>text</code> after which there comes only whitespace, up to * <code>offset</code>. * * @param text the text being searched * @param offset the maximum offset to search for * @return the smallest value <code>v</code> such that <code>text.substring(v, offset).trim() == 0</code> */ private static int startOfWhitespaceBeforeOffset(String text, int offset) { int i= Math.min(offset, text.length()); for (; i >= 1; i--) { if (!Character.isWhitespace(text.charAt(i - 1))) break; } return i; } }
48,504
Bug 48504 Exception while introducing factory [refactoring]
I20031203 with your latest patch: try introducing a factory method for constructor A in class B. Code I used is: public class A { { field= 10; } public A() { } private int field; static class XX extends A { public void foo() { bar(); } public void bar() { } } public void foo(int y) { Runnable runnable= new Runnable() { private int field; public void run() { { A a= null; } } }; } public String foo(String ss) { A a= new A(); return ss; } } /* * Created on Nov 12, 2003 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ /** * @author dbaeumer * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class B { private static interface I { public void foo(); } private static class CC implements I { public void foo() { } } public void foo() { I i= new I() { public void foo() { } public void bar() { foo(); } }; CC c= new CC() {}; B b; } public void bar() { class X { public void baz() { } } class Y extends X { public void baz() { } } } } exception is: 'org.eclipse.jdt.core.dom.SimpleName('XX')' in compilation unit 'A.java'] at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.core.runtime.CoreException.<init>(CoreException.java:35) at org.eclipse.jdt.core.JavaModelException.<init> (JavaModelException.java:67) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ge tCtorCallAt(IntroduceFactoryRefactoring.java:857) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.re placeConstructorCalls(IntroduceFactoryRefactoring.java:788) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ad dAllChangesFor(IntroduceFactoryRefactoring.java:720) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.cr eateChange(IntroduceFactoryRefactoring.java:902) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
resolved fixed
7440e94
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-12T07:55:45Z
2003-12-11T16:26:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceFactory/Bugzilla/48504/p1/A.java
48,504
Bug 48504 Exception while introducing factory [refactoring]
I20031203 with your latest patch: try introducing a factory method for constructor A in class B. Code I used is: public class A { { field= 10; } public A() { } private int field; static class XX extends A { public void foo() { bar(); } public void bar() { } } public void foo(int y) { Runnable runnable= new Runnable() { private int field; public void run() { { A a= null; } } }; } public String foo(String ss) { A a= new A(); return ss; } } /* * Created on Nov 12, 2003 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ /** * @author dbaeumer * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class B { private static interface I { public void foo(); } private static class CC implements I { public void foo() { } } public void foo() { I i= new I() { public void foo() { } public void bar() { foo(); } }; CC c= new CC() {}; B b; } public void bar() { class X { public void baz() { } } class Y extends X { public void baz() { } } } } exception is: 'org.eclipse.jdt.core.dom.SimpleName('XX')' in compilation unit 'A.java'] at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.core.runtime.CoreException.<init>(CoreException.java:35) at org.eclipse.jdt.core.JavaModelException.<init> (JavaModelException.java:67) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ge tCtorCallAt(IntroduceFactoryRefactoring.java:857) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.re placeConstructorCalls(IntroduceFactoryRefactoring.java:788) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ad dAllChangesFor(IntroduceFactoryRefactoring.java:720) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.cr eateChange(IntroduceFactoryRefactoring.java:902) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
resolved fixed
7440e94
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-12T07:55:45Z
2003-12-11T16:26:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceFactory/Bugzilla/48504/p1/A_out.java
48,504
Bug 48504 Exception while introducing factory [refactoring]
I20031203 with your latest patch: try introducing a factory method for constructor A in class B. Code I used is: public class A { { field= 10; } public A() { } private int field; static class XX extends A { public void foo() { bar(); } public void bar() { } } public void foo(int y) { Runnable runnable= new Runnable() { private int field; public void run() { { A a= null; } } }; } public String foo(String ss) { A a= new A(); return ss; } } /* * Created on Nov 12, 2003 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ /** * @author dbaeumer * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class B { private static interface I { public void foo(); } private static class CC implements I { public void foo() { } } public void foo() { I i= new I() { public void foo() { } public void bar() { foo(); } }; CC c= new CC() {}; B b; } public void bar() { class X { public void baz() { } } class Y extends X { public void baz() { } } } } exception is: 'org.eclipse.jdt.core.dom.SimpleName('XX')' in compilation unit 'A.java'] at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.core.runtime.CoreException.<init>(CoreException.java:35) at org.eclipse.jdt.core.JavaModelException.<init> (JavaModelException.java:67) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ge tCtorCallAt(IntroduceFactoryRefactoring.java:857) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.re placeConstructorCalls(IntroduceFactoryRefactoring.java:788) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ad dAllChangesFor(IntroduceFactoryRefactoring.java:720) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.cr eateChange(IntroduceFactoryRefactoring.java:902) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
resolved fixed
7440e94
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-12T07:55:45Z
2003-12-11T16:26:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceFactory/Bugzilla/48504/p1/B.java
48,504
Bug 48504 Exception while introducing factory [refactoring]
I20031203 with your latest patch: try introducing a factory method for constructor A in class B. Code I used is: public class A { { field= 10; } public A() { } private int field; static class XX extends A { public void foo() { bar(); } public void bar() { } } public void foo(int y) { Runnable runnable= new Runnable() { private int field; public void run() { { A a= null; } } }; } public String foo(String ss) { A a= new A(); return ss; } } /* * Created on Nov 12, 2003 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ /** * @author dbaeumer * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class B { private static interface I { public void foo(); } private static class CC implements I { public void foo() { } } public void foo() { I i= new I() { public void foo() { } public void bar() { foo(); } }; CC c= new CC() {}; B b; } public void bar() { class X { public void baz() { } } class Y extends X { public void baz() { } } } } exception is: 'org.eclipse.jdt.core.dom.SimpleName('XX')' in compilation unit 'A.java'] at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.core.runtime.CoreException.<init>(CoreException.java:35) at org.eclipse.jdt.core.JavaModelException.<init> (JavaModelException.java:67) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ge tCtorCallAt(IntroduceFactoryRefactoring.java:857) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.re placeConstructorCalls(IntroduceFactoryRefactoring.java:788) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ad dAllChangesFor(IntroduceFactoryRefactoring.java:720) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.cr eateChange(IntroduceFactoryRefactoring.java:902) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
resolved fixed
7440e94
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-12T07:55:45Z
2003-12-11T16:26:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceFactory/Bugzilla/48504/p1/B_out.java
48,504
Bug 48504 Exception while introducing factory [refactoring]
I20031203 with your latest patch: try introducing a factory method for constructor A in class B. Code I used is: public class A { { field= 10; } public A() { } private int field; static class XX extends A { public void foo() { bar(); } public void bar() { } } public void foo(int y) { Runnable runnable= new Runnable() { private int field; public void run() { { A a= null; } } }; } public String foo(String ss) { A a= new A(); return ss; } } /* * Created on Nov 12, 2003 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ /** * @author dbaeumer * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class B { private static interface I { public void foo(); } private static class CC implements I { public void foo() { } } public void foo() { I i= new I() { public void foo() { } public void bar() { foo(); } }; CC c= new CC() {}; B b; } public void bar() { class X { public void baz() { } } class Y extends X { public void baz() { } } } } exception is: 'org.eclipse.jdt.core.dom.SimpleName('XX')' in compilation unit 'A.java'] at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.core.runtime.CoreException.<init>(CoreException.java:35) at org.eclipse.jdt.core.JavaModelException.<init> (JavaModelException.java:67) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ge tCtorCallAt(IntroduceFactoryRefactoring.java:857) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.re placeConstructorCalls(IntroduceFactoryRefactoring.java:788) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ad dAllChangesFor(IntroduceFactoryRefactoring.java:720) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.cr eateChange(IntroduceFactoryRefactoring.java:902) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
resolved fixed
7440e94
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-12T07:55:45Z
2003-12-11T16:26:40Z
org.eclipse.jdt.ui.tests.refactoring/test
48,504
Bug 48504 Exception while introducing factory [refactoring]
I20031203 with your latest patch: try introducing a factory method for constructor A in class B. Code I used is: public class A { { field= 10; } public A() { } private int field; static class XX extends A { public void foo() { bar(); } public void bar() { } } public void foo(int y) { Runnable runnable= new Runnable() { private int field; public void run() { { A a= null; } } }; } public String foo(String ss) { A a= new A(); return ss; } } /* * Created on Nov 12, 2003 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ /** * @author dbaeumer * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class B { private static interface I { public void foo(); } private static class CC implements I { public void foo() { } } public void foo() { I i= new I() { public void foo() { } public void bar() { foo(); } }; CC c= new CC() {}; B b; } public void bar() { class X { public void baz() { } } class Y extends X { public void baz() { } } } } exception is: 'org.eclipse.jdt.core.dom.SimpleName('XX')' in compilation unit 'A.java'] at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.core.runtime.CoreException.<init>(CoreException.java:35) at org.eclipse.jdt.core.JavaModelException.<init> (JavaModelException.java:67) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ge tCtorCallAt(IntroduceFactoryRefactoring.java:857) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.re placeConstructorCalls(IntroduceFactoryRefactoring.java:788) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ad dAllChangesFor(IntroduceFactoryRefactoring.java:720) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.cr eateChange(IntroduceFactoryRefactoring.java:902) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
resolved fixed
7440e94
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-12T07:55:45Z
2003-12-11T16:26:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/IntroduceFactoryTests.java
57,569
Bug 57569 Search with the $V{PAGE_NUMBER} pattern fails
I am trying to search for "$V{PAGE_NUMBER}". Nothing happens in the interface when I click the Search button, but I see the following in the Eclipse log: !ENTRY org.eclipse.ui 4 0 Apr 06, 2004 16:24:14.260 !MESSAGE can't parse argument number PAGE_NUMBER !STACK 0 java.lang.IllegalArgumentException: can't parse argument number PAGE_NUMBER at java.text.MessageFormat.makeFormat(MessageFormat.java:1330) at java.text.MessageFormat.applyPattern(MessageFormat.java:450) at java.text.MessageFormat.<init>(MessageFormat.java:350) at java.text.MessageFormat.format(MessageFormat.java:803) at org.eclipse.search.internal.ui.text.FileSearchResult.getLabel(FileSearchResult.java:51) at org.eclipse.search2.internal.ui.SearchView.updateTitle(SearchView.java:272) at org.eclipse.search2.internal.ui.SearchView.showSearchResult(SearchView.java:258) at org.eclipse.search2.internal.ui.SearchView.queryAdded(SearchView.java:324) at org.eclipse.search2.internal.ui.QueryManager.fireAdded(QueryManager.java:72) at org.eclipse.search2.internal.ui.QueryManager.addQuery(QueryManager.java:49) at org.eclipse.search2.internal.ui.InternalSearchUI.runSearchInBackground(InternalSearchUI.java:115) at org.eclipse.search.ui.NewSearchUI.runQuery(NewSearchUI.java:44) at org.eclipse.search.internal.ui.text.TextSearchPage.performNewSearch(TextSearchPage.java:291) at org.eclipse.search.internal.ui.text.TextSearchPage.performAction(TextSearchPage.java:135) at org.eclipse.search.internal.ui.SearchDialog.performAction(SearchDialog.java:363) at org.eclipse.search.internal.ui.util.ExtendedDialogWindow.buttonPressed(ExtendedDialogWindow.java:147) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:413) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:769) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2578) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2256) at org.eclipse.jface.window.Window.runEventLoop(Window.java:670) at org.eclipse.jface.window.Window.open(Window.java:650) at org.eclipse.search.internal.ui.OpenSearchDialogAction.run(OpenSearchDialogAction.java:60) at org.eclipse.search.internal.ui.OpenSearchDialogAction.run(OpenSearchDialogAction.java:46) at org.eclipse.ui.internal.PluginAction.runWithEvent(PluginAction.java:269) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent(WWinPluginAction.java:207) at org.eclipse.ui.commands.ActionHandler.execute(ActionHandler.java:68) at org.eclipse.ui.internal.commands.Command.execute(Command.java:173) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.executeCommand(WorkbenchKeyboard.java:463) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.press(WorkbenchKeyboard.java:855) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.processKeyEvent(WorkbenchKeyboard.java:896) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.filterKeySequenceBindings(WorkbenchKeyboard.java:522) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.access$2(WorkbenchKeyboard.java:488) at org.eclipse.ui.internal.keys.WorkbenchKeyboard$1.handleEvent(WorkbenchKeyboard.java:261) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Display.filterEvent(Display.java:705) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:768) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:793) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:778) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1720) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1716) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3041) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2944) at org.eclipse.swt.widgets.Display.windowProc(Display.java:3146) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1450) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2254) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1562) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1536) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:257) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:90) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:277) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:239) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:117) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:494) at org.eclipse.core.launcher.Main.basicRun(Main.java:267) at org.eclipse.core.launcher.Main.run(Main.java:692) at org.eclipse.core.launcher.Main.main(Main.java:676)
verified fixed
47c9caa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-12T08:17:35Z
2004-04-06T14:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchQuery.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.search; import java.text.MessageFormat; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.ISafeRunnable; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.core.search.SearchParticipant; import org.eclipse.jdt.core.search.SearchPattern; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.ui.search.ElementQuerySpecification; import org.eclipse.jdt.ui.search.IMatchPresentation; import org.eclipse.jdt.ui.search.IQueryParticipant; import org.eclipse.jdt.ui.search.ISearchRequestor; import org.eclipse.jdt.ui.search.PatternQuerySpecification; import org.eclipse.jdt.ui.search.QuerySpecification; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.search.internal.ui.SearchPreferencePage; import org.eclipse.search.ui.ISearchQuery; import org.eclipse.search.ui.ISearchResult; import org.eclipse.search.ui.text.Match; public class JavaSearchQuery implements ISearchQuery { private ISearchResult fResult; private QuerySpecification fPatternData; public JavaSearchQuery(QuerySpecification data) { fPatternData= data; } private static class SearchRequestor implements ISearchRequestor { private IQueryParticipant fParticipant; private JavaSearchResult fSearchResult; public void reportMatch(Match match) { IMatchPresentation participant= fParticipant.getUIParticipant(); if (participant == null || match.getElement() instanceof IJavaElement || match.getElement() instanceof IResource) { fSearchResult.addMatch(match); } else { fSearchResult.addMatch(match, participant); } } protected SearchRequestor(IQueryParticipant participant, JavaSearchResult result) { super(); fParticipant= participant; fSearchResult= result; } } public IStatus run(IProgressMonitor monitor) { final JavaSearchResult textResult= (JavaSearchResult) getSearchResult(); textResult.removeAll(); // Don't need to pass in working copies in 3.0 here SearchEngine engine= new SearchEngine(); try { int totalTicks= 1000; IProject[] projects= JavaSearchScopeFactory.getInstance().getProjects(fPatternData.getScope()); final SearchParticipantRecord[] participantDescriptors= SearchParticipantsExtensionPoint.getInstance().getSearchParticipants(projects); final int[] ticks= new int[participantDescriptors.length]; for (int i= 0; i < participantDescriptors.length; i++) { final int iPrime= i; ISafeRunnable runnable= new ISafeRunnable() { public void handleException(Throwable exception) { ticks[iPrime]= 0; String message= SearchMessages.getString("JavaSearchQuery.error.participant.estimate"); //$NON-NLS-1$ JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), 0, message, exception)); } public void run() throws Exception { ticks[iPrime]= participantDescriptors[iPrime].getParticipant().estimateTicks(fPatternData); } }; Platform.run(runnable); totalTicks+= ticks[i]; } monitor.beginTask(SearchMessages.getString("JavaSearchQuery.task.label"), totalTicks); //$NON-NLS-1$ IProgressMonitor mainSearchPM= new SubProgressMonitor(monitor, 1000); boolean ignorePotentials= SearchPreferencePage.arePotentialMatchesIgnored(); NewSearchResultCollector collector= new NewSearchResultCollector(textResult, ignorePotentials); SearchPattern pattern; String stringPattern= null; if (fPatternData instanceof ElementQuerySpecification) { pattern= SearchPattern.createPattern(((ElementQuerySpecification)fPatternData).getElement(), fPatternData.getLimitTo()); stringPattern= ((ElementQuerySpecification)fPatternData).getElement().getElementName(); } else { PatternQuerySpecification patternSpec = (PatternQuerySpecification) fPatternData; stringPattern = patternSpec.getPattern(); int matchMode = stringPattern.indexOf('*') != -1 || stringPattern.indexOf('?') != -1 ? SearchPattern.R_PATTERN_MATCH : SearchPattern.R_EXACT_MATCH; if (patternSpec.isCaseSensitive()) matchMode |= SearchPattern.R_CASE_SENSITIVE; pattern = SearchPattern.createPattern(patternSpec.getPattern(), patternSpec.getSearchFor(), patternSpec.getLimitTo(), matchMode); } if (pattern == null) { return new Status(IStatus.ERROR, JavaPlugin.getPluginId(), 0, SearchMessages.getFormattedString("JavaSearchQuery.error.unsupported_pattern", stringPattern), null); //$NON-NLS-1$ } engine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, fPatternData.getScope(), collector, mainSearchPM); for (int i= 0; i < participantDescriptors.length; i++) { final ISearchRequestor requestor= new SearchRequestor(participantDescriptors[i].getParticipant(), textResult); final IProgressMonitor participantPM= new SubProgressMonitor(monitor, ticks[i]); final int iPrime= i; ISafeRunnable runnable= new ISafeRunnable() { public void handleException(Throwable exception) { participantDescriptors[iPrime].getDescriptor().disable(); String message= SearchMessages.getString("JavaSearchQuery.error.participant.search"); //$NON-NLS-1$ JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), 0, message, exception)); } public void run() throws Exception { participantDescriptors[iPrime].getParticipant().search(requestor, fPatternData, participantPM); } }; Platform.run(runnable); } } catch (CoreException e) { return e.getStatus(); } // TODO fix status message String message= SearchMessages.getString("JavaSearchQuery.status.ok.message"); //$NON-NLS-1$ MessageFormat.format(message, new Object[] { new Integer(textResult.getMatchCount()) }); return new Status(IStatus.OK, JavaPlugin.getPluginId(), 0, message, null); } public String getLabel() { if (fPatternData.getLimitTo() == IJavaSearchConstants.REFERENCES) return SearchMessages.getString("JavaSearchQuery.searchfor_references"); //$NON-NLS-1$ else if (fPatternData.getLimitTo() == IJavaSearchConstants.DECLARATIONS) return SearchMessages.getString("JavaSearchQuery.searchfor_declarations"); //$NON-NLS-1$ else if (fPatternData.getLimitTo() == IJavaSearchConstants.READ_ACCESSES) return SearchMessages.getString("JavaSearchQuery.searchfor_read_access"); //$NON-NLS-1$ else if (fPatternData.getLimitTo() == IJavaSearchConstants.WRITE_ACCESSES) return SearchMessages.getString("JavaSearchQuery.searchfor_write_access"); //$NON-NLS-1$ else if (fPatternData.getLimitTo() == IJavaSearchConstants.IMPLEMENTORS) return SearchMessages.getString("JavaSearchQuery.searchfor_implementors"); //$NON-NLS-1$ return SearchMessages.getString("JavaSearchQuery.search_label"); //$NON-NLS-1$ } String getSingularLabel() { String desc= null; if (fPatternData instanceof ElementQuerySpecification) { IJavaElement element= ((ElementQuerySpecification)fPatternData).getElement(); if (fPatternData.getLimitTo() == IJavaSearchConstants.REFERENCES && element.getElementType() == IJavaElement.METHOD) desc= PrettySignature.getUnqualifiedMethodSignature((IMethod)element); else desc= element.getElementName(); if ("".equals(desc) && element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) //$NON-NLS-1$ desc= SearchMessages.getString("JavaSearchOperation.default_package"); //$NON-NLS-1$ } else { desc= ((PatternQuerySpecification)fPatternData).getPattern(); } desc= "\""+desc+"\""; //$NON-NLS-1$ //$NON-NLS-2$ String[] args= new String[] {desc, fPatternData.getScopeDescription()}; //$NON-NLS-1$ switch (fPatternData.getLimitTo()) { case IJavaSearchConstants.IMPLEMENTORS: return SearchMessages.getFormattedString("JavaSearchOperation.singularImplementorsPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.DECLARATIONS: return SearchMessages.getFormattedString("JavaSearchOperation.singularDeclarationsPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.REFERENCES: return SearchMessages.getFormattedString("JavaSearchOperation.singularReferencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.ALL_OCCURRENCES: return SearchMessages.getFormattedString("JavaSearchOperation.singularOccurrencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.READ_ACCESSES: return SearchMessages.getFormattedString("JavaSearchOperation.singularReadReferencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.WRITE_ACCESSES: return SearchMessages.getFormattedString("JavaSearchOperation.singularWriteReferencesPostfix", args); //$NON-NLS-1$ default: return SearchMessages.getFormattedString("JavaSearchOperation.singularOccurrencesPostfix", args); //$NON-NLS-1$; } } String getPluralLabelPattern() { String desc= null; if (fPatternData instanceof ElementQuerySpecification) { IJavaElement element= ((ElementQuerySpecification)fPatternData).getElement(); if (fPatternData.getLimitTo() == IJavaSearchConstants.REFERENCES && element.getElementType() == IJavaElement.METHOD) desc= PrettySignature.getUnqualifiedMethodSignature((IMethod)element); else desc= element.getElementName(); if ("".equals(desc) && element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) //$NON-NLS-1$ desc= SearchMessages.getString("JavaSearchOperation.default_package"); //$NON-NLS-1$ } else { desc= ((PatternQuerySpecification)fPatternData).getPattern(); } desc= "\""+desc+"\""; //$NON-NLS-1$ //$NON-NLS-2$ String[] args= new String[] {desc, "{0}", fPatternData.getScopeDescription()}; //$NON-NLS-1$ switch (fPatternData.getLimitTo()) { case IJavaSearchConstants.IMPLEMENTORS: return SearchMessages.getFormattedString("JavaSearchOperation.pluralImplementorsPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.DECLARATIONS: return SearchMessages.getFormattedString("JavaSearchOperation.pluralDeclarationsPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.REFERENCES: return SearchMessages.getFormattedString("JavaSearchOperation.pluralReferencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.ALL_OCCURRENCES: return SearchMessages.getFormattedString("JavaSearchOperation.pluralOccurrencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.READ_ACCESSES: return SearchMessages.getFormattedString("JavaSearchOperation.pluralReadReferencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.WRITE_ACCESSES: return SearchMessages.getFormattedString("JavaSearchOperation.pluralWriteReferencesPostfix", args); //$NON-NLS-1$ default: return SearchMessages.getFormattedString("JavaSearchOperation.pluralOccurrencesPostfix", args); //$NON-NLS-1$; } } ImageDescriptor getImageDescriptor() { if (fPatternData.getLimitTo() == IJavaSearchConstants.IMPLEMENTORS || fPatternData.getLimitTo() == IJavaSearchConstants.DECLARATIONS) return JavaPluginImages.DESC_OBJS_SEARCH_DECL; else return JavaPluginImages.DESC_OBJS_SEARCH_REF; } public boolean canRerun() { return true; } public boolean canRunInBackground() { return true; } public ISearchResult getSearchResult() { if (fResult == null) fResult= new JavaSearchResult(this); return fResult; } QuerySpecification getSpecification() { return fPatternData; } }
56,132
Bug 56132 method signature refactoring does not update javadoc [refactoring]
removing an exception with method signature refactoring does not update javadoc. example: /** * @throws Exception * @throws IOException * @throws IllegalArgumentException */ void doNothing() throws Exception, IOException, IllegalArgumentException { } when removing IOException or IllegalArgumentException javadoc is not updated. no problem when removing the "first" exception.
resolved fixed
e27c479
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-12T08:35:24Z
2004-03-25T13:06:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testException05_in.java
56,132
Bug 56132 method signature refactoring does not update javadoc [refactoring]
removing an exception with method signature refactoring does not update javadoc. example: /** * @throws Exception * @throws IOException * @throws IllegalArgumentException */ void doNothing() throws Exception, IOException, IllegalArgumentException { } when removing IOException or IllegalArgumentException javadoc is not updated. no problem when removing the "first" exception.
resolved fixed
e27c479
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-12T08:35:24Z
2004-03-25T13:06:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testException05_out.java
56,132
Bug 56132 method signature refactoring does not update javadoc [refactoring]
removing an exception with method signature refactoring does not update javadoc. example: /** * @throws Exception * @throws IOException * @throws IllegalArgumentException */ void doNothing() throws Exception, IOException, IllegalArgumentException { } when removing IOException or IllegalArgumentException javadoc is not updated. no problem when removing the "first" exception.
resolved fixed
e27c479
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-12T08:35:24Z
2004-03-25T13:06:40Z
org.eclipse.jdt.ui.tests.refactoring/test
56,132
Bug 56132 method signature refactoring does not update javadoc [refactoring]
removing an exception with method signature refactoring does not update javadoc. example: /** * @throws Exception * @throws IOException * @throws IllegalArgumentException */ void doNothing() throws Exception, IOException, IllegalArgumentException { } when removing IOException or IllegalArgumentException javadoc is not updated. no problem when removing the "first" exception.
resolved fixed
e27c479
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-05-12T08:35:24Z
2004-03-25T13:06:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java