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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
45,448 |
Bug 45448 Operation unavailable attempting to search a local variable [search]
|
Build 20031023 Selecting a local variable declaration in a Java editor and attempting to search for references to this local variable brings up a dialog saying the the operation is unavailable for the selected element.
|
verified fixed
|
a6ada08
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-12T10:44:16Z | 2003-10-23T14:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/FindWriteReferencesInWorkingSetAction.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.ui.IWorkbenchSite;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.search.SearchMessages;
/**
* Finds field write accesses of the selected element in working sets.
* The action is applicable to selections representing a Java field.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class FindWriteReferencesInWorkingSetAction extends FindReferencesInWorkingSetAction {
/**
* Creates a new <code>FindWriteReferencesInWorkingSetAction</code>. The action
* requires that the selection provided by the site's selection provider is of type
* <code>org.eclipse.jface.viewers.IStructuredSelection</code>. The user will be
* prompted to select the working sets.
*
* @param site the site providing context information for this action
*/
public FindWriteReferencesInWorkingSetAction(IWorkbenchSite site) {
super(site, SearchMessages.getString("Search.FindWriteReferencesInWorkingSetAction.label"), new Class[] {IField.class} ); //$NON-NLS-1$
setToolTipText(SearchMessages.getString("Search.FindWriteReferencesInWorkingSetAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.FIND_WRITE_REFERENCES_IN_WORKING_SET_ACTION);
}
/**
* Creates a new <code>FindWriteReferencesInWorkingSetAction</code>. The action
* requires that the selection provided by the site's selection provider is of type
* <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
* @param workingSets the working sets to be used in the search
*/
public FindWriteReferencesInWorkingSetAction(IWorkbenchSite site, IWorkingSet[] workingSets) {
super(site, workingSets, new Class[] {IField.class});
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.FIND_WRITE_REFERENCES_IN_WORKING_SET_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public FindWriteReferencesInWorkingSetAction(JavaEditor editor) {
super(editor, SearchMessages.getString("Search.FindWriteReferencesInWorkingSetAction.label"), new Class[] {IField.class} ); //$NON-NLS-1$
setToolTipText(SearchMessages.getString("Search.FindWriteReferencesInWorkingSetAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.FIND_WRITE_REFERENCES_IN_WORKING_SET_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public FindWriteReferencesInWorkingSetAction(JavaEditor editor, IWorkingSet[] workingSets) {
super(editor, workingSets, new Class[] {IField.class});
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.FIND_WRITE_REFERENCES_IN_WORKING_SET_ACTION);
}
int getLimitTo() {
return IJavaSearchConstants.WRITE_ACCESSES;
}
String getOperationUnavailableMessage() {
return SearchMessages.getString("JavaElementAction.operationUnavailable.field"); //$NON-NLS-1$
}
}
|
48,617 |
Bug 48617 Error range for unresolved names in qualified references
|
20031211 1. in the following code public void foo() { int i= xxx.yyy; } 2. if 'xxx' is undefined, but the compiler marks 'xxx.yyy' as unresolved. It would be better to only mark 'xxx'
|
verified fixed
|
885286b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-12T22:39:05Z | 2003-12-12T00: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 <[email protected]> - 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.text.edits.ReplaceEdit;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.core.resources.IFile;
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.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.ASTNodeConstants;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
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.textmanipulation.TextBuffer;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.corext.util.WorkingCopyUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
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 suggestVariablePropasals= 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) {
suggestVariablePropasals= false;
typeKind= SimilarElementsRequestor.REF_TYPES;
}
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;
suggestVariablePropasals= node.isSimpleName();
}
if (selectedNode.getParent() instanceof SimpleType) {
typeKind= SimilarElementsRequestor.REF_TYPES;
suggestVariablePropasals= 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 (!suggestVariablePropasals) {
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) throws CoreException {
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= new ASTRewrite(statement.getParent());
rewrite.markAsRemoved(statement);
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);
proposal.ensureNoModifications();
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, senderBinding.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);
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
}
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 ReplaceCorrectionProposal(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 variablefragment
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;
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 simlar 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 {
TextBuffer buffer= null;
try {
buffer= TextBuffer.acquire((IFile)WorkingCopyUtil.getOriginal(cu).getResource());
CUCorrectionProposal proposal= new CUCorrectionProposal("", cu, 0); //$NON-NLS-1$
ImportRewrite importRewrite= new ImportRewrite(cu, JavaPreferencesSettings.getCodeGenerationSettings());
String simpleName= importRewrite.addImport(fullName);
TextEdit root= proposal.getRootTextEdit();
if (!importRewrite.isEmpty()) {
root.addChild(importRewrite.createEdit(buffer)); //$NON-NLS-1$
}
String packName= Signature.getQualifier(fullName);
String[] arg= { simpleName, packName };
if (node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) { // import only
proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL));
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importtype.description", arg)); //$NON-NLS-1$
proposal.setRelevance(relevance + 20);
} else {
root.addChild(new ReplaceEdit(node.getStartPosition(), node.getLength(), simpleName)); //$NON-NLS-1$
if (packName.length() == 0) {
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.nopack.description", simpleName)); //$NON-NLS-1$
} else {
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.description", arg)); //$NON-NLS-1$
}
proposal.setRelevance(relevance);
}
return proposal;
} finally {
if (buffer != null)
TextBuffer.release(buffer);
}
}
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 sugest 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 ReplaceCorrectionProposal(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) throws CoreException {
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= new ASTRewrite(expression.getParent());
CastExpression newCast= ast.newCastExpression();
newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType()));
newCast.setExpression((Expression) rewrite.createCopy(accessExpression));
ParenthesizedExpression parents= ast.newParenthesizedExpression();
parents.setExpression(newCast);
ASTNode node= rewrite.createCopy(expression.getExpression());
rewrite.markAsReplaced(expression, node);
rewrite.markAsReplaced(accessExpression, parents);
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);
proposal.ensureNoModifications();
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));
proposal.ensureNoModifications();
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, 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
{
ASTNode selectedNode= problem.getCoveringNode(astRoot);
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
for (int i= diff - 1; i >= 0; i--) {
rewrite.markAsRemoved((Expression) arguments.get(indexSkipped[i]));
}
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);
proposal.ensureNoModifications();
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 (isDifferentCU && 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, 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;
}
}
CompilationUnit unit= AST.parsePartialCompilationUnit(targetCU, 0, true);
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 missmatching: 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= LocalCorrectionsSubProcessor.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$
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
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= new ASTRewrite(arg1.getParent());
rewrite.markAsReplaced(arg1, rewrite.createCopy(arg2));
rewrite.markAsReplaced(arg2, rewrite.createCopy(arg1));
{
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);
proposal.ensureNoModifications();
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, 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, 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= new ASTRewrite(invocationNode.getParent());
AST ast= invocationNode.getAST();
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.ensureNoModifications();
proposals.add(proposal);
String qualifier= proposal.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.markAsInsert(invocationNode, ASTNodeConstants.EXPRESSION, newExpression, null);
}
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) {
String qualifiedTypeName= JavaModelUtil.getFullyQualifiedName((IType) curr);
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);
TextBuffer buffer= null;
try {
buffer= TextBuffer.acquire((IFile)WorkingCopyUtil.getOriginal(cu).getResource());
ImportRewrite importRewrite= new ImportRewrite(cu, JavaPreferencesSettings.getCodeGenerationSettings());
importRewrite.addImport(qualifiedTypeName);
importRewrite.setFindAmbiguosImports(true);
proposal.getRootTextEdit().addChild(importRewrite.createEdit(buffer));
proposals.add(proposal);
} finally {
if (buffer != null)
TextBuffer.release(buffer);
}
}
}
}
}
|
27,907 |
Bug 27907 Autocreate of a local variable outside of current block
|
If you type something like the following void myMethod() { try { a=someCall(); } catch(Exception e) { } System.out.println(a); } the variable 'a' isn't declared and code assist proposes to create a declaration for the local variable 'a'. But it is created inside the current block and not in the context of the method: void myMethod() { try { int a=someCall(); } catch(Exception e) { } System.out.println(a); // we've still got a problem here... } Code assist should detect wether the variable is used only inside the current block and create the delcaration only block local if the variable isn't used outside of the block.
|
resolved fixed
|
29bc7e6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-13T00:11:58Z | 2002-12-08T23:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NewVariableCompletionProposal.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.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.internal.corext.dom.ASTNodeConstants;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
public class NewVariableCompletionProposal extends LinkedCorrectionProposal {
public static final int LOCAL= 1;
public static final int FIELD= 2;
public static final int PARAM= 3;
public static final int CONST_FIELD= 4;
private static final String KEY_NAME= "name"; //$NON-NLS-1$
private static final String KEY_TYPE= "type"; //$NON-NLS-1$
private static final String KEY_INITIALIZER= "initializer"; //$NON-NLS-1$
private int fVariableKind;
private SimpleName fOriginalNode;
private ITypeBinding fSenderBinding;
public NewVariableCompletionProposal(String label, ICompilationUnit cu, int variableKind, SimpleName node, ITypeBinding senderBinding, int relevance, Image image) {
super(label, cu, null, relevance, image);
fVariableKind= variableKind;
fOriginalNode= node;
fSenderBinding= senderBinding;
}
protected ASTRewrite getRewrite() throws CoreException {
CompilationUnit cu= ASTResolving.findParentCompilationUnit(fOriginalNode);
if (fVariableKind == PARAM) {
return doAddParam(cu);
} else if (fVariableKind == FIELD || fVariableKind ==CONST_FIELD) {
return doAddField(cu);
} else { // LOCAL
return doAddLocal(cu);
}
}
private ASTRewrite doAddParam(CompilationUnit cu) throws CoreException {
AST ast= cu.getAST();
SimpleName node= fOriginalNode;
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(node);
if (decl instanceof MethodDeclaration) {
ASTRewrite rewrite= new ASTRewrite(decl);
SingleVariableDeclaration newDecl= ast.newSingleVariableDeclaration();
newDecl.setType(evaluateVariableType(ast));
newDecl.setName(ast.newSimpleName(node.getIdentifier()));
rewrite.markAsInsertBeforeOriginal(decl, ASTNodeConstants.PARAMETERS, newDecl, null, null);
markAsLinked(rewrite, newDecl.getType(), false, KEY_TYPE);
markAsLinked(rewrite, node, true, KEY_NAME);
markAsLinked(rewrite, newDecl.getName(), false, KEY_NAME);
return rewrite;
}
return null;
}
private ASTRewrite doAddLocal(CompilationUnit cu) throws CoreException {
AST ast= cu.getAST();
SimpleName node= fOriginalNode;
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(node);
if (decl instanceof MethodDeclaration || decl instanceof Initializer) {
ASTRewrite rewrite= new ASTRewrite(decl);
ASTNode parent= node.getParent();
if (parent.getNodeType() == ASTNode.ASSIGNMENT) {
Assignment assignment= (Assignment) parent;
if (node.equals(assignment.getLeftHandSide())) {
int parentParentKind= parent.getParent().getNodeType();
if (parentParentKind == ASTNode.EXPRESSION_STATEMENT) {
// x = 1; -> int x = 1;
VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment();
VariableDeclarationStatement newDecl= ast.newVariableDeclarationStatement(newDeclFrag);
newDecl.setType(evaluateVariableType(ast));
Expression placeholder= (Expression) rewrite.createCopy(assignment.getRightHandSide());
newDeclFrag.setInitializer(placeholder);
newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
rewrite.markAsReplaced(assignment.getParent(), newDecl);
markAsLinked(rewrite, newDecl.getType(), false, KEY_TYPE);
markAsLinked(rewrite, newDeclFrag.getName(), true, KEY_NAME);
markAsSelection(rewrite, newDecl); // end position
return rewrite;
} else if (parentParentKind == ASTNode.FOR_STATEMENT) {
// for (x = 1;;) ->for (int x = 1;;)
ForStatement forStatement= (ForStatement) parent.getParent();
if (forStatement.initializers().size() == 1 && assignment.equals(forStatement.initializers().get(0))) {
VariableDeclarationFragment frag= ast.newVariableDeclarationFragment();
VariableDeclarationExpression expression= ast.newVariableDeclarationExpression(frag);
frag.setName(ast.newSimpleName(node.getIdentifier()));
Expression placeholder= (Expression) rewrite.createCopy(assignment.getRightHandSide());
frag.setInitializer(placeholder);
expression.setType(evaluateVariableType(ast));
rewrite.markAsReplaced(assignment, expression);
markAsLinked(rewrite, expression.getType(), false, KEY_TYPE);
markAsLinked(rewrite, frag.getName(), true, KEY_NAME);
markAsSelection(rewrite, expression); // end position
return rewrite;
}
}
}
}
// foo(x) -> int x= 0; foo(x)
VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment();
VariableDeclarationStatement newDecl= ast.newVariableDeclarationStatement(newDeclFrag);
newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
newDecl.setType(evaluateVariableType(ast));
newDeclFrag.setInitializer(ASTNodeFactory.newDefaultExpression(ast, newDecl.getType(), 0));
markAsLinked(rewrite, newDecl.getType(), false, KEY_TYPE);
markAsLinked(rewrite, node, true, KEY_NAME);
markAsLinked(rewrite, newDeclFrag.getName(), false, KEY_NAME);
Statement statement= ASTResolving.findParentStatement(node);
if (statement != null) {
List list= ASTNodes.getContainingList(statement);
while (list == null && statement.getParent() instanceof Statement) { // parent must be if, for or while
statement= (Statement) statement.getParent();
list= ASTNodes.getContainingList(statement);
}
if (list != null) {
list.add(list.indexOf(statement), newDecl);
rewrite.markAsInserted(newDecl);
return rewrite;
}
}
}
return null;
}
private ASTRewrite doAddField(CompilationUnit astRoot) throws CoreException {
SimpleName node= fOriginalNode;
boolean isInDifferentCU= false;
ASTNode newTypeDecl= astRoot.findDeclaringNode(fSenderBinding);
if (newTypeDecl == null) {
astRoot= AST.parseCompilationUnit(getCompilationUnit(), true);
newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
isInDifferentCU= true;
}
if (newTypeDecl != null) {
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= newTypeDecl.getAST();
VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
fragment.setName(ast.newSimpleName(node.getIdentifier()));
Type type= evaluateVariableType(ast);
FieldDeclaration newDecl= ast.newFieldDeclaration(fragment);
newDecl.setType(type);
newDecl.setModifiers(evaluateFieldModifiers(newTypeDecl));
if (fSenderBinding.isInterface() || fVariableKind == CONST_FIELD) {
fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0));
}
boolean isAnonymous= newTypeDecl.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION;
List decls= isAnonymous ? ((AnonymousClassDeclaration) newTypeDecl).bodyDeclarations() : ((TypeDeclaration) newTypeDecl).bodyDeclarations();
int insertIndex= findFieldInsertIndex(decls, node.getStartPosition());
rewrite.markAsInsertInOriginal(newTypeDecl, ASTNodeConstants.BODY_DECLARATIONS, newDecl, insertIndex, null);
markAsLinked(rewrite, newDecl.getType(), false, KEY_TYPE);
if (!isInDifferentCU) {
markAsLinked(rewrite, node, true, KEY_NAME);
}
markAsLinked(rewrite, fragment.getName(), false, KEY_NAME);
if (fragment.getInitializer() != null) {
markAsLinked(rewrite, fragment.getInitializer(), false, KEY_INITIALIZER);
}
return rewrite;
}
return null;
}
private int findFieldInsertIndex(List decls, int currPos) {
for (int i= decls.size() - 1; i >= 0; i--) {
ASTNode curr= (ASTNode) decls.get(i);
if (curr instanceof FieldDeclaration) {
if (currPos > curr.getStartPosition() + curr.getLength()) {
return i + 1;
}
}
}
return 0;
}
private Type evaluateVariableType(AST ast) throws CoreException {
ITypeBinding binding= ASTResolving.guessBindingForReference(fOriginalNode);
if (binding != null) {
if (isVariableAssigned()) {
ITypeBinding[] typeProposals= ASTResolving.getRelaxingTypes(ast, binding);
for (int i= 0; i < typeProposals.length; i++) {
addLinkedModeProposal(KEY_TYPE, typeProposals[i]);
}
}
String typeName= addImport(binding);
return ASTNodeFactory.newType(ast, typeName);
}
Type type= ASTResolving.guessTypeForReference(ast, fOriginalNode);
if (type != null) {
return type;
}
if (fVariableKind == CONST_FIELD) {
return ast.newSimpleType(ast.newSimpleName("String")); //$NON-NLS-1$
}
return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
}
private boolean isVariableAssigned() {
ASTNode parent= fOriginalNode.getParent();
return (parent instanceof Assignment) && (fOriginalNode == ((Assignment) parent).getLeftHandSide());
}
private int evaluateFieldModifiers(ASTNode newTypeDecl) {
if (fSenderBinding.isInterface()) {
// for interface members copy the modifiers from an existing field
FieldDeclaration[] fieldDecls= ((TypeDeclaration) newTypeDecl).getFields();
if (fieldDecls.length > 0) {
return fieldDecls[0].getModifiers();
}
return 0;
}
int modifiers= 0;
if (fVariableKind == CONST_FIELD) {
modifiers |= Modifier.FINAL | Modifier.STATIC;
} else {
ASTNode parent= fOriginalNode.getParent();
if (parent instanceof QualifiedName) {
IBinding qualifierBinding= ((QualifiedName)parent).getQualifier().resolveBinding();
if (qualifierBinding instanceof ITypeBinding) {
modifiers |= Modifier.STATIC;
}
} else if (ASTResolving.isInStaticContext(fOriginalNode)) {
modifiers |= Modifier.STATIC;
}
}
ASTNode node= ASTResolving.findParentType(fOriginalNode);
if (newTypeDecl.equals(node)) {
modifiers |= Modifier.PRIVATE;
} else if (node instanceof AnonymousClassDeclaration) {
modifiers |= Modifier.PROTECTED;
} else {
modifiers |= Modifier.PUBLIC;
}
return modifiers;
}
/**
* Returns the variable kind.
* @return int
*/
public int getVariableKind() {
return fVariableKind;
}
}
|
48,696 |
Bug 48696 Add JUnit libraries Quick Fix [JUnit]
|
Currently the Quick Fix only works on a line containing "TestCase". It should also work on lines w/ a) "junit.framework" b) "Test suite()" c) "TestSuite"
|
verified fixed
|
7284a4f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-14T15:32:11Z | 2003-12-13T15:40:00Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/JUnitQuickFixProcessor.java
|
/*
* Created on Jul 2, 2003
*
* To change this generated comment go to
* Window>Preferences>Java>Code Generation>Code Template
*/
package org.eclipse.jdt.internal.junit.ui;
import org.eclipse.core.runtime.CoreException;
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 JUnitQuickFixProcessor implements IQuickFixProcessor {
/* (non-Javadoc)
* @see org.eclipse.jdt.ui.text.java.IQuickFixProcessor#hasCorrections(org.eclipse.jdt.core.ICompilationUnit, int)
*/
public boolean hasCorrections(ICompilationUnit unit, int problemId) {
return IProblem.SuperclassNotFound == problemId || IProblem.ImportNotFound == problemId;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.ui.text.java.IQuickFixProcessor#getCorrections(org.eclipse.jdt.ui.text.java.IInvocationContext, org.eclipse.jdt.ui.text.java.IProblemLocation[])
*/
public IJavaCompletionProposal[] getCorrections(final IInvocationContext context, IProblemLocation[] locations) throws CoreException {
if (isJUnitProblem(context, locations))
return new IJavaCompletionProposal[] { new JUnitAddLibraryProposal(context) };
return new IJavaCompletionProposal[] {};
}
private boolean isJUnitProblem(IInvocationContext context, IProblemLocation[] locations) {
ICompilationUnit unit= context.getCompilationUnit();
for (int i= 0; i < locations.length; i++) {
IProblemLocation location= locations[i];
try {
String s= unit.getBuffer().getText(location.getOffset(), location.getLength());
if (s.equals("TestCase") || s.equals("junit.framework.TestCase")) //$NON-NLS-1$ //$NON-NLS-2$
return true;
} catch (JavaModelException e) {
e.printStackTrace();
}
}
return false;
}
}
|
46,933 |
Bug 46933 refactoring: NPE when using "Generalize Type" on field in local type
|
I20031119 (M5 test pass) 1. have this code: public class Test { public void foobar() { class Listener3 { private Test fTest; private Listener3() { fTest= new Test(); } public int bar() { return foo(); } public int foo() { return 1; } private String getProperty() { return null; } } this.addListener(new Listener3() { public int bar() { return 1; } }); } public void addListener(Object o) { } } 2. Select the type name ('Test') of field fTest in the local type 3. Choose Refactor->Generalize Type -> The dialog comes up, but then an exception is thrown, stack trace of the inner exception (inside a runnable): 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.ChangeTypeWizard$ChangeTypeInputPage$ValidTypesTask.run(ChangeTypeWizard.java:173) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ChangeTypeAction.run(ChangeTypeAction.java:75) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java) 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:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
|
resolved fixed
|
4493b21
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T13:24:10Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeTypeRefactoring/negative/A_testFieldOfLocalType_in.java
| |
46,933 |
Bug 46933 refactoring: NPE when using "Generalize Type" on field in local type
|
I20031119 (M5 test pass) 1. have this code: public class Test { public void foobar() { class Listener3 { private Test fTest; private Listener3() { fTest= new Test(); } public int bar() { return foo(); } public int foo() { return 1; } private String getProperty() { return null; } } this.addListener(new Listener3() { public int bar() { return 1; } }); } public void addListener(Object o) { } } 2. Select the type name ('Test') of field fTest in the local type 3. Choose Refactor->Generalize Type -> The dialog comes up, but then an exception is thrown, stack trace of the inner exception (inside a runnable): 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.ChangeTypeWizard$ChangeTypeInputPage$ValidTypesTask.run(ChangeTypeWizard.java:173) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ChangeTypeAction.run(ChangeTypeAction.java:75) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java) 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:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
|
resolved fixed
|
4493b21
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T13:24:10Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeTypeRefactoring/negative/A_testFieldOfLocalType_out.java
| |
46,933 |
Bug 46933 refactoring: NPE when using "Generalize Type" on field in local type
|
I20031119 (M5 test pass) 1. have this code: public class Test { public void foobar() { class Listener3 { private Test fTest; private Listener3() { fTest= new Test(); } public int bar() { return foo(); } public int foo() { return 1; } private String getProperty() { return null; } } this.addListener(new Listener3() { public int bar() { return 1; } }); } public void addListener(Object o) { } } 2. Select the type name ('Test') of field fTest in the local type 3. Choose Refactor->Generalize Type -> The dialog comes up, but then an exception is thrown, stack trace of the inner exception (inside a runnable): 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.ChangeTypeWizard$ChangeTypeInputPage$ValidTypesTask.run(ChangeTypeWizard.java:173) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ChangeTypeAction.run(ChangeTypeAction.java:75) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java) 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:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
|
resolved fixed
|
4493b21
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T13:24:10Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
46,933 |
Bug 46933 refactoring: NPE when using "Generalize Type" on field in local type
|
I20031119 (M5 test pass) 1. have this code: public class Test { public void foobar() { class Listener3 { private Test fTest; private Listener3() { fTest= new Test(); } public int bar() { return foo(); } public int foo() { return 1; } private String getProperty() { return null; } } this.addListener(new Listener3() { public int bar() { return 1; } }); } public void addListener(Object o) { } } 2. Select the type name ('Test') of field fTest in the local type 3. Choose Refactor->Generalize Type -> The dialog comes up, but then an exception is thrown, stack trace of the inner exception (inside a runnable): 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.ChangeTypeWizard$ChangeTypeInputPage$ValidTypesTask.run(ChangeTypeWizard.java:173) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ChangeTypeAction.run(ChangeTypeAction.java:75) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java) 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:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
|
resolved fixed
|
4493b21
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T13:24:10Z | 2003-11-19T11:06:40Z |
cases/org/eclipse/jdt/ui/tests/refactoring/ChangeTypeRefactoringTests.java
| |
46,933 |
Bug 46933 refactoring: NPE when using "Generalize Type" on field in local type
|
I20031119 (M5 test pass) 1. have this code: public class Test { public void foobar() { class Listener3 { private Test fTest; private Listener3() { fTest= new Test(); } public int bar() { return foo(); } public int foo() { return 1; } private String getProperty() { return null; } } this.addListener(new Listener3() { public int bar() { return 1; } }); } public void addListener(Object o) { } } 2. Select the type name ('Test') of field fTest in the local type 3. Choose Refactor->Generalize Type -> The dialog comes up, but then an exception is thrown, stack trace of the inner exception (inside a runnable): 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.ChangeTypeWizard$ChangeTypeInputPage$ValidTypesTask.run(ChangeTypeWizard.java:173) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ChangeTypeAction.run(ChangeTypeAction.java:75) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java) 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:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
|
resolved fixed
|
4493b21
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T13:24:10Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui/core
| |
46,933 |
Bug 46933 refactoring: NPE when using "Generalize Type" on field in local type
|
I20031119 (M5 test pass) 1. have this code: public class Test { public void foobar() { class Listener3 { private Test fTest; private Listener3() { fTest= new Test(); } public int bar() { return foo(); } public int foo() { return 1; } private String getProperty() { return null; } } this.addListener(new Listener3() { public int bar() { return 1; } }); } public void addListener(Object o) { } } 2. Select the type name ('Test') of field fTest in the local type 3. Choose Refactor->Generalize Type -> The dialog comes up, but then an exception is thrown, stack trace of the inner exception (inside a runnable): 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.ChangeTypeWizard$ChangeTypeInputPage$ValidTypesTask.run(ChangeTypeWizard.java:173) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ChangeTypeAction.run(ChangeTypeAction.java:75) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java) 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:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
|
resolved fixed
|
4493b21
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T13:24:10Z | 2003-11-19T11:06:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeTypeRefactoring.java
| |
46,933 |
Bug 46933 refactoring: NPE when using "Generalize Type" on field in local type
|
I20031119 (M5 test pass) 1. have this code: public class Test { public void foobar() { class Listener3 { private Test fTest; private Listener3() { fTest= new Test(); } public int bar() { return foo(); } public int foo() { return 1; } private String getProperty() { return null; } } this.addListener(new Listener3() { public int bar() { return 1; } }); } public void addListener(Object o) { } } 2. Select the type name ('Test') of field fTest in the local type 3. Choose Refactor->Generalize Type -> The dialog comes up, but then an exception is thrown, stack trace of the inner exception (inside a runnable): 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.ChangeTypeWizard$ChangeTypeInputPage$ValidTypesTask.run(ChangeTypeWizard.java:173) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ChangeTypeAction.run(ChangeTypeAction.java:75) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java) 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:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
|
resolved fixed
|
4493b21
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T13:24:10Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui/ui
| |
46,933 |
Bug 46933 refactoring: NPE when using "Generalize Type" on field in local type
|
I20031119 (M5 test pass) 1. have this code: public class Test { public void foobar() { class Listener3 { private Test fTest; private Listener3() { fTest= new Test(); } public int bar() { return foo(); } public int foo() { return 1; } private String getProperty() { return null; } } this.addListener(new Listener3() { public int bar() { return 1; } }); } public void addListener(Object o) { } } 2. Select the type name ('Test') of field fTest in the local type 3. Choose Refactor->Generalize Type -> The dialog comes up, but then an exception is thrown, stack trace of the inner exception (inside a runnable): 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.ChangeTypeWizard$ChangeTypeInputPage$ValidTypesTask.run(ChangeTypeWizard.java:173) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ChangeTypeAction.run(ChangeTypeAction.java:75) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java) 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:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
|
resolved fixed
|
4493b21
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T13:24:10Z | 2003-11-19T11:06:40Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeTypeWizard.java
| |
45,926 |
Bug 45926 Change Method Signature dialog does not show "static" in Method Signature Preview. [refactoring]
|
The Refactor/Change Method Signature dialog does not show "static" in Method Signature Preview for static methods. Version: 3.0.0 Build id: 200310101454
|
resolved fixed
|
a565abc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T15:47:47Z | 2003-11-03T00:40:00Z |
org.eclipse.jdt.ui/core
| |
45,926 |
Bug 45926 Change Method Signature dialog does not show "static" in Method Signature Preview. [refactoring]
|
The Refactor/Change Method Signature dialog does not show "static" in Method Signature Preview for static methods. Version: 3.0.0 Build id: 200310101454
|
resolved fixed
|
a565abc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T15:47:47Z | 2003-11-03T00:40:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureRefactoring.java
| |
46,926 |
Bug 46926 Editable Table: Key-navigation is bad [refactoring] [misc]
|
20031119 My expectations for table navigation and usages come from windows applications like MS Excel. The eclipse tables are not follow the 'look' but not the 'feel' and are in general very frustarting to use. 1. select a method and choose 'Refactoring > Change Method Signature' 2. Press 'Add'. A new line added, table cursor set to first field 3a. Press 'TAB'. The focus goes to the field. Press 'TAB' again: The add button gets the focus I would expect that the first TAB sets the table cursor to the next cell. 3b. Press 'cursor right'. Nothing happens. Press Enter first, press 'cursor right'. The next field gets the focus I would expect the first cursor right to focus on the next cell. 4b. With the next cell in focus, start typing. Nothing happens. Press Enter first, then you can type I would expect that entering should be possible right away.
|
resolved fixed
|
7f9d24d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T18:21:49Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui/ui
| |
46,926 |
Bug 46926 Editable Table: Key-navigation is bad [refactoring] [misc]
|
20031119 My expectations for table navigation and usages come from windows applications like MS Excel. The eclipse tables are not follow the 'look' but not the 'feel' and are in general very frustarting to use. 1. select a method and choose 'Refactoring > Change Method Signature' 2. Press 'Add'. A new line added, table cursor set to first field 3a. Press 'TAB'. The focus goes to the field. Press 'TAB' again: The add button gets the focus I would expect that the first TAB sets the table cursor to the next cell. 3b. Press 'cursor right'. Nothing happens. Press Enter first, press 'cursor right'. The next field gets the focus I would expect the first cursor right to focus on the next cell. 4b. With the next cell in focus, start typing. Nothing happens. Press Enter first, then you can type I would expect that entering should be possible right away.
|
resolved fixed
|
7f9d24d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T18:21:49Z | 2003-11-19T11:06:40Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeParametersControl.java
| |
46,926 |
Bug 46926 Editable Table: Key-navigation is bad [refactoring] [misc]
|
20031119 My expectations for table navigation and usages come from windows applications like MS Excel. The eclipse tables are not follow the 'look' but not the 'feel' and are in general very frustarting to use. 1. select a method and choose 'Refactoring > Change Method Signature' 2. Press 'Add'. A new line added, table cursor set to first field 3a. Press 'TAB'. The focus goes to the field. Press 'TAB' again: The add button gets the focus I would expect that the first TAB sets the table cursor to the next cell. 3b. Press 'cursor right'. Nothing happens. Press Enter first, press 'cursor right'. The next field gets the focus I would expect the first cursor right to focus on the next cell. 4b. With the next cell in focus, start typing. Nothing happens. Press Enter first, then you can type I would expect that entering should be possible right away.
|
resolved fixed
|
7f9d24d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T18:21:49Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui/ui
| |
46,926 |
Bug 46926 Editable Table: Key-navigation is bad [refactoring] [misc]
|
20031119 My expectations for table navigation and usages come from windows applications like MS Excel. The eclipse tables are not follow the 'look' but not the 'feel' and are in general very frustarting to use. 1. select a method and choose 'Refactoring > Change Method Signature' 2. Press 'Add'. A new line added, table cursor set to first field 3a. Press 'TAB'. The focus goes to the field. Press 'TAB' again: The add button gets the focus I would expect that the first TAB sets the table cursor to the next cell. 3b. Press 'cursor right'. Nothing happens. Press Enter first, press 'cursor right'. The next field gets the focus I would expect the first cursor right to focus on the next cell. 4b. With the next cell in focus, start typing. Nothing happens. Press Enter first, then you can type I would expect that entering should be possible right away.
|
resolved fixed
|
7f9d24d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T18:21:49Z | 2003-11-19T11:06:40Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeSignatureWizard.java
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/initializer_in/A_test1000.java
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/initializer_in/A_test1001.java
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/initializer_in/A_test1002.java
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/initializer_in/A_test1003.java
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/initializer_out/A_test1000.java
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/initializer_out/A_test1001.java
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/initializer_out/A_test1002.java
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/initializer_out/A_test1003.java
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTestSetup.java
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTests.java
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
org.eclipse.jdt.ui/core
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
extension/org/eclipse/jdt/internal/corext/dom/ASTNodes.java
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
org.eclipse.jdt.ui/core
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
extension/org/eclipse/jdt/internal/corext/dom/LocalVariableIndex.java
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
org.eclipse.jdt.ui/core
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExceptionAnalyzer.java
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
org.eclipse.jdt.ui/core
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodAnalyzer.java
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
org.eclipse.jdt.ui/core
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodRefactoring.java
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
org.eclipse.jdt.ui/core
| |
39,155 |
Bug 39155 Extract method in static initialisers [refactoring]
|
I got this: static { // do something } I want this: static { methodCall(); } private static void methodCall() { // do something }
|
resolved fixed
|
1728d83
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-15T19:45:55Z | 2003-06-20T06:20:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/LocalTypeAnalyzer.java
| |
48,868 |
Bug 48868 New compiler preference: Overriding Deprecated Method
|
20011216 Added option to avoid reporting a warning when overriding a deprecated method. By default, such warnings are no longer reported. * COMPILER / Reporting Deprecation When Overriding Deprecated Method * When enabled, the compiler will signal the declaration of a method overriding a deprecated one. * The severity of the problem is controlled with option "org.eclipse.jdt.core.compiler.problem.deprecation". * - option id: "org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod" * - possible values: { "enabled", "disabled" } * - default: "disabled"
|
resolved fixed
|
4aef2f0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-16T16:22:00Z | 2003-12-16T15:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CompilerConfigurationBlock.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.Arrays;
import java.util.Map;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
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.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.util.TabFolderLayout;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
/**
*/
public class CompilerConfigurationBlock extends OptionsConfigurationBlock {
// Preference store keys, see JavaCore.getOptions
private static final String PREF_LOCAL_VARIABLE_ATTR= JavaCore.COMPILER_LOCAL_VARIABLE_ATTR;
private static final String PREF_LINE_NUMBER_ATTR= JavaCore.COMPILER_LINE_NUMBER_ATTR;
private static final String PREF_SOURCE_FILE_ATTR= JavaCore.COMPILER_SOURCE_FILE_ATTR;
private static final String PREF_CODEGEN_UNUSED_LOCAL= JavaCore.COMPILER_CODEGEN_UNUSED_LOCAL;
private static final String PREF_CODEGEN_TARGET_PLATFORM= JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM;
//private static final String PREF_PB_UNREACHABLE_CODE= JavaCore.COMPILER_PB_UNREACHABLE_CODE;
//private static final String PREF_PB_INVALID_IMPORT= JavaCore.COMPILER_PB_INVALID_IMPORT;
private static final String PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD= JavaCore.COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD;
private static final String PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME= JavaCore.COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME;
private static final String PREF_PB_DEPRECATION= JavaCore.COMPILER_PB_DEPRECATION;
private static final String PREF_PB_HIDDEN_CATCH_BLOCK= JavaCore.COMPILER_PB_HIDDEN_CATCH_BLOCK;
private static final String PREF_PB_UNUSED_LOCAL= JavaCore.COMPILER_PB_UNUSED_LOCAL;
private static final String PREF_PB_UNUSED_PARAMETER= JavaCore.COMPILER_PB_UNUSED_PARAMETER;
private static final String PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING= JavaCore.COMPILER_PB_UNUSED_PARAMETER_WHEN_OVERRIDING_CONCRETE;
private static final String PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT= JavaCore.COMPILER_PB_UNUSED_PARAMETER_WHEN_IMPLEMENTING_ABSTRACT;
private static final String PREF_PB_SYNTHETIC_ACCESS_EMULATION= JavaCore.COMPILER_PB_SYNTHETIC_ACCESS_EMULATION;
private static final String PREF_PB_NON_EXTERNALIZED_STRINGS= JavaCore.COMPILER_PB_NON_NLS_STRING_LITERAL;
private static final String PREF_PB_ASSERT_AS_IDENTIFIER= JavaCore.COMPILER_PB_ASSERT_IDENTIFIER;
private static final String PREF_PB_MAX_PER_UNIT= JavaCore.COMPILER_PB_MAX_PER_UNIT;
private static final String PREF_PB_UNUSED_IMPORT= JavaCore.COMPILER_PB_UNUSED_IMPORT;
private static final String PREF_PB_UNUSED_PRIVATE= JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER;
private static final String PREF_PB_STATIC_ACCESS_RECEIVER= JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER;
private static final String PREF_PB_NO_EFFECT_ASSIGNMENT= JavaCore.COMPILER_PB_NO_EFFECT_ASSIGNMENT;
private static final String PREF_PB_CHAR_ARRAY_IN_CONCAT= JavaCore.COMPILER_PB_CHAR_ARRAY_IN_STRING_CONCATENATION;
private static final String PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT= JavaCore.COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT;
private static final String PREF_PB_LOCAL_VARIABLE_HIDING= JavaCore.COMPILER_PB_LOCAL_VARIABLE_HIDING;
private static final String PREF_PB_FIELD_HIDING= JavaCore.COMPILER_PB_FIELD_HIDING;
private static final String PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD= JavaCore.COMPILER_PB_SPECIAL_PARAMETER_HIDING_FIELD;
private static final String PREF_PB_INDIRECT_STATIC_ACCESS= JavaCore.COMPILER_PB_INDIRECT_STATIC_ACCESS;
private static final String PREF_PB_SUPERFLUOUS_SEMICOLON= JavaCore.COMPILER_PB_SUPERFLUOUS_SEMICOLON;
private static final String PREF_PB_UNNECESSARY_TYPE_CHECK= JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK;
private static final String PREF_PB_INVALID_JAVADOC= JavaCore.COMPILER_PB_INVALID_JAVADOC;
private static final String PREF_PB_INVALID_JAVADOC_TAGS= JavaCore.COMPILER_PB_INVALID_JAVADOC_TAGS;
private static final String PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY= JavaCore.COMPILER_PB_INVALID_JAVADOC_TAGS_VISIBILITY;
private static final String PREF_PB_MISSING_JAVADOC_TAGS= JavaCore.COMPILER_PB_MISSING_JAVADOC_TAGS;
private static final String PREF_PB_MISSING_JAVADOC_TAGS_VISIBILITY= JavaCore.COMPILER_PB_MISSING_JAVADOC_TAGS_VISIBILITY;
private static final String PREF_PB_MISSING_JAVADOC_TAGS_OVERRIDING= JavaCore.COMPILER_PB_MISSING_JAVADOC_TAGS_OVERRIDING;
private static final String PREF_PB_MISSING_JAVADOC_COMMENTS= JavaCore.COMPILER_PB_MISSING_JAVADOC_COMMENTS;
private static final String PREF_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY= JavaCore.COMPILER_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY;
private static final String PREF_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING= JavaCore.COMPILER_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING;
private static final String PREF_SOURCE_COMPATIBILITY= JavaCore.COMPILER_SOURCE;
private static final String PREF_COMPLIANCE= JavaCore.COMPILER_COMPLIANCE;
private static final String PREF_RESOURCE_FILTER= JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER;
private static final String PREF_BUILD_INVALID_CLASSPATH= JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH;
private static final String PREF_BUILD_CLEAN_OUTPUT_FOLDER= JavaCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER;
private static final String PREF_ENABLE_EXCLUSION_PATTERNS= JavaCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS;
private static final String PREF_ENABLE_MULTIPLE_OUTPUT_LOCATIONS= JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS;
private static final String PREF_PB_INCOMPLETE_BUILDPATH= JavaCore.CORE_INCOMPLETE_CLASSPATH;
private static final String PREF_PB_CIRCULAR_BUILDPATH= JavaCore.CORE_CIRCULAR_CLASSPATH;
private static final String PREF_PB_INCOMPATIBLE_JDK_LEVEL= JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL;
private static final String PREF_PB_DEPRECATION_IN_DEPRECATED_CODE= JavaCore.COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE;
private static final String PREF_PB_DUPLICATE_RESOURCE= JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE;
private static final String PREF_PB_INCOMPATIBLE_INTERFACE_METHOD= JavaCore.COMPILER_PB_INCOMPATIBLE_NON_INHERITED_INTERFACE_METHOD;
private static final String PREF_PB_UNDOCUMENTED_EMPTY_BLOCK= JavaCore.COMPILER_PB_UNDOCUMENTED_EMPTY_BLOCK;
private static final String PREF_PB_FINALLY_BLOCK_NOT_COMPLETING= JavaCore.COMPILER_PB_FINALLY_BLOCK_NOT_COMPLETING;
private static final String PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION= JavaCore.COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION;
private static final String PREF_PB_UNQUALIFIED_FIELD_ACCESS= JavaCore.COMPILER_PB_UNQUALIFIED_FIELD_ACCESS;
private static final String INTR_DEFAULT_COMPLIANCE= "internal.default.compliance"; //$NON-NLS-1$
// values
private static final String GENERATE= JavaCore.GENERATE;
private static final String DO_NOT_GENERATE= JavaCore.DO_NOT_GENERATE;
private static final String PRESERVE= JavaCore.PRESERVE;
private static final String OPTIMIZE_OUT= JavaCore.OPTIMIZE_OUT;
private static final String VERSION_1_1= JavaCore.VERSION_1_1;
private static final String VERSION_1_2= JavaCore.VERSION_1_2;
private static final String VERSION_1_3= JavaCore.VERSION_1_3;
private static final String VERSION_1_4= JavaCore.VERSION_1_4;
private static final String ERROR= JavaCore.ERROR;
private static final String WARNING= JavaCore.WARNING;
private static final String IGNORE= JavaCore.IGNORE;
private static final String ABORT= JavaCore.ABORT;
private static final String CLEAN= JavaCore.CLEAN;
private static final String ENABLED= JavaCore.ENABLED;
private static final String DISABLED= JavaCore.DISABLED;
private static final String PUBLIC= JavaCore.PUBLIC;
private static final String PROTECTED= JavaCore.PROTECTED;
private static final String DEFAULT= JavaCore.DEFAULT;
private static final String PRIVATE= JavaCore.PRIVATE;
private static final String DEFAULT_CONF= "default"; //$NON-NLS-1$
private static final String USER_CONF= "user"; //$NON-NLS-1$
private ArrayList fComplianceControls;
private PixelConverter fPixelConverter;
private IStatus fComplianceStatus, fMaxNumberProblemsStatus, fResourceFilterStatus;
public CompilerConfigurationBlock(IStatusChangeListener context, IJavaProject project) {
super(context, project);
fComplianceControls= new ArrayList();
fComplianceStatus= new StatusInfo();
fMaxNumberProblemsStatus= new StatusInfo();
fResourceFilterStatus= new StatusInfo();
}
private final String[] KEYS= new String[] {
PREF_LOCAL_VARIABLE_ATTR, PREF_LINE_NUMBER_ATTR, PREF_SOURCE_FILE_ATTR, PREF_CODEGEN_UNUSED_LOCAL,
PREF_CODEGEN_TARGET_PLATFORM, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD,
PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, PREF_PB_DEPRECATION, PREF_PB_HIDDEN_CATCH_BLOCK, PREF_PB_UNUSED_LOCAL,
PREF_PB_UNUSED_PARAMETER, PREF_PB_SYNTHETIC_ACCESS_EMULATION, PREF_PB_NON_EXTERNALIZED_STRINGS,
PREF_PB_ASSERT_AS_IDENTIFIER, PREF_PB_UNUSED_IMPORT, PREF_PB_MAX_PER_UNIT, PREF_SOURCE_COMPATIBILITY, PREF_COMPLIANCE,
PREF_RESOURCE_FILTER, PREF_BUILD_INVALID_CLASSPATH, PREF_PB_STATIC_ACCESS_RECEIVER, PREF_PB_INCOMPLETE_BUILDPATH,
PREF_PB_CIRCULAR_BUILDPATH, PREF_PB_DEPRECATION_IN_DEPRECATED_CODE, PREF_BUILD_CLEAN_OUTPUT_FOLDER,
PREF_PB_DUPLICATE_RESOURCE, PREF_PB_NO_EFFECT_ASSIGNMENT, PREF_PB_INCOMPATIBLE_INTERFACE_METHOD,
PREF_PB_UNUSED_PRIVATE, PREF_PB_CHAR_ARRAY_IN_CONCAT, PREF_ENABLE_EXCLUSION_PATTERNS, PREF_ENABLE_MULTIPLE_OUTPUT_LOCATIONS,
PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT, PREF_PB_LOCAL_VARIABLE_HIDING, PREF_PB_FIELD_HIDING,
PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD, PREF_PB_INCOMPATIBLE_JDK_LEVEL, PREF_PB_INDIRECT_STATIC_ACCESS,
PREF_PB_SUPERFLUOUS_SEMICOLON, PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING, PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT,
PREF_PB_UNNECESSARY_TYPE_CHECK, PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION, PREF_PB_UNQUALIFIED_FIELD_ACCESS,
PREF_PB_UNDOCUMENTED_EMPTY_BLOCK, PREF_PB_FINALLY_BLOCK_NOT_COMPLETING,
PREF_PB_INVALID_JAVADOC, PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY, PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY,
PREF_PB_MISSING_JAVADOC_TAGS, PREF_PB_MISSING_JAVADOC_TAGS_VISIBILITY, PREF_PB_MISSING_JAVADOC_TAGS_OVERRIDING,
PREF_PB_MISSING_JAVADOC_COMMENTS, PREF_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY, PREF_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING
};
protected String[] getAllKeys() {
return KEYS;
}
protected final Map getOptions(boolean inheritJavaCoreOptions) {
Map map= super.getOptions(inheritJavaCoreOptions);
map.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance(map));
return map;
}
protected final Map getDefaultOptions() {
Map map= super.getDefaultOptions();
map.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance(map));
return map;
}
/*
* @see org.eclipse.jface.preference.PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
fPixelConverter= new PixelConverter(parent);
setShell(parent.getShell());
TabFolder folder= new TabFolder(parent, SWT.NONE);
folder.setLayout(new TabFolderLayout());
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite commonComposite= createStyleTabContent(folder);
Composite unusedComposite= createUnusedCodeTabContent(folder);
Composite advancedComposite= createAdvancedTabContent(folder);
Composite javadocComposite= createJavadocTabContent(folder);
Composite complianceComposite= createComplianceTabContent(folder);
Composite othersComposite= createBuildPathTabContent(folder);
TabItem item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.common.tabtitle")); //$NON-NLS-1$
item.setControl(commonComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.advanced.tabtitle")); //$NON-NLS-1$
item.setControl(advancedComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.unused.tabtitle")); //$NON-NLS-1$
item.setControl(unusedComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.javadoc.tabtitle")); //$NON-NLS-1$
item.setControl(javadocComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.compliance.tabtitle")); //$NON-NLS-1$
item.setControl(complianceComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.others.tabtitle")); //$NON-NLS-1$
item.setControl(othersComposite);
validateSettings(null, null);
return folder;
}
private Composite createStyleTabContent(Composite folder) {
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
int nColumns= 3;
GridLayout layout= new GridLayout();
layout.numColumns= nColumns;
Composite composite= new Composite(folder, SWT.NULL);
composite.setLayout(layout);
Label description= new Label(composite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.common.description")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= nColumns;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50);
description.setLayoutData(gd);
String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_overriding_pkg_dflt.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_method_naming.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_hidden_catchblock.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_HIDDEN_CATCH_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_static_access_receiver.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_STATIC_ACCESS_RECEIVER, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_no_effect_assignment.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_NO_EFFECT_ASSIGNMENT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_indirect_access_to_static.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_INDIRECT_STATIC_ACCESS, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_accidential_assignement.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_finally_block_not_completing.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_FINALLY_BLOCK_NOT_COMPLETING, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_undocumented_empty_block.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_UNDOCUMENTED_EMPTY_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels, 0);
return composite;
}
private Composite createAdvancedTabContent(TabFolder folder) {
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
String[] enabledDisabled= new String[] { ENABLED, DISABLED };
int nColumns= 3;
GridLayout layout= new GridLayout();
layout.numColumns= nColumns;
Composite composite= new Composite(folder, SWT.NULL);
composite.setLayout(layout);
Label description= new Label(composite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.advanced.description")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= nColumns;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50);
description.setLayoutData(gd);
String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_synth_access_emul.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_SYNTHETIC_ACCESS_EMULATION, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_local_variable_hiding.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_LOCAL_VARIABLE_HIDING, errorWarningIgnore, errorWarningIgnoreLabels, 0);
int indent= fPixelConverter.convertWidthInCharsToPixels(2);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_special_param_hiding.label"); //$NON-NLS-1$
addCheckBox(composite, label, PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD, enabledDisabled, indent);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_field_hiding.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_FIELD_HIDING, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_non_externalized_strings.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_NON_EXTERNALIZED_STRINGS, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_incompatible_interface_method.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_INCOMPATIBLE_INTERFACE_METHOD, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_char_array_in_concat.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_CHAR_ARRAY_IN_CONCAT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unqualified_field_access.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_UNQUALIFIED_FIELD_ACCESS, errorWarningIgnore, errorWarningIgnoreLabels, 0);
gd= new GridData();
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(6);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_max_per_unit.label"); //$NON-NLS-1$
Text text= addTextField(composite, label, PREF_PB_MAX_PER_UNIT, 0, 0);
text.setTextLimit(6);
text.setLayoutData(gd);
return composite;
}
private Composite createUnusedCodeTabContent(TabFolder folder) {
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
String[] enabledDisabled= new String[] { ENABLED, DISABLED };
int nColumns= 3;
GridLayout layout= new GridLayout();
layout.numColumns= nColumns;
Composite composite= new Composite(folder, SWT.NULL);
composite.setLayout(layout);
Label description= new Label(composite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.unused.description")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= nColumns;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50);
description.setLayoutData(gd);
String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_local.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_UNUSED_LOCAL, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_parameter.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_UNUSED_PARAMETER, errorWarningIgnore, errorWarningIgnoreLabels, 0);
int indent= fPixelConverter.convertWidthInCharsToPixels(2);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_signal_param_in_overriding.label"); //$NON-NLS-1$
addCheckBox(composite, label, PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING, enabledDisabled, indent);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_signal_param_in_abstract.label"); //$NON-NLS-1$
addCheckBox(composite, label, PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT, enabledDisabled, indent);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_imports.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_UNUSED_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_private.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_UNUSED_PRIVATE, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_deprecation.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_DEPRECATION, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_deprecation_in_deprecation.label"); //$NON-NLS-1$
addCheckBox(composite, label, PREF_PB_DEPRECATION_IN_DEPRECATED_CODE, enabledDisabled, indent);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_superfluous_semicolon.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_SUPERFLUOUS_SEMICOLON, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unnecessary_type_check.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_UNNECESSARY_TYPE_CHECK, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_throwing_exception.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION, errorWarningIgnore, errorWarningIgnoreLabels, 0);
return composite;
}
private Composite createJavadocTabContent(TabFolder folder) {
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
String[] enabledDisabled= new String[] { ENABLED, DISABLED };
String[] visibilities= new String[] { PUBLIC, PROTECTED, DEFAULT, PRIVATE };
String[] visibilitiesLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.public"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.protected"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.default"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.private") //$NON-NLS-1$
};
int nColumns= 3;
/*
* COMPILER_PB_INVALID_JAVADOC: "ignore", "warning", "error"
COMPILER_PB_INVALID_JAVADOC_TAGS: "enabled", "disabled"
COMPILER_PB_INVALID_JAVADOC_TAGS_VISIBILITY: "public", "protected", "default", "private"
COMPILER_PB_MISSING_JAVADOC_TAGS: "ignore", "warning", "error"
COMPILER_PB_MISSING_JAVADOC_TAGS_VISIBILITY: "public", "protected", "default", "private"
COMPILER_PB_MISSING_JAVADOC_TAGS_OVERRIDING: "enabled", "disabled"
COMPILER_PB_MISSING_JAVADOC_COMMENTS: "ignore", "warning", "error"
COMPILER_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY: "public", "protected", "default", "private"
COMPILER_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING: "enabled", "disabled"
*/
// GridLayout layout = new GridLayout();
// layout.numColumns= nColumns;
//
// Composite composite= new Composite(folder, SWT.NULL);
// composite.setLayout(layout);
//
// Label description= new Label(composite, SWT.WRAP);
// description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.javadoc.description")); //$NON-NLS-1$
// GridData gd= new GridData();
// gd.horizontalSpan= nColumns;
// gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50);
// description.setLayoutData(gd);
GridLayout layout = new GridLayout();
layout.numColumns= nColumns;
Composite composite= new Composite(folder, SWT.NULL);
composite.setLayout(layout);
Label description= new Label(composite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.javadoc.description")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= nColumns;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50);
description.setLayoutData(gd);
int indent= fPixelConverter.convertWidthInCharsToPixels(2);
String label = PreferencesMessages.getString("CompilerConfigurationBlock.pb_missing_comments.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_MISSING_JAVADOC_COMMENTS, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label = PreferencesMessages.getString("CompilerConfigurationBlock.pb_missing_comments_visibility.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY, visibilities, visibilitiesLabels, indent);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_missing_comments_overriding.label"); //$NON-NLS-1$
addCheckBox(composite, label, PREF_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING, enabledDisabled, indent);
Label separator= new Label(composite, SWT.HORIZONTAL);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns;
separator.setLayoutData(gd);
label = PreferencesMessages.getString("CompilerConfigurationBlock.pb_missing_javadoc.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_MISSING_JAVADOC_TAGS, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label = PreferencesMessages.getString("CompilerConfigurationBlock.pb_missing_javadoc_tags_visibility.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_MISSING_JAVADOC_TAGS_VISIBILITY, visibilities, visibilitiesLabels, indent);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_missing_javadoc_tags_overriding.label"); //$NON-NLS-1$
addCheckBox(composite, label, PREF_PB_MISSING_JAVADOC_TAGS_OVERRIDING, enabledDisabled, indent);
separator= new Label(composite, SWT.HORIZONTAL);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns;
separator.setLayoutData(gd);
label = PreferencesMessages.getString("CompilerConfigurationBlock.pb_invalid_javadoc.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_INVALID_JAVADOC, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label = PreferencesMessages.getString("CompilerConfigurationBlock.pb_invalid_javadoc_tags_visibility.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY, visibilities, visibilitiesLabels, indent);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_invalid_javadoc_tags.label"); //$NON-NLS-1$
addCheckBox(composite, label, PREF_PB_INVALID_JAVADOC_TAGS, enabledDisabled, indent);
return composite;
}
private Composite createBuildPathTabContent(TabFolder folder) {
String[] abortIgnoreValues= new String[] { ABORT, IGNORE };
String[] cleanIgnoreValues= new String[] { CLEAN, IGNORE };
String[] enableDisableValues= new String[] { ENABLED, DISABLED };
String[] errorWarning= new String[] { ERROR, WARNING };
String[] errorWarningLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning") //$NON-NLS-1$
};
int nColumns= 3;
GridLayout layout= new GridLayout();
layout.numColumns= nColumns;
Composite othersComposite= new Composite(folder, SWT.NULL);
othersComposite.setLayout(layout);
Label description= new Label(othersComposite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.build_warnings.description")); //$NON-NLS-1$
GridData gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
gd.horizontalSpan= nColumns;
description.setLayoutData(gd);
String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_incomplete_build_path.label"); //$NON-NLS-1$
addComboBox(othersComposite, label, PREF_PB_INCOMPLETE_BUILDPATH, errorWarning, errorWarningLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_build_path_cycles.label"); //$NON-NLS-1$
addComboBox(othersComposite, label, PREF_PB_CIRCULAR_BUILDPATH, errorWarning, errorWarningLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_duplicate_resources.label"); //$NON-NLS-1$
addComboBox(othersComposite, label, PREF_PB_DUPLICATE_RESOURCE, errorWarning, errorWarningLabels, 0);
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_check_prereq_binary_level.label"); //$NON-NLS-1$
addComboBox(othersComposite, label, PREF_PB_INCOMPATIBLE_JDK_LEVEL, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.build_invalid_classpath.label"); //$NON-NLS-1$
addCheckBox(othersComposite, label, PREF_BUILD_INVALID_CLASSPATH, abortIgnoreValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.build_clean_outputfolder.label"); //$NON-NLS-1$
addCheckBox(othersComposite, label, PREF_BUILD_CLEAN_OUTPUT_FOLDER, cleanIgnoreValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.enable_exclusion_patterns.label"); //$NON-NLS-1$
addCheckBox(othersComposite, label, PREF_ENABLE_EXCLUSION_PATTERNS, enableDisableValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.enable_multiple_outputlocations.label"); //$NON-NLS-1$
addCheckBox(othersComposite, label, PREF_ENABLE_MULTIPLE_OUTPUT_LOCATIONS, enableDisableValues, 0);
description= new Label(othersComposite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.resource_filter.description")); //$NON-NLS-1$
gd= new GridData(GridData.FILL);
gd.horizontalSpan= nColumns;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(60);
description.setLayoutData(gd);
label= PreferencesMessages.getString("CompilerConfigurationBlock.resource_filter.label"); //$NON-NLS-1$
Text text= addTextField(othersComposite, label, PREF_RESOURCE_FILTER, 0, 0);
gd= (GridData) text.getLayoutData();
gd.grabExcessHorizontalSpace= true;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(10);
return othersComposite;
}
private Composite createComplianceTabContent(Composite folder) {
GridLayout layout= new GridLayout();
layout.numColumns= 1;
String[] values34= new String[] { VERSION_1_3, VERSION_1_4 };
String[] values34Labels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.version13"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.version14") //$NON-NLS-1$
};
Composite compComposite= new Composite(folder, SWT.NULL);
compComposite.setLayout(layout);
int nColumns= 3;
layout= new GridLayout();
layout.numColumns= nColumns;
Group group= new Group(compComposite, SWT.NONE);
group.setText(PreferencesMessages.getString("CompilerConfigurationBlock.compliance.group.label")); //$NON-NLS-1$
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setLayout(layout);
String label= PreferencesMessages.getString("CompilerConfigurationBlock.compiler_compliance.label"); //$NON-NLS-1$
addComboBox(group, label, PREF_COMPLIANCE, values34, values34Labels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.default_settings.label"); //$NON-NLS-1$
addCheckBox(group, label, INTR_DEFAULT_COMPLIANCE, new String[] { DEFAULT_CONF, USER_CONF }, 0);
int indent= fPixelConverter.convertWidthInCharsToPixels(2);
Control[] otherChildren= group.getChildren();
String[] values14= new String[] { VERSION_1_1, VERSION_1_2, VERSION_1_3, VERSION_1_4 };
String[] values14Labels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.version11"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.version12"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.version13"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.version14") //$NON-NLS-1$
};
label= PreferencesMessages.getString("CompilerConfigurationBlock.codegen_targetplatform.label"); //$NON-NLS-1$
addComboBox(group, label, PREF_CODEGEN_TARGET_PLATFORM, values14, values14Labels, indent);
label= PreferencesMessages.getString("CompilerConfigurationBlock.source_compatibility.label"); //$NON-NLS-1$
addComboBox(group, label, PREF_SOURCE_COMPATIBILITY, values34, values34Labels, indent);
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_assert_as_identifier.label"); //$NON-NLS-1$
addComboBox(group, label, PREF_PB_ASSERT_AS_IDENTIFIER, errorWarningIgnore, errorWarningIgnoreLabels, indent);
Control[] allChildren= group.getChildren();
fComplianceControls.addAll(Arrays.asList(allChildren));
fComplianceControls.removeAll(Arrays.asList(otherChildren));
layout= new GridLayout();
layout.numColumns= nColumns;
group= new Group(compComposite, SWT.NONE);
group.setText(PreferencesMessages.getString("CompilerConfigurationBlock.classfiles.group.label")); //$NON-NLS-1$
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setLayout(layout);
String[] generateValues= new String[] { GENERATE, DO_NOT_GENERATE };
label= PreferencesMessages.getString("CompilerConfigurationBlock.variable_attr.label"); //$NON-NLS-1$
addCheckBox(group, label, PREF_LOCAL_VARIABLE_ATTR, generateValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.line_number_attr.label"); //$NON-NLS-1$
addCheckBox(group, label, PREF_LINE_NUMBER_ATTR, generateValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.source_file_attr.label"); //$NON-NLS-1$
addCheckBox(group, label, PREF_SOURCE_FILE_ATTR, generateValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.codegen_unused_local.label"); //$NON-NLS-1$
addCheckBox(group, label, PREF_CODEGEN_UNUSED_LOCAL, new String[] { PRESERVE, OPTIMIZE_OUT }, 0);
return compComposite;
}
/* (non-javadoc)
* Update fields and validate.
* @param changedKey Key that changed, or null, if all changed.
*/
protected void validateSettings(String changedKey, String newValue) {
if (changedKey != null) {
if (INTR_DEFAULT_COMPLIANCE.equals(changedKey)) {
updateComplianceEnableState();
if (DEFAULT_CONF.equals(newValue)) {
updateComplianceDefaultSettings();
}
fComplianceStatus= validateCompliance();
} else if (PREF_COMPLIANCE.equals(changedKey)) {
if (checkValue(INTR_DEFAULT_COMPLIANCE, DEFAULT_CONF)) {
updateComplianceDefaultSettings();
}
fComplianceStatus= validateCompliance();
} else if (PREF_SOURCE_COMPATIBILITY.equals(changedKey) ||
PREF_CODEGEN_TARGET_PLATFORM.equals(changedKey) ||
PREF_PB_ASSERT_AS_IDENTIFIER.equals(changedKey)) {
fComplianceStatus= validateCompliance();
} else if (PREF_PB_MAX_PER_UNIT.equals(changedKey)) {
fMaxNumberProblemsStatus= validateMaxNumberProblems();
} else if (PREF_RESOURCE_FILTER.equals(changedKey)) {
fResourceFilterStatus= validateResourceFilters();
} else if (PREF_PB_UNUSED_PARAMETER.equals(changedKey) ||
PREF_PB_DEPRECATION.equals(changedKey) ||
PREF_PB_INVALID_JAVADOC.equals(changedKey) ||
PREF_PB_MISSING_JAVADOC_TAGS.equals(changedKey) ||
PREF_PB_MISSING_JAVADOC_COMMENTS.equals(changedKey) ||
PREF_PB_LOCAL_VARIABLE_HIDING.equals(changedKey)) {
updateEnableStates();
} else {
return;
}
} else {
updateEnableStates();
updateComplianceEnableState();
fComplianceStatus= validateCompliance();
fMaxNumberProblemsStatus= validateMaxNumberProblems();
fResourceFilterStatus= validateResourceFilters();
}
IStatus status= StatusUtil.getMostSevere(new IStatus[] { fComplianceStatus, fMaxNumberProblemsStatus, fResourceFilterStatus });
fContext.statusChanged(status);
}
private void updateEnableStates() {
boolean enableUnusedParams= !checkValue(PREF_PB_UNUSED_PARAMETER, IGNORE);
getCheckBox(PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING).setEnabled(enableUnusedParams);
getCheckBox(PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT).setEnabled(enableUnusedParams);
boolean enableDeprecation= !checkValue(PREF_PB_DEPRECATION, IGNORE);
getCheckBox(PREF_PB_DEPRECATION_IN_DEPRECATED_CODE).setEnabled(enableDeprecation);
boolean enableHiding= !checkValue(PREF_PB_LOCAL_VARIABLE_HIDING, IGNORE);
getCheckBox(PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD).setEnabled(enableHiding);
boolean enableInvalidTagsErrors= !checkValue(PREF_PB_INVALID_JAVADOC, IGNORE);
getCheckBox(PREF_PB_INVALID_JAVADOC_TAGS).setEnabled(enableInvalidTagsErrors);
setComboEnabled(PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY, enableInvalidTagsErrors);
boolean enableMissingTagsErrors= !checkValue(PREF_PB_MISSING_JAVADOC_TAGS, IGNORE);
getCheckBox(PREF_PB_MISSING_JAVADOC_TAGS_OVERRIDING).setEnabled(enableMissingTagsErrors);
setComboEnabled(PREF_PB_MISSING_JAVADOC_TAGS_VISIBILITY, enableMissingTagsErrors);
boolean enableMissingCommentsErrors= !checkValue(PREF_PB_MISSING_JAVADOC_COMMENTS, IGNORE);
getCheckBox(PREF_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING).setEnabled(enableMissingCommentsErrors);
setComboEnabled(PREF_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY, enableMissingCommentsErrors);
}
private IStatus validateCompliance() {
StatusInfo status= new StatusInfo();
if (checkValue(PREF_COMPLIANCE, VERSION_1_3)) {
if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.cpl13src14.error")); //$NON-NLS-1$
return status;
} else if (checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.cpl13trg14.error")); //$NON-NLS-1$
return status;
}
}
if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) {
if (!checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR)) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.src14asrterr.error")); //$NON-NLS-1$
return status;
}
}
if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) {
if (!checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.src14tgt14.error")); //$NON-NLS-1$
return status;
}
}
return status;
}
private IStatus validateMaxNumberProblems() {
String number= (String) fWorkingValues.get(PREF_PB_MAX_PER_UNIT);
StatusInfo status= new StatusInfo();
if (number.length() == 0) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.empty_input")); //$NON-NLS-1$
} else {
try {
int value= Integer.parseInt(number);
if (value <= 0) {
status.setError(PreferencesMessages.getFormattedString("CompilerConfigurationBlock.invalid_input", number)); //$NON-NLS-1$
}
} catch (NumberFormatException e) {
status.setError(PreferencesMessages.getFormattedString("CompilerConfigurationBlock.invalid_input", number)); //$NON-NLS-1$
}
}
return status;
}
private IStatus validateResourceFilters() {
String text= (String) fWorkingValues.get(PREF_RESOURCE_FILTER);
IWorkspace workspace= ResourcesPlugin.getWorkspace();
String[] filters= getTokens(text, ","); //$NON-NLS-1$
for (int i= 0; i < filters.length; i++) {
String fileName= filters[i].replace('*', 'x');
int resourceType= IResource.FILE;
int lastCharacter= fileName.length() - 1;
if (lastCharacter >= 0 && fileName.charAt(lastCharacter) == '/') {
fileName= fileName.substring(0, lastCharacter);
resourceType= IResource.FOLDER;
}
IStatus status= workspace.validateName(fileName, resourceType);
if (status.matches(IStatus.ERROR)) {
String message= PreferencesMessages.getFormattedString("CompilerConfigurationBlock.filter.invalidsegment.error", status.getMessage()); //$NON-NLS-1$
return new StatusInfo(IStatus.ERROR, message);
}
}
return new StatusInfo();
}
/*
* Update the compliance controls' enable state
*/
private void updateComplianceEnableState() {
boolean enabled= checkValue(INTR_DEFAULT_COMPLIANCE, USER_CONF);
for (int i= fComplianceControls.size() - 1; i >= 0; i--) {
Control curr= (Control) fComplianceControls.get(i);
curr.setEnabled(enabled);
}
}
/*
* Set the default compliance values derived from the chosen level
*/
private void updateComplianceDefaultSettings() {
Object complianceLevel= fWorkingValues.get(PREF_COMPLIANCE);
if (VERSION_1_3.equals(complianceLevel)) {
fWorkingValues.put(PREF_PB_ASSERT_AS_IDENTIFIER, IGNORE);
fWorkingValues.put(PREF_SOURCE_COMPATIBILITY, VERSION_1_3);
fWorkingValues.put(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_1);
} else if (VERSION_1_4.equals(complianceLevel)) {
fWorkingValues.put(PREF_PB_ASSERT_AS_IDENTIFIER, WARNING);
fWorkingValues.put(PREF_SOURCE_COMPATIBILITY, VERSION_1_3);
fWorkingValues.put(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_2);
}
updateControls();
}
/*
* Evaluate if the current compliance setting correspond to a default setting
*/
private static String getCurrentCompliance(Map map) {
Object complianceLevel= map.get(PREF_COMPLIANCE);
if ((VERSION_1_3.equals(complianceLevel)
&& IGNORE.equals(map.get(PREF_PB_ASSERT_AS_IDENTIFIER))
&& VERSION_1_3.equals(map.get(PREF_SOURCE_COMPATIBILITY))
&& VERSION_1_1.equals(map.get(PREF_CODEGEN_TARGET_PLATFORM)))
|| (VERSION_1_4.equals(complianceLevel)
&& WARNING.equals(map.get(PREF_PB_ASSERT_AS_IDENTIFIER))
&& VERSION_1_3.equals(map.get(PREF_SOURCE_COMPATIBILITY))
&& VERSION_1_2.equals(map.get(PREF_CODEGEN_TARGET_PLATFORM)))) {
return DEFAULT_CONF;
}
return USER_CONF;
}
protected String[] getFullBuildDialogStrings(boolean workspaceSettings) {
String title= PreferencesMessages.getString("CompilerConfigurationBlock.needsbuild.title"); //$NON-NLS-1$
String message;
if (workspaceSettings) {
message= PreferencesMessages.getString("CompilerConfigurationBlock.needsfullbuild.message"); //$NON-NLS-1$
} else {
message= PreferencesMessages.getString("CompilerConfigurationBlock.needsprojectbuild.message"); //$NON-NLS-1$
}
return new String[] { title, message };
}
}
|
48,975 |
Bug 48975 Comment Formatter should compare values using equals()
|
Currently, the preference values are read and compared by reference, which only works in special circumstances.
|
verified fixed
|
988ada7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T10:38:53Z | 2003-12-17T11:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/CommentFormattingContext.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.comment;
import org.eclipse.jface.text.formatter.FormattingContext;
import org.eclipse.jdt.ui.PreferenceConstants;
/**
* Formatting context for the comment formatter.
*
* @since 3.0
*/
public class CommentFormattingContext extends FormattingContext {
/*
* @see org.eclipse.jface.text.formatter.IFormattingContext#getPreferenceKeys()
*/
public String[] getPreferenceKeys() {
return new String[] { PreferenceConstants.FORMATTER_COMMENT_FORMAT, PreferenceConstants.FORMATTER_COMMENT_FORMATHEADER, PreferenceConstants.FORMATTER_COMMENT_FORMATSOURCE, PreferenceConstants.FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION, PreferenceConstants.FORMATTER_COMMENT_INDENTROOTTAGS, PreferenceConstants.FORMATTER_COMMENT_NEWLINEFORPARAMETER, PreferenceConstants.FORMATTER_COMMENT_SEPARATEROOTTAGS, PreferenceConstants.FORMATTER_COMMENT_LINELENGTH, PreferenceConstants.FORMATTER_COMMENT_CLEARBLANKLINES, PreferenceConstants.FORMATTER_COMMENT_FORMATHTML };
}
/*
* @see org.eclipse.jface.text.formatter.IFormattingContext#isBooleanPreference(java.lang.String)
*/
public boolean isBooleanPreference(String key) {
return !key.equals(PreferenceConstants.FORMATTER_COMMENT_LINELENGTH);
}
/*
* @see org.eclipse.jface.text.formatter.IFormattingContext#isIntegerPreference(java.lang.String)
*/
public boolean isIntegerPreference(String key) {
return key.equals(PreferenceConstants.FORMATTER_COMMENT_LINELENGTH);
}
}
|
48,975 |
Bug 48975 Comment Formatter should compare values using equals()
|
Currently, the preference values are read and compared by reference, which only works in special circumstances.
|
verified fixed
|
988ada7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T10:38:53Z | 2003-12-17T11:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/CommentFormattingStrategy.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.comment;
import java.util.LinkedList;
import java.util.Map;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.TypedPosition;
import org.eclipse.jface.text.formatter.ContentFormatter2;
import org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy;
import org.eclipse.jface.text.formatter.FormattingContext;
import org.eclipse.jface.text.formatter.FormattingContextProperties;
import org.eclipse.jface.text.formatter.IFormattingContext;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
/**
* Formatting strategy for general source code comments.
* <p>
* This strategy implements <code>IFormattingStrategyExtension</code>. It
* must be registered with a content formatter implementing <code>IContentFormatterExtension2<code>
* to take effect.
*
* @since 3.0
*/
public class CommentFormattingStrategy extends ContextBasedFormattingStrategy {
/**
* Returns the indentation of the line at the specified offset.
*
* @param document
* Document which owns the line
* @param region
* Comment region which owns the line
* @param offset
* Offset where to determine the indentation
* @return The indentation of the line
*/
public static String getLineIndentation(final IDocument document, final CommentRegion region, final int offset) {
String result= ""; //$NON-NLS-1$
try {
final IRegion line= document.getLineInformationOfOffset(offset);
final int begin= line.getOffset();
final int end= Math.min(offset, line.getOffset() + line.getLength());
boolean useTab= JavaCore.TAB.equals(JavaCore.getOption(JavaCore.FORMATTER_TAB_CHAR));
result= region.stringToIndent(document.get(begin, end - begin), useTab);
} catch (BadLocationException exception) {
// Ignore and return empty
}
return result;
}
/**
* Content formatter with which this formatting strategy has been
* registered
*/
private final ContentFormatter2 fFormatter;
/** Partitions to be formatted by this strategy */
private final LinkedList fPartitions= new LinkedList();
/**
* Creates a new comment formatting strategy.
*
* @param formatter
* The content formatter with which this formatting strategy has
* been registered
* @param viewer
* The source viewer where to apply the formatting strategy
*/
public CommentFormattingStrategy(final ContentFormatter2 formatter, final ISourceViewer viewer) {
super(viewer);
fFormatter= formatter;
}
/*
* @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#format()
*/
public void format() {
super.format();
Assert.isLegal(fPartitions.size() > 0);
final IDocument document= getViewer().getDocument();
final TypedPosition position= (TypedPosition)fPartitions.removeFirst();
try {
final ITypedRegion partition= TextUtilities.getPartition(document, fFormatter.getDocumentPartitioning(), position.getOffset());
final String type= partition.getType();
position.offset= partition.getOffset();
position.length= partition.getLength();
final Map preferences= getPreferences();
final boolean format= preferences.get(PreferenceConstants.FORMATTER_COMMENT_FORMAT) == IPreferenceStore.TRUE;
final boolean header= preferences.get(PreferenceConstants.FORMATTER_COMMENT_FORMATHEADER) == IPreferenceStore.TRUE;
if (format && (header || position.getOffset() != 0 || !type.equals(IJavaPartitions.JAVA_DOC))) {
final CommentRegion region= CommentObjectFactory.createRegion(this, position, TextUtilities.getDefaultLineDelimiter(document));
final String indentation= getLineIndentation(document, region, position.getOffset());
region.format(indentation);
}
} catch (BadLocationException exception) {
// Should not happen
}
}
/*
* @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#formatterStarts(org.eclipse.jface.text.formatter.IFormattingContext)
*/
public void formatterStarts(IFormattingContext context) {
super.formatterStarts(context);
final FormattingContext current= (FormattingContext)context;
fPartitions.addLast(current.getProperty(FormattingContextProperties.CONTEXT_PARTITION));
}
/*
* @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#formatterStops()
*/
public void formatterStops() {
super.formatterStops();
fPartitions.clear();
}
/**
* Returns the content formatter with which this formatting strategy has
* been registered.
*
* @return The content formatter
*/
public final ContentFormatter2 getFormatter() {
return fFormatter;
}
}
|
48,975 |
Bug 48975 Comment Formatter should compare values using equals()
|
Currently, the preference values are read and compared by reference, which only works in special circumstances.
|
verified fixed
|
988ada7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T10:38:53Z | 2003-12-17T11:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/CommentRegion.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.comment;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.GC;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.ConfigurableLineTracker;
import org.eclipse.jface.text.DefaultPositionUpdater;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ILineTracker;
import org.eclipse.jface.text.IPositionUpdater;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.TypedPosition;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jdt.ui.PreferenceConstants;
/**
* Comment region in a source code document.
*
* @since 3.0
*/
public class CommentRegion extends TypedPosition implements IHtmlTagConstants, IBorderAttributes, ICommentAttributes {
/** Position category of comment regions */
protected static final String COMMENT_POSITION_CATEGORY= "__comment_position"; //$NON-NLS-1$
/** Default line prefix length */
public static final int COMMENT_PREFIX_LENGTH= 3;
/** Default range delimiter */
protected static final String COMMENT_RANGE_DELIMITER= " "; //$NON-NLS-1$
/** The borders of this range */
private int fBorders= 0;
/** Should all blank lines be cleared during formatting? */
private final boolean fClear;
/** The line delimiter used in this comment region */
private final String fDelimiter;
/** The document to format */
private final IDocument fDocument;
/** Graphics context for non-monospace fonts */
private final GC fGraphics;
/** The sequence of lines in this comment region */
private final LinkedList fLines= new LinkedList();
/** The sequence of comment ranges in this comment region */
private final LinkedList fRanges= new LinkedList();
/** Is this comment region a single line region? */
private final boolean fSingleLine;
/** The comment formatting strategy for this comment region */
private final CommentFormattingStrategy fStrategy;
/** Number of characters representing tabulator */
private final int fTabs;
/**
* Creates a new comment region.
*
* @param strategy
* The comment formatting strategy used to format this comment
* region
* @param position
* The typed position which forms this comment region
* @param delimiter
* The line delimiter to use in this comment region
*/
protected CommentRegion(final CommentFormattingStrategy strategy, final TypedPosition position, final String delimiter) {
super(position.getOffset(), position.getLength(), position.getType());
fStrategy= strategy;
fDelimiter= delimiter;
fClear= fStrategy.getPreferences().get(PreferenceConstants.FORMATTER_COMMENT_CLEARBLANKLINES) == IPreferenceStore.TRUE;
final ISourceViewer viewer= strategy.getViewer();
final StyledText text= viewer.getTextWidget();
fDocument= viewer.getDocument();
if (text != null && !text.isDisposed()) {
fGraphics= new GC(text);
fGraphics.setFont(text.getFont());
fTabs= text.getTabs();
} else {
fGraphics= null;
fTabs= 4;
}
final ILineTracker tracker= new ConfigurableLineTracker(new String[] { delimiter });
IRegion range= null;
CommentLine line= null;
tracker.set(getText(0, getLength()));
final int lines= tracker.getNumberOfLines();
fSingleLine= lines == 1;
try {
for (int index= 0; index < lines; index++) {
range= tracker.getLineInformation(index);
line= CommentObjectFactory.createLine(this);
line.append(new CommentRange(range.getOffset(), range.getLength()));
fLines.add(line);
}
} catch (BadLocationException exception) {
// Should not happen
}
}
/**
* Appends the comment range to this comment region.
*
* @param range
* Comment range to append to this comment region
*/
protected final void append(final CommentRange range) {
fRanges.addLast(range);
}
/**
* Applies the formatted comment region to the underlying document.
*
* @param indentation
* Indentation of the formatted comment region
* @param width
* The maximal width of text in this comment region measured in
* average character widths
*/
protected void applyRegion(final String indentation, final int width) {
final int last= fLines.size() - 1;
if (last >= 0) {
CommentLine previous= null;
CommentLine next= (CommentLine)fLines.get(last);
CommentRange range= next.getLast();
next.applyEnd(range, indentation, width);
for (int line= last; line >= 0; line--) {
previous= next;
next= (CommentLine)fLines.get(line);
range= next.applyLine(previous, range, indentation, line);
}
next.applyStart(range, indentation, width);
}
}
/**
* Applies the changed content to the underlying document
*
* @param change
* Text content to apply to the underlying document
* @param position
* Offset measured in comment region coordinates where to apply
* the changed content
* @param count
* Length of the content to be changed
*/
protected final void applyText(final String change, final int position, final int count) {
try {
final int base= getOffset() + position;
final String content= fDocument.get(base, count);
if (!change.equals(content))
fDocument.replace(getOffset() + position, count, change);
} catch (BadLocationException exception) {
// Should not happen
}
}
/**
* Can the comment range be appended to the comment line?
*
* @param line
* Comment line where to append the comment range
* @param previous
* Comment range which is the predecessor of the current comment
* range
* @param next
* Comment range to test whether it can be appended to the
* comment line
* @param space
* Amount of space in the comment line used by already inserted
* comment ranges
* @param width
* The maximal width of text in this comment region measured in
* average character widths
* @return <code>true</code> iff the comment range can be added to the
* line, <code>false</code> otherwise
*/
protected boolean canAppend(final CommentLine line, final CommentRange previous, final CommentRange next, final int space, final int width) {
return space == 0 || space + next.getLength() < width;
}
/**
* Can the two current comment ranges be applied to the underlying
* document?
*
* @param previous
* Previous comment range which was already applied
* @param next
* Next comment range to be applied
* @return <code>true</code> iff the next comment range can be applied,
* <code>false</code> otherwise
*/
protected boolean canApply(final CommentRange previous, final CommentRange next) {
return true;
}
/**
* Finalizes the comment region and adjusts its starting indentation.
*
* @param indentation
* Indentation of the formatted comment region
*/
protected void finalizeRegion(final String indentation) {
// Do nothing
}
/**
* Formats the comment region.
*
* @param indentation
* Indentation of the formatted comment region
*/
public void format(String indentation) {
final String probe= getText(0, CommentLine.NON_FORMAT_START_PREFIX.length());
if (probe.startsWith(CommentLine.NON_FORMAT_START_PREFIX))
return;
final Map preferences= fStrategy.getPreferences();
int margin= 80;
try {
margin= Integer.parseInt(preferences.get(PreferenceConstants.FORMATTER_COMMENT_LINELENGTH).toString());
} catch (Exception exception) {
// Do nothing
}
margin= Math.max(COMMENT_PREFIX_LENGTH + 1, margin - stringToLength(indentation) - COMMENT_PREFIX_LENGTH);
fDocument.addPositionCategory(COMMENT_POSITION_CATEGORY);
final IPositionUpdater positioner= new DefaultPositionUpdater(COMMENT_POSITION_CATEGORY);
fDocument.addPositionUpdater(positioner);
try {
initializeRegion();
markRegion();
wrapRegion(margin);
applyRegion(indentation, margin);
finalizeRegion(indentation);
} finally {
if (fGraphics != null && !fGraphics.isDisposed())
fGraphics.dispose();
try {
fDocument.removePositionCategory(COMMENT_POSITION_CATEGORY);
fDocument.removePositionUpdater(positioner);
} catch (BadPositionCategoryException exception) {
// Should not happen
}
}
}
/**
* Returns the general line delimiter used in this comment region.
*
* @return The line delimiter for this comment region
*/
protected final String getDelimiter() {
return fDelimiter;
}
/**
* Returns the line delimiter used in this comment line break.
*
* @param predecessor
* The predecessor comment line before the line break
* @param successor
* The successor comment line after the line break
* @param previous
* The comment range after the line break
* @param next
* The comment range before the line break
* @param indentation
* Indentation of the formatted line break
* @return The line delimiter for this comment line break
*/
protected String getDelimiter(final CommentLine predecessor, final CommentLine successor, final CommentRange previous, final CommentRange next, final String indentation) {
return fDelimiter + indentation + successor.getContentPrefix();
}
/**
* Returns the range delimiter for this comment range break in this comment
* region.
*
* @param previous
* The previous comment range to the right of the range delimiter
* @param next
* The next comment range to the left of the range delimiter
* @return The delimiter for this comment range break
*/
protected String getDelimiter(final CommentRange previous, final CommentRange next) {
return COMMENT_RANGE_DELIMITER;
}
/**
* Returns the document of this comment region.
*
* @return The document of this region
*/
protected final IDocument getDocument() {
return fDocument;
}
/**
* Returns the list of comment ranges in this comment region
*
* @return The list of comment ranges in this region
*/
protected final LinkedList getRanges() {
return fRanges;
}
/**
* Returns the number of comment lines in this comment region.
*
* @return The number of lines in this comment region
*/
protected final int getSize() {
return fLines.size();
}
/**
* Returns the comment formatting strategy used to format this comment
* region.
*
* @return The formatting strategy for this comment region
*/
protected final CommentFormattingStrategy getStrategy() {
return fStrategy;
}
/**
* Returns the text of this comment region in the indicated range.
*
* @param position
* The offset of the comment range to retrieve in comment region
* coordinates
* @param count
* The length of the comment range to retrieve
* @return The content of this comment region in the indicated range
*/
protected final String getText(final int position, final int count) {
String content= ""; //$NON-NLS-1$
try {
content= fDocument.get(getOffset() + position, count);
} catch (BadLocationException exception) {
// Should not happen
}
return content;
}
/**
* Does the border <code>border</code> exist?
*
* @param border
* The type of the border. Must be a border attribute of <code>CommentRegion</code>.
* @return <code>true</code> iff this border exists, <code>false</code>
* otherwise.
*/
protected final boolean hasBorder(final int border) {
return (fBorders & border) == border;
}
/**
* Initializes the internal representation of the comment region.
*/
protected void initializeRegion() {
try {
fDocument.addPosition(COMMENT_POSITION_CATEGORY, this);
} catch (BadLocationException exception) {
// Should not happen
} catch (BadPositionCategoryException exception) {
// Should not happen
}
int index= 0;
CommentLine line= null;
for (final Iterator iterator= fLines.iterator(); iterator.hasNext(); index++) {
line= (CommentLine)iterator.next();
line.scanLine(index);
line.tokenizeLine(index);
}
}
/**
* Should blank lines be cleared during formatting?
*
* @return <code>true</code> iff blank lines should be cleared, <code>false</code>
* otherwise
*/
protected final boolean isClearLines() {
return fClear;
}
/**
* Is the current comment range a word?
*
* @param current
* Comment range to test whether it is a word
* @return <code>true</code> iff the comment range is a word, <code>false</code>
* otherwise.
*/
protected final boolean isCommentWord(final CommentRange current) {
final String token= getText(current.getOffset(), current.getLength());
for (int index= 0; index < token.length(); index++) {
if (!Character.isLetterOrDigit(token.charAt(index)))
return false;
}
return true;
}
/**
* Is this comment region a single line region?
*
* @return <code>true</code> iff this region is single line, <code>false</code>
* otherwise.
*/
protected final boolean isSingleLine() {
return fSingleLine;
}
/**
* Marks the attributed ranges in this comment region.
*/
protected void markRegion() {
// Do nothing
}
/**
* Set the border <code>border</code> to true.
*
* @param border
* The type of the border. Must be a border attribute of <code>CommentRegion</code>.
*/
protected final void setBorder(final int border) {
fBorders |= border;
}
/**
* Returns the indentation string for a reference string
*
* @param reference
* The reference string to get the indentation string for
* @param tabs
* <code>true</code> iff the indent should use tabs, <code>false</code>
* otherwise.
* @return The indentation string
*/
protected final String stringToIndent(final String reference, final boolean tabs) {
int space= 1;
int pixels= reference.length();
if (fGraphics != null) {
pixels= stringToPixels(reference);
space= fGraphics.stringExtent(" ").x; //$NON-NLS-1$
}
final StringBuffer buffer= new StringBuffer();
final int spaces= pixels / space;
if (tabs) {
final int count= spaces / fTabs;
final int modulo= spaces % fTabs;
for (int index= 0; index < count; index++)
buffer.append('\t');
for (int index= 0; index < modulo; index++)
buffer.append(' ');
} else {
for (int index= 0; index < spaces; index++)
buffer.append(' ');
}
return buffer.toString();
}
/**
* Returns the length of the reference string in characters.
*
* @param reference
* The reference string to get the length
* @return The length of the string in characters
*/
protected final int stringToLength(final String reference) {
int tabs= 0;
int count= reference.length();
for (int index= 0; index < count; index++) {
if (reference.charAt(index) == '\t')
tabs++;
}
count += tabs * (fTabs - 1);
return count;
}
/**
* Returns the width of the reference string in pixels.
*
* @param reference
* The reference string to get the width
* @return The width of the string in pixels
*/
protected final int stringToPixels(final String reference) {
final StringBuffer buffer= new StringBuffer();
char character= 0;
for (int index= 0; index < reference.length(); index++) {
character= reference.charAt(index);
if (character == '\t') {
for (int tab= 0; tab < fTabs; tab++)
buffer.append(' ');
} else
buffer.append(character);
}
return fGraphics.stringExtent(buffer.toString()).x;
}
/**
* Wraps the comment ranges in this comment region into comment lines.
*
* @param width
* The maximal width of text in this comment region measured in
* average character widths
*/
protected void wrapRegion(final int width) {
fLines.clear();
int index= 0;
boolean adapted= false;
CommentLine successor= null;
CommentLine predecessor= null;
CommentRange previous= null;
CommentRange next= null;
while (!fRanges.isEmpty()) {
index= 0;
adapted= false;
predecessor= successor;
successor= CommentObjectFactory.createLine(this);
fLines.add(successor);
while (!fRanges.isEmpty()) {
next= (CommentRange)fRanges.getFirst();
if (canAppend(successor, previous, next, index, width)) {
if (!adapted && predecessor != null) {
successor.adapt(predecessor);
adapted= true;
}
fRanges.removeFirst();
successor.append(next);
index += (next.getLength() + 1);
previous= next;
} else
break;
}
}
}
}
|
48,975 |
Bug 48975 Comment Formatter should compare values using equals()
|
Currently, the preference values are read and compared by reference, which only works in special circumstances.
|
verified fixed
|
988ada7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T10:38:53Z | 2003-12-17T11:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/JavaDocRegion.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.comment;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.ConfigurableLineTracker;
import org.eclipse.jface.text.DefaultPositionUpdater;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ILineTracker;
import org.eclipse.jface.text.IPositionUpdater;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.TypedPosition;
import org.eclipse.jface.text.formatter.ContentFormatter2;
import org.eclipse.jface.text.formatter.FormattingContextProperties;
import org.eclipse.jface.text.formatter.IFormattingContext;
import org.eclipse.jdt.ui.PreferenceConstants;
/**
* Javadoc region in a source code document.
*
* @since 3.0
*/
public class JavaDocRegion extends MultiCommentRegion implements IJavaDocTagConstants {
/** Position category of javadoc code ranges */
protected static final String CODE_POSITION_CATEGORY= "__javadoc_code_position"; //$NON-NLS-1$
/** Should html tags be formatted? */
private final boolean fFormatHtml;
/** Should source code regions be formatted? */
private final boolean fFormatSource;
/**
* Creates a new javadoc region.
*
* @param strategy
* The comment formatting strategy used to format this comment
* region
* @param position
* The typed position which forms this javadoc region
* @param delimiter
* The line delimiter to use in this javadoc region
*/
protected JavaDocRegion(final CommentFormattingStrategy strategy, final TypedPosition position, final String delimiter) {
super(strategy, position, delimiter);
final Map preferences= strategy.getPreferences();
fFormatSource= preferences.get(PreferenceConstants.FORMATTER_COMMENT_FORMATSOURCE) == IPreferenceStore.TRUE;
fFormatHtml= preferences.get(PreferenceConstants.FORMATTER_COMMENT_FORMATHTML) == IPreferenceStore.TRUE;
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#applyRegion(java.lang.String,int)
*/
protected void applyRegion(final String indentation, final int width) {
super.applyRegion(indentation, width);
if (fFormatSource) {
final ContentFormatter2 formatter= getStrategy().getFormatter();
try {
final IDocument document= getDocument();
final Position[] positions= document.getPositions(CODE_POSITION_CATEGORY);
if (positions.length > 0) {
int begin= 0;
int end= 0;
final IFormattingContext context= new CommentFormattingContext();
context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.valueOf(false));
context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, getStrategy().getPreferences());
for (int position= 0; position < positions.length - 1; position++) {
begin= positions[position++].getOffset();
end= positions[position].getOffset();
context.setProperty(FormattingContextProperties.CONTEXT_PARTITION, new TypedPosition(begin, end - begin, IDocument.DEFAULT_CONTENT_TYPE));
formatter.format(document, context);
}
}
} catch (BadPositionCategoryException exception) {
// Should not happen
}
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#canApply(org.eclipse.jdt.internal.ui.text.comment.CommentRange,org.eclipse.jdt.internal.ui.text.comment.CommentRange)
*/
protected boolean canApply(final CommentRange previous, final CommentRange next) {
if (previous != null) {
final boolean isCurrentCode= next.hasAttribute(COMMENT_CODE);
final boolean isLastCode= previous.hasAttribute(COMMENT_CODE);
try {
final int index= getOffset();
final IDocument document= getDocument();
if (!isLastCode && isCurrentCode)
document.addPosition(CODE_POSITION_CATEGORY, new Position(index + next.getOffset() + next.getLength()));
else if (isLastCode && !isCurrentCode)
document.addPosition(CODE_POSITION_CATEGORY, new Position(index + previous.getOffset()));
} catch (BadLocationException exception) {
// Should not happen
} catch (BadPositionCategoryException exception) {
// Should not happen
}
if (previous.hasAttribute(COMMENT_IMMUTABLE) && next.hasAttribute(COMMENT_IMMUTABLE) && !isLastCode)
return false;
}
return true;
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#finishRegion(java.lang.String)
*/
protected void finalizeRegion(final String indentation) {
final String test= indentation + MultiCommentLine.MULTI_COMMENT_CONTENT_PREFIX;
final StringBuffer buffer= new StringBuffer();
buffer.append(test);
buffer.append(' ');
final String delimiter= buffer.toString();
try {
final ILineTracker tracker= new ConfigurableLineTracker(new String[] { getDelimiter()});
tracker.set(getText(0, getLength()));
int index= 0;
String content= null;
IRegion range= null;
for (int line= tracker.getNumberOfLines() - 3; line >= 1; line--) {
range= tracker.getLineInformation(line);
index= range.getOffset();
content= getText(index, range.getLength());
if (!content.startsWith(test))
applyText(delimiter, index, 0);
}
} catch (BadLocationException exception) {
// Should not happen
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#formatRegion(java.lang.String)
*/
public void format(final String indentation) {
IPositionUpdater updater= null;
final IDocument document= getDocument();
if (fFormatSource) {
document.addPositionCategory(CODE_POSITION_CATEGORY);
updater= new DefaultPositionUpdater(CODE_POSITION_CATEGORY);
document.addPositionUpdater(updater);
}
super.format(indentation);
if (fFormatSource) {
try {
document.removePositionCategory(CODE_POSITION_CATEGORY);
document.removePositionUpdater(updater);
} catch (BadPositionCategoryException exception) {
// Should not happen
}
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.MultiCommentRegion#markHtmlRanges()
*/
protected final void markHtmlRanges() {
markTagRanges(JAVADOC_IMMUTABLE_TAGS, COMMENT_IMMUTABLE, true);
if (fFormatSource)
markTagRanges(JAVADOC_CODE_TAGS, COMMENT_CODE, false);
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.MultiCommentRegion#markHtmlTags(org.eclipse.jdt.internal.ui.text.comment.CommentRange,java.lang.String)
*/
protected final void markHtmlTag(final CommentRange range, final String token) {
if (range.hasAttribute(COMMENT_HTML)) {
range.markHtmlTag(JAVADOC_IMMUTABLE_TAGS, token, COMMENT_IMMUTABLE, true, true);
if (fFormatHtml) {
range.markHtmlTag(JAVADOC_SEPARATOR_TAGS, token, COMMENT_SEPARATOR, true, true);
range.markHtmlTag(JAVADOC_BREAK_TAGS, token, COMMENT_BREAK, false, true);
range.markHtmlTag(JAVADOC_NEWLINE_TAGS, token, COMMENT_NEWLINE, true, false);
} else
range.markHtmlTag(JAVADOC_CODE_TAGS, token, COMMENT_SEPARATOR, true, true);
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.MultiCommentRegion#markJavadocTag(org.eclipse.jdt.internal.ui.text.comment.CommentRange,java.lang.String)
*/
protected final void markJavadocTag(final CommentRange range, final String token) {
range.markPrefixTag(JAVADOC_PARAM_TAGS, COMMENT_TAG_PREFIX, token, COMMENT_PARAMETER);
range.markPrefixTag(JAVADOC_ROOT_TAGS, COMMENT_TAG_PREFIX, token, COMMENT_ROOT);
}
/**
* Marks tag ranges in this javadoc region.
*
* @param tags
* The tags which confine the attributed ranges
* @param key
* The key of the attribute to set when an attributed range has
* been recognized
* @param include
* <code>true</code> iff end tags in this attributed range
* should be attributed too, <code>false</code> otherwise
*/
protected final void markTagRanges(final String[] tags, final int key, final boolean include) {
int level= 0;
int count= 0;
String token= null;
CommentRange current= null;
for (int index= 0; index < tags.length; index++) {
level= 0;
for (final Iterator iterator= getRanges().iterator(); iterator.hasNext();) {
current= (CommentRange)iterator.next();
count= current.getLength();
if (count > 0) {
token= getText(current.getOffset(), current.getLength());
level= current.markRange(token, tags[index], level, key, include);
}
}
}
}
}
|
48,975 |
Bug 48975 Comment Formatter should compare values using equals()
|
Currently, the preference values are read and compared by reference, which only works in special circumstances.
|
verified fixed
|
988ada7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T10:38:53Z | 2003-12-17T11:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/MultiCommentRegion.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.comment;
import java.util.ListIterator;
import java.util.Map;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.TypedPosition;
import org.eclipse.jdt.ui.PreferenceConstants;
/**
* Multi-comment region in a source code document.
*
* @since 3.0
*/
public class MultiCommentRegion extends CommentRegion implements ICommentTagConstants {
/** Should root tag parameter descriptions be indented after the tag? */
private final boolean fIndentDescriptions;
/** Should root tag parameter descriptions be indented? */
private final boolean fIndentRoots;
/** Should description of parameters go to the next line? */
private final boolean fParameterNewLine;
/** Should root tags be separated from description? */
private boolean fSeparateRoots;
/**
* Creates a new multi-comment region.
*
* @param strategy
* The comment formatting strategy used to format this comment
* region
* @param position
* The typed position which forms this comment region
* @param delimiter
* The line delimiter to use in this comment region
*/
protected MultiCommentRegion(final CommentFormattingStrategy strategy, final TypedPosition position, final String delimiter) {
super(strategy, position, delimiter);
final Map preferences= strategy.getPreferences();
fIndentRoots= preferences.get(PreferenceConstants.FORMATTER_COMMENT_INDENTROOTTAGS) == IPreferenceStore.TRUE;
fIndentDescriptions= preferences.get(PreferenceConstants.FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION) == IPreferenceStore.TRUE;
fSeparateRoots= preferences.get(PreferenceConstants.FORMATTER_COMMENT_SEPARATEROOTTAGS) == IPreferenceStore.TRUE;
fParameterNewLine= preferences.get(PreferenceConstants.FORMATTER_COMMENT_NEWLINEFORPARAMETER) == IPreferenceStore.TRUE;
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#canAppend(org.eclipse.jdt.internal.ui.text.comment.CommentLine,org.eclipse.jdt.internal.ui.text.comment.CommentRange, org.eclipse.jdt.internal.ui.text.comment.CommentRange, int, int)
*/
protected boolean canAppend(final CommentLine line, final CommentRange previous, final CommentRange next, final int position, int count) {
final boolean blank= next.hasAttribute(COMMENT_BLANKLINE);
if (next.getLength() <= 2 && !blank && !isCommentWord(next))
return true;
if (fParameterNewLine && line.hasAttribute(COMMENT_PARAMETER) && line.getSize() > 1)
return false;
if (previous != null) {
if (previous.hasAttribute(COMMENT_ROOT))
return true;
if (position != 0 && (blank || previous.hasAttribute(COMMENT_BLANKLINE) || next.hasAttribute(COMMENT_PARAMETER) || next.hasAttribute(COMMENT_ROOT) || next.hasAttribute(COMMENT_SEPARATOR) || next.hasAttribute(COMMENT_NEWLINE) || previous.hasAttribute(COMMENT_BREAK) || previous.hasAttribute(COMMENT_SEPARATOR)))
return false;
if (next.hasAttribute(COMMENT_IMMUTABLE) && previous.hasAttribute(COMMENT_IMMUTABLE))
return true;
}
if (fIndentRoots && !line.hasAttribute(COMMENT_ROOT) && !line.hasAttribute(COMMENT_PARAMETER))
count -= stringToLength(line.getIndentation());
return super.canAppend(line, previous, next, position, count);
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#getDelimiter(org.eclipse.jdt.internal.ui.text.comment.CommentLine, org.eclipse.jdt.internal.ui.text.comment.CommentLine, org.eclipse.jdt.internal.ui.text.comment.CommentRange, org.eclipse.jdt.internal.ui.text.comment.CommentRange, java.lang.String)
*/
protected String getDelimiter(CommentLine predecessor, CommentLine successor, CommentRange previous, CommentRange next, String indentation) {
final String delimiter= super.getDelimiter(predecessor, successor, previous, next, indentation);
if (previous != null) {
if (previous.hasAttribute(COMMENT_IMMUTABLE | COMMENT_SEPARATOR) && !next.hasAttribute(COMMENT_CODE) && !successor.hasAttribute(COMMENT_BLANKLINE))
return delimiter + delimiter;
else if (previous.hasAttribute(COMMENT_CODE) && !next.hasAttribute(COMMENT_CODE))
return getDelimiter();
else if ((next.hasAttribute(COMMENT_IMMUTABLE | COMMENT_SEPARATOR) || ((fSeparateRoots || !isClearLines()) && previous.hasAttribute(COMMENT_PARAGRAPH))) && !successor.hasAttribute(COMMENT_BLANKLINE))
return delimiter + delimiter;
else if (fIndentRoots && !predecessor.hasAttribute(COMMENT_ROOT) && !predecessor.hasAttribute(COMMENT_PARAMETER) && !predecessor.hasAttribute(COMMENT_BLANKLINE))
return delimiter + stringToIndent(predecessor.getIndentation(), false);
}
return delimiter;
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#getDelimiter(org.eclipse.jdt.internal.ui.text.comment.CommentRange,org.eclipse.jdt.internal.ui.text.comment.CommentRange)
*/
protected String getDelimiter(final CommentRange previous, final CommentRange next) {
if (previous != null) {
if (previous.hasAttribute(COMMENT_HTML) && next.hasAttribute(COMMENT_HTML))
return ""; //$NON-NLS-1$
else if (next.hasAttribute(COMMENT_OPEN) || previous.hasAttribute(COMMENT_HTML | COMMENT_CLOSE))
return ""; //$NON-NLS-1$
else if (!next.hasAttribute(COMMENT_CODE) && previous.hasAttribute(COMMENT_CODE))
return ""; //$NON-NLS-1$
else if (next.hasAttribute(COMMENT_CLOSE) && previous.getLength() <= 2 && !isCommentWord(previous))
return ""; //$NON-NLS-1$
else if (previous.hasAttribute(COMMENT_OPEN) && next.getLength() <= 2 && !isCommentWord(next))
return ""; //$NON-NLS-1$
}
return super.getDelimiter(previous, next);
}
/**
* Should root tag parameter descriptions be indented after the tag?
*
* @return <code>true</code> iff the descriptions should be indented after,
* <code>false</code> otherwise.
*/
protected final boolean isIndentDescriptions() {
return fIndentDescriptions;
}
/**
* Should root tag parameter descriptions be indented?
*
* @return <code>true</code> iff the root tags should be indented,
* <code>false</code> otherwise.
*/
protected final boolean isIndentRoots() {
return fIndentRoots;
}
/**
* Marks the comment ranges confined by html tags.
*/
protected void markHtmlRanges() {
// Do nothing
}
/**
* Marks the comment range with its html tag attributes.
*
* @param range
* The comment range to mark
* @param token
* Token associated with the comment range
*/
protected void markHtmlTag(final CommentRange range, final String token) {
// Do nothing
}
/**
* Marks the comment range with its javadoc tag attributes.
*
* @param range
* The comment range to mark
* @param token
* Token associated with the comment range
*/
protected void markJavadocTag(final CommentRange range, final String token) {
range.markPrefixTag(COMMENT_ROOT_TAGS, COMMENT_TAG_PREFIX, token, COMMENT_ROOT);
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#markRegion()
*/
protected final void markRegion() {
int count= 0;
boolean paragraph= false;
String token= null;
CommentRange range= null;
CommentRange blank= null;
for (final ListIterator iterator= getRanges().listIterator(); iterator.hasNext();) {
range= (CommentRange)iterator.next();
count= range.getLength();
if (count > 0) {
token= getText(range.getOffset(), count).toLowerCase();
markJavadocTag(range, token);
if (!paragraph && (range.hasAttribute(COMMENT_ROOT) || range.hasAttribute(COMMENT_PARAMETER))) {
iterator.previous();
while (iterator.hasPrevious()) {
blank= (CommentRange)iterator.previous();
if (blank.hasAttribute(COMMENT_BLANKLINE))
iterator.remove();
else
break;
}
range.setAttribute(COMMENT_PARAGRAPH);
paragraph= true;
}
markHtmlTag(range, token);
}
}
markHtmlRanges();
}
}
|
46,364 |
Bug 46364 [content assist] Support incremental content assist
|
I've been spoiled by content assist. What would be a great addition would be a Unix-style "look ahead" invoked by the TAB key, like at a Unix Shell. If non-whitespace characters appear to the left of the Caret, it is unlikely that a TAB is going to be inserted in that line. This is why I think it's ok to use TAB for this. Basically, pressing TAB will be equivalent to the combination of: Control+SPACE, followed by ENTER. So, given: for (int i = 0; i < cols.length; i++) { Entry entry = cols[i]; double distance; if (entry.side == -1) { distance = Math.abs(baseRect.preciseX - entry.offset); if (distance < best) { bestSide = -1; best = dis<<CARET>> Pressing the TAB key will insert "tance".
|
verified fixed
|
3fa1021
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T12:04:41Z | 2003-11-10T18:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/BasicEditorActionContributor.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.javaeditor;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.ui.editors.text.EncodingActionGroup;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.actions.RetargetAction;
import org.eclipse.ui.ide.IDEActionFactory;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.RetargetTextEditorAction;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.JdtActionConstants;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
public class BasicEditorActionContributor extends BasicJavaEditorActionContributor {
protected RetargetAction fRetargetContentAssist;
protected RetargetTextEditorAction fContentAssist;
protected RetargetTextEditorAction fCompletePrefix;
protected RetargetTextEditorAction fContextInformation;
protected RetargetTextEditorAction fCorrectionAssist;
private EncodingActionGroup fEncodingActionGroup;
public BasicEditorActionContributor() {
fRetargetContentAssist= new RetargetAction(JdtActionConstants.CONTENT_ASSIST, JavaEditorMessages.getString("ContentAssistProposal.label")); //$NON-NLS-1$
fRetargetContentAssist.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
markAsPartListener(fRetargetContentAssist);
fContentAssist= new RetargetTextEditorAction(JavaEditorMessages.getResourceBundle(), "ContentAssistProposal."); //$NON-NLS-1$
fContentAssist.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
fContentAssist.setImageDescriptor(JavaPluginImages.DESC_CLCL_CODE_ASSIST);
fContentAssist.setDisabledImageDescriptor(JavaPluginImages.DESC_DLCL_CODE_ASSIST);
fContextInformation= new RetargetTextEditorAction(JavaEditorMessages.getResourceBundle(), "ContentAssistContextInformation."); //$NON-NLS-1$
fContextInformation.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
fCompletePrefix= new RetargetTextEditorAction(JavaEditorMessages.getResourceBundle(), "ContentAssistCompletePrefix."); //$NON-NLS-1$
fCompletePrefix.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX);
fCorrectionAssist= new RetargetTextEditorAction(JavaEditorMessages.getResourceBundle(), "CorrectionAssistProposal."); //$NON-NLS-1$
fCorrectionAssist.setActionDefinitionId(IJavaEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS);
// character encoding
fEncodingActionGroup= new EncodingActionGroup();
}
/*
* @see EditorActionBarContributor#contributeToMenu(IMenuManager)
*/
public void contributeToMenu(IMenuManager menu) {
super.contributeToMenu(menu);
IMenuManager editMenu= menu.findMenuUsingPath(IWorkbenchActionConstants.M_EDIT);
if (editMenu != null) {
editMenu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, fRetargetContentAssist);
editMenu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, fCorrectionAssist);
editMenu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, fContextInformation);
editMenu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, fCompletePrefix);
}
}
/*
* @see IEditorActionBarContributor#setActiveEditor(IEditorPart)
*/
public void setActiveEditor(IEditorPart part) {
super.setActiveEditor(part);
ITextEditor textEditor= null;
if (part instanceof ITextEditor)
textEditor= (ITextEditor) part;
fContentAssist.setAction(getAction(textEditor, "ContentAssistProposal")); //$NON-NLS-1$
fContextInformation.setAction(getAction(textEditor, "ContentAssistContextInformation")); //$NON-NLS-1$
fCorrectionAssist.setAction(getAction(textEditor, "CorrectionAssistProposal")); //$NON-NLS-1$
fCompletePrefix.setAction(getAction(textEditor, "ContentAssistCompletePrefix")); //$NON-NLS-1$
IActionBars actionBars= getActionBars();
actionBars.setGlobalActionHandler(JdtActionConstants.SHIFT_RIGHT, getAction(textEditor, "ShiftRight")); //$NON-NLS-1$
actionBars.setGlobalActionHandler(JdtActionConstants.SHIFT_LEFT, getAction(textEditor, "ShiftLeft")); //$NON-NLS-1$
actionBars.setGlobalActionHandler(IDEActionFactory.ADD_TASK.getId(), getAction(textEditor, IDEActionFactory.ADD_TASK.getId())); //$NON-NLS-1$
actionBars.setGlobalActionHandler(IDEActionFactory.BOOKMARK.getId(), getAction(textEditor, IDEActionFactory.BOOKMARK.getId())); //$NON-NLS-1$
// character encoding
fEncodingActionGroup.retarget(textEditor);
}
/*
* @see IEditorActionBarContributor#init(IActionBars, IWorkbenchPage)
*/
public void init(IActionBars bars, IWorkbenchPage page) {
super.init(bars, page);
// register actions that have a dynamic editor.
bars.setGlobalActionHandler(JdtActionConstants.CONTENT_ASSIST, fContentAssist);
// character encoding
fEncodingActionGroup.fillActionBars(bars);
}
}
|
48,978 |
Bug 48978 New code formatter prefs: java.lang.ArithmeticException: / by zero
|
I200312162000 Sorry no steps. Happened while playing with the preferences. !SESSION Dez 17, 2003 11:22:47.461 --------------------------------------------- java.version=1.4.2 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=de_CH Command-line arguments: -os win32 -ws win32 -arch x86 -configuration file:c:\eclipse\drops\I200312162000/.config -install file:c:/eclipse/drops/I200312162000/ !ENTRY org.eclipse.ui 4 4 Dez 17, 2003 11:22:47.461 !MESSAGE Unhandled event loop exception !ENTRY org.eclipse.ui 4 0 Dez 17, 2003 11:22:47.511 !MESSAGE / by zero !STACK 0 java.lang.ArithmeticException: / by zero at org.eclipse.jdt.internal.formatter.Scribe.getNextIndentationLevel(Scribe.java:327) at org.eclipse.jdt.internal.formatter.align.Alignment.checkColumn(Alignment.java:199) at org.eclipse.jdt.internal.formatter.Scribe.alignFragment(Scribe.java:178) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:517) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.formatTypeMembers(CodeFormatterVisitor.java:1566) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:925) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.visit(CodeFormatterVisitor.java:2372) at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.traverse(CompilationUnitDeclaration.java:292) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:726) at org.eclipse.jdt.internal.formatter.DefaultCodeFormatter.formatCompilationUnit(DefaultCodeFormatter.java:238) at org.eclipse.jdt.internal.formatter.DefaultCodeFormatter.format(DefaultCodeFormatter.java:205) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format2(CodeFormatterUtil.java:189) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format(CodeFormatterUtil.java:101) at org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy.format(JavaFormattingStrategy.java:95) at org.eclipse.jface.text.formatter.ContentFormatter2.format(ContentFormatter2.java:806) at org.eclipse.jface.text.formatter.ContentFormatter2.formatMaster(ContentFormatter2.java:661) at org.eclipse.jface.text.formatter.ContentFormatter2.format(ContentFormatter2.java:487) at org.eclipse.jdt.internal.ui.preferences.formatter.JavaPreview.update(JavaPreview.java:165) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage.updatePreview(ModifyDialogTabPage.java:378) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$1.update(ModifyDialogTabPage.java:46) at java.util.Observable.notifyObservers(Observable.java:142) at java.util.Observable.notifyObservers(Observable.java:98) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$CheckboxPreference.checkboxChecked(ModifyDialogTabPage.java:81) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$2.widgetSelected(ModifyDialogTabPage.java:71) 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:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2311) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1992) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.preferences.formatter.CodingStyleConfigurationBlock$ButtonController.modifyButtonPressed(CodingStyleConfigurationBlock.java:202) at org.eclipse.jdt.internal.ui.preferences.formatter.CodingStyleConfigurationBlock$ButtonController.widgetSelected(CodingStyleConfigurationBlock.java:177) 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:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2311) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1992) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.ui.internal.OpenPreferencesAction.run(OpenPreferencesAction.java:72) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:509) at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:461) at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:408) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2311) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1992) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:233) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:85) 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:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:281) at org.eclipse.core.launcher.Main.run(Main.java:744) at org.eclipse.core.launcher.Main.main(Main.java:583) !ENTRY org.eclipse.ui 4 4 Dez 17, 2003 11:22:49.58 !MESSAGE Unhandled event loop exception !ENTRY org.eclipse.ui 4 0 Dez 17, 2003 11:22:49.68 !MESSAGE / by zero !STACK 0 java.lang.ArithmeticException: / by zero at org.eclipse.jdt.internal.formatter.Scribe.getNextIndentationLevel(Scribe.java:327) at org.eclipse.jdt.internal.formatter.align.Alignment.checkColumn(Alignment.java:199) at org.eclipse.jdt.internal.formatter.Scribe.alignFragment(Scribe.java:178) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:517) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.formatTypeMembers(CodeFormatterVisitor.java:1566) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:925) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.visit(CodeFormatterVisitor.java:2372) at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.traverse(CompilationUnitDeclaration.java:292) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:726) at org.eclipse.jdt.internal.formatter.DefaultCodeFormatter.formatCompilationUnit(DefaultCodeFormatter.java:238) at org.eclipse.jdt.internal.formatter.DefaultCodeFormatter.format(DefaultCodeFormatter.java:205) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format2(CodeFormatterUtil.java:189) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format(CodeFormatterUtil.java:101) at org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy.format(JavaFormattingStrategy.java:95) at org.eclipse.jface.text.formatter.ContentFormatter2.format(ContentFormatter2.java:806) at org.eclipse.jface.text.formatter.ContentFormatter2.formatMaster(ContentFormatter2.java:661) at org.eclipse.jface.text.formatter.ContentFormatter2.format(ContentFormatter2.java:487) at org.eclipse.jdt.internal.ui.preferences.formatter.JavaPreview.update(JavaPreview.java:165) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage.updatePreview(ModifyDialogTabPage.java:378) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$1.update(ModifyDialogTabPage.java:46) at java.util.Observable.notifyObservers(Observable.java:142) at java.util.Observable.notifyObservers(Observable.java:98) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$NumberPreference.updatePreferences(ModifyDialogTabPage.java:246) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$NumberPreference.numberChanged(ModifyDialogTabPage.java:238) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$5.modifyText(ModifyDialogTabPage.java:225) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:187) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:852) at org.eclipse.swt.widgets.Text.wmCommandChild(Text.java:2007) at org.eclipse.swt.widgets.Control.WM_COMMAND(Control.java:3069) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2942) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.CallWindowProc(OS.java:1293) at org.eclipse.swt.widgets.Text.callWindowProc(Text.java:127) at org.eclipse.swt.widgets.Control.windowProc(Control.java:3019) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1369) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1990) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.preferences.formatter.CodingStyleConfigurationBlock$ButtonController.modifyButtonPressed(CodingStyleConfigurationBlock.java:202) at org.eclipse.jdt.internal.ui.preferences.formatter.CodingStyleConfigurationBlock$ButtonController.widgetSelected(CodingStyleConfigurationBlock.java:177) 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:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2311) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1992) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.ui.internal.OpenPreferencesAction.run(OpenPreferencesAction.java:72) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:509) at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:461) at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:408) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2311) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1992) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:233) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:85) 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:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:281) at org.eclipse.core.launcher.Main.run(Main.java:744) at org.eclipse.core.launcher.Main.main(Main.java:583) !ENTRY org.eclipse.ui 4 4 Dez 17, 2003 11:22:49.570 !MESSAGE Unhandled event loop exception !ENTRY org.eclipse.ui 4 0 Dez 17, 2003 11:22:49.580 !MESSAGE / by zero !STACK 0 java.lang.ArithmeticException: / by zero at org.eclipse.jdt.internal.formatter.Scribe.getNextIndentationLevel(Scribe.java:327) at org.eclipse.jdt.internal.formatter.align.Alignment.checkColumn(Alignment.java:199) at org.eclipse.jdt.internal.formatter.Scribe.alignFragment(Scribe.java:178) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:517) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.formatTypeMembers(CodeFormatterVisitor.java:1566) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:925) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.visit(CodeFormatterVisitor.java:2372) at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.traverse(CompilationUnitDeclaration.java:292) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:726) at org.eclipse.jdt.internal.formatter.DefaultCodeFormatter.formatCompilationUnit(DefaultCodeFormatter.java:238) at org.eclipse.jdt.internal.formatter.DefaultCodeFormatter.format(DefaultCodeFormatter.java:205) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format2(CodeFormatterUtil.java:189) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format(CodeFormatterUtil.java:101) at org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy.format(JavaFormattingStrategy.java:95) at org.eclipse.jface.text.formatter.ContentFormatter2.format(ContentFormatter2.java:806) at org.eclipse.jface.text.formatter.ContentFormatter2.formatMaster(ContentFormatter2.java:661) at org.eclipse.jface.text.formatter.ContentFormatter2.format(ContentFormatter2.java:487) at org.eclipse.jdt.internal.ui.preferences.formatter.JavaPreview.update(JavaPreview.java:165) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage.updatePreview(ModifyDialogTabPage.java:378) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$1.update(ModifyDialogTabPage.java:46) at java.util.Observable.notifyObservers(Observable.java:142) at java.util.Observable.notifyObservers(Observable.java:98) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$NumberPreference.updatePreferences(ModifyDialogTabPage.java:246) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$NumberPreference.numberChanged(ModifyDialogTabPage.java:238) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$5.modifyText(ModifyDialogTabPage.java:225) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:187) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:852) at org.eclipse.swt.widgets.Text.wmCommandChild(Text.java:2007) at org.eclipse.swt.widgets.Control.WM_COMMAND(Control.java:3069) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2942) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.CallWindowProc(OS.java:1293) at org.eclipse.swt.widgets.Text.callWindowProc(Text.java:127) at org.eclipse.swt.widgets.Control.windowProc(Control.java:3019) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1369) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1990) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.preferences.formatter.CodingStyleConfigurationBlock$ButtonController.modifyButtonPressed(CodingStyleConfigurationBlock.java:202) at org.eclipse.jdt.internal.ui.preferences.formatter.CodingStyleConfigurationBlock$ButtonController.widgetSelected(CodingStyleConfigurationBlock.java:177) 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:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2311) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1992) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.ui.internal.OpenPreferencesAction.run(OpenPreferencesAction.java:72) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:509) at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:461) at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:408) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2311) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1992) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:233) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:85) 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:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:281) at org.eclipse.core.launcher.Main.run(Main.java:744) at org.eclipse.core.launcher.Main.main(Main.java:583) !ENTRY org.eclipse.ui 4 4 Dez 17, 2003 11:22:49.610 !MESSAGE Unhandled event loop exception !ENTRY org.eclipse.ui 4 0 Dez 17, 2003 11:22:49.620 !MESSAGE / by zero !STACK 0 java.lang.ArithmeticException: / by zero at org.eclipse.jdt.internal.formatter.Scribe.getNextIndentationLevel(Scribe.java:327) at org.eclipse.jdt.internal.formatter.align.Alignment.checkColumn(Alignment.java:199) at org.eclipse.jdt.internal.formatter.Scribe.alignFragment(Scribe.java:178) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:517) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.formatTypeMembers(CodeFormatterVisitor.java:1566) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:925) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.visit(CodeFormatterVisitor.java:2372) at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.traverse(CompilationUnitDeclaration.java:292) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:726) at org.eclipse.jdt.internal.formatter.DefaultCodeFormatter.formatCompilationUnit(DefaultCodeFormatter.java:238) at org.eclipse.jdt.internal.formatter.DefaultCodeFormatter.format(DefaultCodeFormatter.java:205) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format2(CodeFormatterUtil.java:189) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format(CodeFormatterUtil.java:101) at org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy.format(JavaFormattingStrategy.java:95) at org.eclipse.jface.text.formatter.ContentFormatter2.format(ContentFormatter2.java:806) at org.eclipse.jface.text.formatter.ContentFormatter2.formatMaster(ContentFormatter2.java:661) at org.eclipse.jface.text.formatter.ContentFormatter2.format(ContentFormatter2.java:487) at org.eclipse.jdt.internal.ui.preferences.formatter.JavaPreview.update(JavaPreview.java:165) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage.updatePreview(ModifyDialogTabPage.java:378) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$1.update(ModifyDialogTabPage.java:46) at java.util.Observable.notifyObservers(Observable.java:142) at java.util.Observable.notifyObservers(Observable.java:98) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$NumberPreference.updatePreferences(ModifyDialogTabPage.java:246) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$NumberPreference.numberChanged(ModifyDialogTabPage.java:238) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$5.modifyText(ModifyDialogTabPage.java:225) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:187) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:852) at org.eclipse.swt.widgets.Text.wmCommandChild(Text.java:2007) at org.eclipse.swt.widgets.Control.WM_COMMAND(Control.java:3069) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2942) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.CallWindowProc(OS.java:1293) at org.eclipse.swt.widgets.Text.callWindowProc(Text.java:127) at org.eclipse.swt.widgets.Control.windowProc(Control.java:3019) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1369) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1990) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.preferences.formatter.CodingStyleConfigurationBlock$ButtonController.modifyButtonPressed(CodingStyleConfigurationBlock.java:202) at org.eclipse.jdt.internal.ui.preferences.formatter.CodingStyleConfigurationBlock$ButtonController.widgetSelected(CodingStyleConfigurationBlock.java:177) 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:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2311) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1992) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.ui.internal.OpenPreferencesAction.run(OpenPreferencesAction.java:72) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:509) at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:461) at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:408) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2311) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1992) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:233) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:85) 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:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:281) at org.eclipse.core.launcher.Main.run(Main.java:744) at org.eclipse.core.launcher.Main.main(Main.java:583) !ENTRY org.eclipse.ui 4 4 Dez 17, 2003 11:22:49.640 !MESSAGE Unhandled event loop exception !ENTRY org.eclipse.ui 4 0 Dez 17, 2003 11:22:49.650 !MESSAGE / by zero !STACK 0 java.lang.ArithmeticException: / by zero at org.eclipse.jdt.internal.formatter.Scribe.getNextIndentationLevel(Scribe.java:327) at org.eclipse.jdt.internal.formatter.align.Alignment.checkColumn(Alignment.java:199) at org.eclipse.jdt.internal.formatter.Scribe.alignFragment(Scribe.java:178) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:517) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.formatTypeMembers(CodeFormatterVisitor.java:1566) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:925) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.visit(CodeFormatterVisitor.java:2372) at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.traverse(CompilationUnitDeclaration.java:292) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:726) at org.eclipse.jdt.internal.formatter.DefaultCodeFormatter.formatCompilationUnit(DefaultCodeFormatter.java:238) at org.eclipse.jdt.internal.formatter.DefaultCodeFormatter.format(DefaultCodeFormatter.java:205) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format2(CodeFormatterUtil.java:189) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format(CodeFormatterUtil.java:101) at org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy.format(JavaFormattingStrategy.java:95) at org.eclipse.jface.text.formatter.ContentFormatter2.format(ContentFormatter2.java:806) at org.eclipse.jface.text.formatter.ContentFormatter2.formatMaster(ContentFormatter2.java:661) at org.eclipse.jface.text.formatter.ContentFormatter2.format(ContentFormatter2.java:487) at org.eclipse.jdt.internal.ui.preferences.formatter.JavaPreview.update(JavaPreview.java:165) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage.updatePreview(ModifyDialogTabPage.java:378) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$1.update(ModifyDialogTabPage.java:46) at java.util.Observable.notifyObservers(Observable.java:142) at java.util.Observable.notifyObservers(Observable.java:98) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$NumberPreference.updatePreferences(ModifyDialogTabPage.java:246) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$NumberPreference.numberChanged(ModifyDialogTabPage.java:238) at org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage$5.modifyText(ModifyDialogTabPage.java:225) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:187) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:852) at org.eclipse.swt.widgets.Text.wmCommandChild(Text.java:2007) at org.eclipse.swt.widgets.Control.WM_COMMAND(Control.java:3069) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2942) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.CallWindowProc(OS.java:1293) at org.eclipse.swt.widgets.Text.callWindowProc(Text.java:127) at org.eclipse.swt.widgets.Control.windowProc(Control.java:3019) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1369) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1990) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.preferences.formatter.CodingStyleConfigurationBlock$ButtonController.modifyButtonPressed(CodingStyleConfigurationBlock.java:202) at org.eclipse.jdt.internal.ui.preferences.formatter.CodingStyleConfigurationBlock$ButtonController.widgetSelected(CodingStyleConfigurationBlock.java:177) 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:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2311) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1992) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.ui.internal.OpenPreferencesAction.run(OpenPreferencesAction.java:72) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:509) at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:461) at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:408) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2311) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1992) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:233) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:85) 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:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:281) at org.eclipse.core.launcher.Main.run(Main.java:744) at org.eclipse.core.launcher.Main.main(Main.java:583) !ENTRY org.eclipse.ui 4 4 Dez 17, 2003 11:22:49.680 !MESSAGE Unhandled event loop exception !ENTRY org.eclipse.ui 4 0 Dez 17, 2003 11:22:49.690 !MESSAGE / by zero !STACK 0 java.lang.ArithmeticException: / by zero at org.eclipse.jdt.internal.formatter.Scribe.getNextIndentationLevel(Scribe.java:327) at org.eclipse.jdt.internal.formatter.align.Alignment.checkColumn(Alignment.java:199) at org.eclipse.jdt.internal.formatter.Scribe.alignFragment(Scribe.java:178) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:517) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.formatTypeMembers(CodeFormatterVisitor.java:1566) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:925) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.visit(CodeFormatterVisitor.java:2372) at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.traverse(CompilationUnitDeclaration.java:292) at org.eclipse.jdt.internal.formatter.CodeFormatterVisitor.format(CodeFormatterVisitor.java:726) at org.eclipse.jdt.internal.formatter.DefaultCodeFormatter.formatCompilationUnit(DefaultCodeFormatter.java:238) at org.eclipse.jdt.internal.formatter.DefaultCodeFormatter.format(DefaultCodeFormatter.ja
|
verified fixed
|
df86372
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T13:20:50Z | 2003-12-17T11:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/OtherSettingsTabPage.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.formatter;
import java.util.Map;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
public class OtherSettingsTabPage extends ModifyDialogTabPage {
private final String preview=
createPreviewHeader("Other Settings") +
"class Example {" +
"int theInt= 1;" +
"String someString= \"Hello\";" +
"double aDouble= 3.0;" +
"void foo(int a, int b, int c, int d, int e, int f) {" +
"}" +
"}";
// private final String [] lineDelimiterNames= {
// "Unix", "Windows", "Mac"
// };
//
// private final String [] lineDelimiters= {
// "\n", "\r\n", "\r"
// };
private final String [] multiAlign= {
DefaultCodeFormatterConstants.FORMATTER_NO_ALIGNMENT,
DefaultCodeFormatterConstants.FORMATTER_MULTICOLUMN
};
private final int numColumns= 4;
/**
* Create a new GeneralSettingsTabPage.
*/
public OtherSettingsTabPage(Map workingValues) {
super(workingValues);
fJavaPreview.setPreviewText(preview);
}
protected Composite doCreatePreferences(Composite parent) {
final Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(createGridLayout(numColumns, false));
final Group generalGroup= createGroup(numColumns, composite, "General settings");
createNumberPref(generalGroup, numColumns, "Maximum line &width:", DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, 0, Integer.MAX_VALUE);
createNumberPref(generalGroup, numColumns, "Tab si&ze:", DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, 0, 999);
createCheckboxPref(generalGroup, numColumns, "U&se tab character", DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, new String [] {JavaCore.SPACE, JavaCore.TAB});
final Group typeMemberGroup= createGroup(numColumns, composite, "Alignment of fields in class declarations");
createCheckboxPref(typeMemberGroup, numColumns, "Align fields in &columns", DefaultCodeFormatterConstants.FORMATTER_TYPE_MEMBER_ALIGNMENT, multiAlign);
return composite;
}
}
|
48,852 |
Bug 48852 Found the followng exception in the log
|
I20031216 java.lang.IllegalArgumentException: at org.eclipse.core.internal.runtime.Assert.isLegal(Assert.java:56) at org.eclipse.core.internal.runtime.Assert.isLegal(Assert.java:41) at org.eclipse.core.runtime.Status.setMessage(Status.java:156) at org.eclipse.core.runtime.Status.<init>(Status.java:75) at org.eclipse.ui.editors.text.TextFileDocumentProvider.executeOperation (TextFileDocumentProvider.java:396) at org.eclipse.ui.editors.text.TextFileDocumentProvider.validateState (TextFileDocumentProvider.java:812) at org.eclipse.ui.texteditor.AbstractTextEditor.validateState (AbstractTextEditor.java:3035) at org.eclipse.ui.texteditor.AbstractTextEditor$16.run (AbstractTextEditor.java:3080) at org.eclipse.swt.custom.BusyIndicator.showWhile (BusyIndicator.java:84) at org.eclipse.ui.texteditor.AbstractTextEditor.validateEditorInputState (AbstractTextEditor.java:3075) at org.eclipse.ui.texteditor.AbstractTextEditor$ElementStateListener$Validator.ver ifyText(AbstractTextEditor.java:212) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:193) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:664) at org.eclipse.swt.custom.StyledText.modifyContent (StyledText.java:5947) at org.eclipse.swt.custom.StyledText.sendKeyEvent(StyledText.java:6931) at org.eclipse.swt.custom.StyledText.doContent(StyledText.java:2554) at org.eclipse.swt.custom.StyledText.handleKey(StyledText.java:5300) at org.eclipse.swt.custom.StyledText.handleKeyDown (StyledText.java:5323) at org.eclipse.swt.custom.StyledText$8.handleEvent (StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1716) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1712) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3036) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2939) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1369) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1990) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:233) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:84) 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:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:280) at org.eclipse.core.launcher.Main.run(Main.java:741) at org.eclipse.core.launcher.Main.main(Main.java:582)
|
verified fixed
|
0486978
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T14:30:20Z | 2003-12-16T15:53:20Z |
org.eclipse.jdt.ui/core
| |
48,852 |
Bug 48852 Found the followng exception in the log
|
I20031216 java.lang.IllegalArgumentException: at org.eclipse.core.internal.runtime.Assert.isLegal(Assert.java:56) at org.eclipse.core.internal.runtime.Assert.isLegal(Assert.java:41) at org.eclipse.core.runtime.Status.setMessage(Status.java:156) at org.eclipse.core.runtime.Status.<init>(Status.java:75) at org.eclipse.ui.editors.text.TextFileDocumentProvider.executeOperation (TextFileDocumentProvider.java:396) at org.eclipse.ui.editors.text.TextFileDocumentProvider.validateState (TextFileDocumentProvider.java:812) at org.eclipse.ui.texteditor.AbstractTextEditor.validateState (AbstractTextEditor.java:3035) at org.eclipse.ui.texteditor.AbstractTextEditor$16.run (AbstractTextEditor.java:3080) at org.eclipse.swt.custom.BusyIndicator.showWhile (BusyIndicator.java:84) at org.eclipse.ui.texteditor.AbstractTextEditor.validateEditorInputState (AbstractTextEditor.java:3075) at org.eclipse.ui.texteditor.AbstractTextEditor$ElementStateListener$Validator.ver ifyText(AbstractTextEditor.java:212) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:193) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:664) at org.eclipse.swt.custom.StyledText.modifyContent (StyledText.java:5947) at org.eclipse.swt.custom.StyledText.sendKeyEvent(StyledText.java:6931) at org.eclipse.swt.custom.StyledText.doContent(StyledText.java:2554) at org.eclipse.swt.custom.StyledText.handleKey(StyledText.java:5300) at org.eclipse.swt.custom.StyledText.handleKeyDown (StyledText.java:5323) at org.eclipse.swt.custom.StyledText$8.handleEvent (StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1716) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1712) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3036) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2939) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1369) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1990) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:233) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:84) 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:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:280) at org.eclipse.core.launcher.Main.run(Main.java:741) at org.eclipse.core.launcher.Main.main(Main.java:582)
|
verified fixed
|
0486978
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T14:30:20Z | 2003-12-16T15:53:20Z |
extension/org/eclipse/jdt/internal/corext/textmanipulation/TextBufferEditor.java
| |
48,852 |
Bug 48852 Found the followng exception in the log
|
I20031216 java.lang.IllegalArgumentException: at org.eclipse.core.internal.runtime.Assert.isLegal(Assert.java:56) at org.eclipse.core.internal.runtime.Assert.isLegal(Assert.java:41) at org.eclipse.core.runtime.Status.setMessage(Status.java:156) at org.eclipse.core.runtime.Status.<init>(Status.java:75) at org.eclipse.ui.editors.text.TextFileDocumentProvider.executeOperation (TextFileDocumentProvider.java:396) at org.eclipse.ui.editors.text.TextFileDocumentProvider.validateState (TextFileDocumentProvider.java:812) at org.eclipse.ui.texteditor.AbstractTextEditor.validateState (AbstractTextEditor.java:3035) at org.eclipse.ui.texteditor.AbstractTextEditor$16.run (AbstractTextEditor.java:3080) at org.eclipse.swt.custom.BusyIndicator.showWhile (BusyIndicator.java:84) at org.eclipse.ui.texteditor.AbstractTextEditor.validateEditorInputState (AbstractTextEditor.java:3075) at org.eclipse.ui.texteditor.AbstractTextEditor$ElementStateListener$Validator.ver ifyText(AbstractTextEditor.java:212) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:193) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:664) at org.eclipse.swt.custom.StyledText.modifyContent (StyledText.java:5947) at org.eclipse.swt.custom.StyledText.sendKeyEvent(StyledText.java:6931) at org.eclipse.swt.custom.StyledText.doContent(StyledText.java:2554) at org.eclipse.swt.custom.StyledText.handleKey(StyledText.java:5300) at org.eclipse.swt.custom.StyledText.handleKeyDown (StyledText.java:5323) at org.eclipse.swt.custom.StyledText$8.handleEvent (StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1716) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1712) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3036) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2939) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1369) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1990) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:233) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:84) 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:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:280) at org.eclipse.core.launcher.Main.run(Main.java:741) at org.eclipse.core.launcher.Main.main(Main.java:582)
|
verified fixed
|
0486978
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T14:30:20Z | 2003-12-16T15:53:20Z |
org.eclipse.jdt.ui/core
| |
48,852 |
Bug 48852 Found the followng exception in the log
|
I20031216 java.lang.IllegalArgumentException: at org.eclipse.core.internal.runtime.Assert.isLegal(Assert.java:56) at org.eclipse.core.internal.runtime.Assert.isLegal(Assert.java:41) at org.eclipse.core.runtime.Status.setMessage(Status.java:156) at org.eclipse.core.runtime.Status.<init>(Status.java:75) at org.eclipse.ui.editors.text.TextFileDocumentProvider.executeOperation (TextFileDocumentProvider.java:396) at org.eclipse.ui.editors.text.TextFileDocumentProvider.validateState (TextFileDocumentProvider.java:812) at org.eclipse.ui.texteditor.AbstractTextEditor.validateState (AbstractTextEditor.java:3035) at org.eclipse.ui.texteditor.AbstractTextEditor$16.run (AbstractTextEditor.java:3080) at org.eclipse.swt.custom.BusyIndicator.showWhile (BusyIndicator.java:84) at org.eclipse.ui.texteditor.AbstractTextEditor.validateEditorInputState (AbstractTextEditor.java:3075) at org.eclipse.ui.texteditor.AbstractTextEditor$ElementStateListener$Validator.ver ifyText(AbstractTextEditor.java:212) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:193) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:664) at org.eclipse.swt.custom.StyledText.modifyContent (StyledText.java:5947) at org.eclipse.swt.custom.StyledText.sendKeyEvent(StyledText.java:6931) at org.eclipse.swt.custom.StyledText.doContent(StyledText.java:2554) at org.eclipse.swt.custom.StyledText.handleKey(StyledText.java:5300) at org.eclipse.swt.custom.StyledText.handleKeyDown (StyledText.java:5323) at org.eclipse.swt.custom.StyledText$8.handleEvent (StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1716) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1712) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3036) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2939) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1369) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1990) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:233) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:84) 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:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:280) at org.eclipse.core.launcher.Main.run(Main.java:741) at org.eclipse.core.launcher.Main.main(Main.java:582)
|
verified fixed
|
0486978
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T14:30:20Z | 2003-12-16T15:53:20Z |
extension/org/eclipse/jdt/internal/corext/textmanipulation/TextBufferFactory.java
| |
48,852 |
Bug 48852 Found the followng exception in the log
|
I20031216 java.lang.IllegalArgumentException: at org.eclipse.core.internal.runtime.Assert.isLegal(Assert.java:56) at org.eclipse.core.internal.runtime.Assert.isLegal(Assert.java:41) at org.eclipse.core.runtime.Status.setMessage(Status.java:156) at org.eclipse.core.runtime.Status.<init>(Status.java:75) at org.eclipse.ui.editors.text.TextFileDocumentProvider.executeOperation (TextFileDocumentProvider.java:396) at org.eclipse.ui.editors.text.TextFileDocumentProvider.validateState (TextFileDocumentProvider.java:812) at org.eclipse.ui.texteditor.AbstractTextEditor.validateState (AbstractTextEditor.java:3035) at org.eclipse.ui.texteditor.AbstractTextEditor$16.run (AbstractTextEditor.java:3080) at org.eclipse.swt.custom.BusyIndicator.showWhile (BusyIndicator.java:84) at org.eclipse.ui.texteditor.AbstractTextEditor.validateEditorInputState (AbstractTextEditor.java:3075) at org.eclipse.ui.texteditor.AbstractTextEditor$ElementStateListener$Validator.ver ifyText(AbstractTextEditor.java:212) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:193) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:664) at org.eclipse.swt.custom.StyledText.modifyContent (StyledText.java:5947) at org.eclipse.swt.custom.StyledText.sendKeyEvent(StyledText.java:6931) at org.eclipse.swt.custom.StyledText.doContent(StyledText.java:2554) at org.eclipse.swt.custom.StyledText.handleKey(StyledText.java:5300) at org.eclipse.swt.custom.StyledText.handleKeyDown (StyledText.java:5323) at org.eclipse.swt.custom.StyledText$8.handleEvent (StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1716) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1712) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3036) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2939) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1369) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1990) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:233) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:84) 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:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:280) at org.eclipse.core.launcher.Main.run(Main.java:741) at org.eclipse.core.launcher.Main.main(Main.java:582)
|
verified fixed
|
0486978
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T14:30:20Z | 2003-12-16T15:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/IndentAction.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.actions;
import java.util.ResourceBundle;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.IRewriteTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.ITextEditorExtension3;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner;
import org.eclipse.jdt.internal.ui.text.JavaIndenter;
import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocAutoIndentStrategy;
/**
* Indents a line or range of lines in a Java document to its correct position. No complete
* AST must be present, the indentation is computed using heuristics. The algorith used is fast for
* single lines, but does not store any information and therefore not so efficient for large line
* ranges.
*
* @see org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner
* @see org.eclipse.jdt.internal.ui.text.JavaIndenter
* @since 3.0
*/
public class IndentAction extends TextEditorAction {
/** The caret offset after an indent operation. */
private int fCaretOffset;
/**
* Whether this is the action invoked by TAB. When <code>true</code>, indentation behaves
* differently to accomodate normal TAB operation.
*/
private final boolean fIsTabAction;
/**
* Creates a new instance.
*
* @param bundle the resource bundle
* @param prefix the prefix to use for keys in <code>bundle</code>
* @param editor the text editor
*/
public IndentAction(ResourceBundle bundle, String prefix, ITextEditor editor, boolean isTabAction) {
super(bundle, prefix, editor);
fIsTabAction= isTabAction;
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
// update has been called by the framework
if (!isEnabled() || !validateEditorInputState())
return;
ITextSelection selection= getSelection();
final IDocument document= getDocument();
if (document != null) {
final int offset= selection.getOffset();
final int length= selection.getLength();
final Position end= new Position(offset + length);
final int firstLine, nLines;
fCaretOffset= -1;
try {
document.addPosition(end);
firstLine= document.getLineOfOffset(offset);
// check for marginal (zero-length) lines
int minusOne= length == 0 ? 0 : 1;
nLines= document.getLineOfOffset(offset + length - minusOne) - firstLine + 1;
} catch (BadLocationException e) {
// will only happen on concurrent modification
JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, null, e));
return;
}
Runnable runnable= new Runnable() {
public void run() {
IRewriteTarget target= (IRewriteTarget)getTextEditor().getAdapter(IRewriteTarget.class);
if (target != null) {
target.beginCompoundChange();
target.setRedraw(false);
}
try {
JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
JavaIndenter indenter= new JavaIndenter(document, scanner);
boolean hasChanged= false;
for (int i= 0; i < nLines; i++) {
hasChanged |= indentLine(document, firstLine + i, offset, indenter, scanner);
}
// update caret position: move to new position when indenting just one line
// keep selection when indenting multiple
int newOffset, newLength;
if (fIsTabAction) {
newOffset= fCaretOffset;
newLength= 0;
} else if (nLines > 1) {
newOffset= offset;
newLength= end.getOffset() - offset;
} else {
newOffset= fCaretOffset;
newLength= 0;
}
// always reset the selection if anything was replaced
// but not when we had a singleline nontab invocation
if (newOffset != -1 && (hasChanged || newOffset != offset || newLength != length))
selectAndReveal(newOffset, newLength);
document.removePosition(end);
} catch (BadLocationException e) {
// will only happen on concurrent modification
JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, "ConcurrentModification in IndentAction", e)); //$NON-NLS-1$
} finally {
if (target != null) {
target.endCompoundChange();
target.setRedraw(true);
}
}
}
};
if (nLines > 50) {
Display display= getTextEditor().getEditorSite().getWorkbenchWindow().getShell().getDisplay();
BusyIndicator.showWhile(display, runnable);
} else
runnable.run();
}
}
/**
* Selects the given range on the editor.
*
* @param newOffset the selection offset
* @param newLength the selection range
*/
private void selectAndReveal(int newOffset, int newLength) {
Assert.isTrue(newOffset >= 0);
Assert.isTrue(newLength >= 0);
ITextEditor editor= getTextEditor();
if (editor instanceof JavaEditor) {
ISourceViewer viewer= ((JavaEditor)editor).getViewer();
if (viewer != null)
viewer.setSelectedRange(newOffset, newLength);
} else
// this is too intrusive, but will never get called anyway
getTextEditor().selectAndReveal(newOffset, newLength);
}
/**
* Indents a single line using the java heuristic scanner. Javadoc and multiline comments are
* indented as specified by the <code>JavaDocAutoIndentStrategy</code>.
*
* @param document the document
* @param line the line to be indented
* @param caret the caret position
* @param indenter the java indenter
* @param scanner the heuristic scanner
* @return <code>true</code> if <code>document</code> was modified, <code>false</code> otherwise
* @throws BadLocationException if the document got changed concurrently
*/
private boolean indentLine(IDocument document, int line, int caret, JavaIndenter indenter, JavaHeuristicScanner scanner) throws BadLocationException {
IRegion currentLine= document.getLineInformation(line);
int offset= currentLine.getOffset();
String indent= null;
if (offset < document.getLength()) {
ITypedRegion partition= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, offset);
String type= partition.getType();
if (partition.getOffset() < offset
&& type.equals(IJavaPartitions.JAVA_DOC)
|| type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) {
// TODO this is a hack
// what I want to do
// new JavaDocAutoIndentStrategy().indentLineAtOffset(document, offset);
// return;
int start= 0;
if (line > 0) {
IRegion previousLine= document.getLineInformation(line - 1);
start= previousLine.getOffset() + previousLine.getLength();
}
DocumentCommand command= new DocumentCommand() {};
command.text= "\n"; //$NON-NLS-1$
command.offset= start;
new JavaDocAutoIndentStrategy(IJavaPartitions.JAVA_PARTITIONING).customizeDocumentCommand(document, command);
int i= command.text.indexOf('*');
if (i != -1)
indent= command.text.substring(1, i);
else
indent= command.text.substring(1);
}
}
// standard java indentation
if (indent == null) {
StringBuffer computed= indenter.computeIndentation(offset);
if (computed != null)
indent= computed.toString();
else
indent= new String();
}
// change document:
// get current white space
int lineLength= currentLine.getLength();
int end= scanner.findNonWhitespaceForwardInAnyPartition(offset, offset + lineLength);
if (end == JavaHeuristicScanner.NOT_FOUND)
end= offset + lineLength;
int length= end - offset;
String currentIndent= document.get(offset, length);
// if we are right before the text start / line end, and already after the insertion point
// then just insert a tab.
if (fIsTabAction && caret == end && whiteSpaceLength(currentIndent) >= whiteSpaceLength(indent)) {
String tab= getTabEquivalent();
document.replace(caret, 0, tab);
fCaretOffset= caret + tab.length();
return true;
}
// set the caret offset so it can be used when setting the selection
if (caret >= offset && caret <= end)
fCaretOffset= offset + indent.length();
else
fCaretOffset= -1;
// only change the document if it is a real change
if (!indent.equals(currentIndent)) {
document.replace(offset, length, indent);
return true;
} else
return false;
}
/**
* Returns the size in characters of a string. All characters count one, tabs count the editor's
* preference for the tab display
*
* @param indent the string to be measured.
* @return
*/
private int whiteSpaceLength(String indent) {
if (indent == null)
return 0;
else {
int size= 0;
int l= indent.length();
int tabSize= JavaPlugin.getDefault().getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH);
for (int i= 0; i < l; i++)
size += indent.charAt(i) == '\t' ? tabSize : 1;
return size;
}
}
/**
* Returns a tab equivalent, either as a tab character or as spaces, depending on the editor and
* formatter preferences.
*
* @return a string representing one tab in the editor, never <code>null</code>
*/
private String getTabEquivalent() {
String tab;
if (JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SPACES_FOR_TABS)) {
int size= JavaCore.getPlugin().getPluginPreferences().getInt(JavaCore.FORMATTER_TAB_SIZE);
StringBuffer buf= new StringBuffer();
for (int i= 0; i< size; i++)
buf.append(' ');
tab= buf.toString();
} else
tab= "\t"; //$NON-NLS-1$
return tab;
}
/**
* Returns the editor's selection provider.
*
* @return the editor's selection provider or <code>null</code>
*/
private ISelectionProvider getSelectionProvider() {
ITextEditor editor= getTextEditor();
if (editor != null) {
return editor.getSelectionProvider();
}
return null;
}
/*
* @see org.eclipse.ui.texteditor.IUpdate#update()
*/
public void update() {
super.update();
if (isEnabled())
if (fIsTabAction)
setEnabled(canModifyEditor() && isSmartMode() && isValidSelection());
else
setEnabled(canModifyEditor() && !getSelection().isEmpty());
}
/**
* Returns if the current selection is valid, i.e. whether it is empty and the caret in the
* whitespace at the start of a line, or covers multiple lines.
*
* @return <code>true</code> if the selection is valid for an indent operation
*/
private boolean isValidSelection() {
ITextSelection selection= getSelection();
if (selection.isEmpty())
return false;
int offset= selection.getOffset();
int length= selection.getLength();
IDocument document= getDocument();
if (document == null)
return false;
try {
IRegion firstLine= document.getLineInformationOfOffset(offset);
int lineOffset= firstLine.getOffset();
// either the selection has to be empty and the caret in the WS at the line start
// or the selection has to extend over multiple lines
if (length == 0)
return document.get(lineOffset, offset - lineOffset).trim().length() == 0;
else
// return lineOffset + firstLine.getLength() < offset + length;
return false; // only enable for empty selections for now
} catch (BadLocationException e) {
}
return false;
}
/**
* Returns the smart preference state.
*
* @return <code>true</code> if smart mode is on, <code>false</code> otherwise
*/
private boolean isSmartMode() {
ITextEditor editor= getTextEditor();
if (editor instanceof ITextEditorExtension3)
return ((ITextEditorExtension3) editor).getInsertMode() == ITextEditorExtension3.SMART_INSERT;
return false;
}
/**
* Returns the document currently displayed in the editor, or <code>null</code> if none can be
* obtained.
*
* @return the current document or <code>null</code>
*/
private IDocument getDocument() {
ITextEditor editor= getTextEditor();
if (editor != null) {
IDocumentProvider provider= editor.getDocumentProvider();
IEditorInput input= editor.getEditorInput();
if (provider != null && input != null)
return provider.getDocument(input);
}
return null;
}
/**
* Returns the selection on the editor or an invalid selection if none can be obtained. Returns
* never <code>null</code>.
*
* @return the current selection, never <code>null</code>
*/
private ITextSelection getSelection() {
ISelectionProvider provider= getSelectionProvider();
if (provider != null) {
ISelection selection= provider.getSelection();
if (selection instanceof ITextSelection)
return (ITextSelection) selection;
}
// null object
return TextSelection.emptySelection();
}
}
|
48,852 |
Bug 48852 Found the followng exception in the log
|
I20031216 java.lang.IllegalArgumentException: at org.eclipse.core.internal.runtime.Assert.isLegal(Assert.java:56) at org.eclipse.core.internal.runtime.Assert.isLegal(Assert.java:41) at org.eclipse.core.runtime.Status.setMessage(Status.java:156) at org.eclipse.core.runtime.Status.<init>(Status.java:75) at org.eclipse.ui.editors.text.TextFileDocumentProvider.executeOperation (TextFileDocumentProvider.java:396) at org.eclipse.ui.editors.text.TextFileDocumentProvider.validateState (TextFileDocumentProvider.java:812) at org.eclipse.ui.texteditor.AbstractTextEditor.validateState (AbstractTextEditor.java:3035) at org.eclipse.ui.texteditor.AbstractTextEditor$16.run (AbstractTextEditor.java:3080) at org.eclipse.swt.custom.BusyIndicator.showWhile (BusyIndicator.java:84) at org.eclipse.ui.texteditor.AbstractTextEditor.validateEditorInputState (AbstractTextEditor.java:3075) at org.eclipse.ui.texteditor.AbstractTextEditor$ElementStateListener$Validator.ver ifyText(AbstractTextEditor.java:212) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:193) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:664) at org.eclipse.swt.custom.StyledText.modifyContent (StyledText.java:5947) at org.eclipse.swt.custom.StyledText.sendKeyEvent(StyledText.java:6931) at org.eclipse.swt.custom.StyledText.doContent(StyledText.java:2554) at org.eclipse.swt.custom.StyledText.handleKey(StyledText.java:5300) at org.eclipse.swt.custom.StyledText.handleKeyDown (StyledText.java:5323) at org.eclipse.swt.custom.StyledText$8.handleEvent (StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1716) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1712) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3036) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2939) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1369) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1990) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:233) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:84) 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:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:280) at org.eclipse.core.launcher.Main.run(Main.java:741) at org.eclipse.core.launcher.Main.main(Main.java:582)
|
verified fixed
|
0486978
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T14:30:20Z | 2003-12-16T15:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarPackageReader.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.jarpackager;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.util.Assert;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.jarpackager.IJarDescriptionReader;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
/**
* Reads data from an InputStream and returns a JarPackage
*/
public class JarPackageReader extends Object implements IJarDescriptionReader {
protected InputStream fInputStream;
private MultiStatus fWarnings;
/**
* Reads a Jar Package from the underlying stream.
* It is the client's responsiblity to close the stream.
*/
public JarPackageReader(InputStream inputStream) {
Assert.isNotNull(inputStream);
fInputStream= new BufferedInputStream(inputStream);
fWarnings= new MultiStatus(JavaPlugin.getPluginId(), 0, JarPackagerMessages.getString("JarPackageReader.jarPackageReaderWarnings"), null); //$NON-NLS-1$
}
public void read(JarPackageData jarPackage) throws CoreException {
try {
readXML(jarPackage);
} catch (IOException ex) {
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, ex.getLocalizedMessage(), ex));
} catch (SAXException ex) {
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, ex.getLocalizedMessage(), ex));
}
}
/**
* Closes this stream.
* It is the clients responsiblity to close the stream.
*
* @exception CoreException
*/
public void close() throws CoreException {
if (fInputStream != null)
try {
fInputStream.close();
} catch (IOException ex) {
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, ex.getLocalizedMessage(), ex));
}
}
public JarPackageData readXML(JarPackageData jarPackage) throws IOException, SAXException {
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder parser= null;
try {
parser= factory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
throw new IOException(ex.getLocalizedMessage());
} finally {
// Note: Above code is ok since clients are responsible to close the stream
}
Element xmlJarDesc= parser.parse(new InputSource(fInputStream)).getDocumentElement();
if (!xmlJarDesc.getNodeName().equals(JarPackagerUtil.DESCRIPTION_EXTENSION)) {
throw new IOException(JarPackagerMessages.getString("JarPackageReader.error.badFormat")); //$NON-NLS-1$
}
NodeList topLevelElements= xmlJarDesc.getChildNodes();
for (int i= 0; i < topLevelElements.getLength(); i++) {
Node node= topLevelElements.item(i);
if (node.getNodeType() != Node.ELEMENT_NODE)
continue;
Element element= (Element)node;
xmlReadJarLocation(jarPackage, element);
xmlReadOptions(jarPackage, element);
if (jarPackage.areClassFilesExported())
xmlReadManifest(jarPackage, element);
xmlReadSelectedElements(jarPackage, element);
}
return jarPackage;
}
private void xmlReadJarLocation(JarPackageData jarPackage, Element element) {
if (element.getNodeName().equals(JarPackagerUtil.JAR_EXTENSION))
jarPackage.setJarLocation(new Path(element.getAttribute("path"))); //$NON-NLS-1$
}
private void xmlReadOptions(JarPackageData jarPackage, Element element) throws java.io.IOException {
if (element.getNodeName().equals("options")) { //$NON-NLS-1$
jarPackage.setOverwrite(getBooleanAttribute(element, "overwrite")); //$NON-NLS-1$
jarPackage.setCompress(getBooleanAttribute(element, "compress")); //$NON-NLS-1$
jarPackage.setExportErrors(getBooleanAttribute(element, "exportErrors")); //$NON-NLS-1$
jarPackage.setExportWarnings(getBooleanAttribute(element, "exportWarnings")); //$NON-NLS-1$
jarPackage.setSaveDescription(getBooleanAttribute(element, "saveDescription")); //$NON-NLS-1$
jarPackage.setUseSourceFolderHierarchy(getBooleanAttribute(element, "useSourceFolders", false)); //$NON-NLS-1$
jarPackage.setDescriptionLocation(new Path(element.getAttribute("descriptionLocation"))); //$NON-NLS-1$
jarPackage.setBuildIfNeeded(getBooleanAttribute(element, "buildIfNeeded", jarPackage.isBuildingIfNeeded())); //$NON-NLS-1$
}
}
private void xmlReadManifest(JarPackageData jarPackage, Element element) throws java.io.IOException {
if (element.getNodeName().equals("manifest")) { //$NON-NLS-1$
jarPackage.setManifestVersion(element.getAttribute("manifestVersion")); //$NON-NLS-1$
jarPackage.setUsesManifest(getBooleanAttribute(element, "usesManifest")); //$NON-NLS-1$
jarPackage.setReuseManifest(getBooleanAttribute(element, "reuseManifest")); //$NON-NLS-1$
jarPackage.setSaveManifest(getBooleanAttribute(element,"saveManifest")); //$NON-NLS-1$
jarPackage.setGenerateManifest(getBooleanAttribute(element, "generateManifest")); //$NON-NLS-1$
jarPackage.setManifestLocation(new Path(element.getAttribute("manifestLocation"))); //$NON-NLS-1$
jarPackage.setManifestMainClass(getMainClass(element));
xmlReadSealingInfo(jarPackage, element);
}
}
private void xmlReadSealingInfo(JarPackageData jarPackage, Element element) throws java.io.IOException {
/*
* Try to find sealing info. Could ask for single child node
* but this would stop others from adding more child nodes to
* the manifest node.
*/
NodeList sealingElementContainer= element.getChildNodes();
for (int j= 0; j < sealingElementContainer.getLength(); j++) {
Node sealingNode= sealingElementContainer.item(j);
if (sealingNode.getNodeType() == Node.ELEMENT_NODE
&& sealingNode.getNodeName().equals("sealing")) { //$NON-NLS-1$
// Sealing
Element sealingElement= (Element)sealingNode;
jarPackage.setSealJar(getBooleanAttribute(sealingElement, "sealJar")); //$NON-NLS-1$
jarPackage.setPackagesToSeal(getPackages(sealingElement.getElementsByTagName("packagesToSeal"))); //$NON-NLS-1$
jarPackage.setPackagesToUnseal(getPackages(sealingElement.getElementsByTagName("packagesToUnSeal"))); //$NON-NLS-1$
}
}
}
private void xmlReadSelectedElements(JarPackageData jarPackage, Element element) throws java.io.IOException {
if (element.getNodeName().equals("selectedElements")) { //$NON-NLS-1$
jarPackage.setExportClassFiles(getBooleanAttribute(element, "exportClassFiles")); //$NON-NLS-1$
jarPackage.setExportJavaFiles(getBooleanAttribute(element, "exportJavaFiles")); //$NON-NLS-1$
NodeList selectedElements= element.getChildNodes();
Set elementsToExport= new HashSet(selectedElements.getLength());
for (int j= 0; j < selectedElements.getLength(); j++) {
Node selectedNode= selectedElements.item(j);
if (selectedNode.getNodeType() != Node.ELEMENT_NODE)
continue;
Element selectedElement= (Element)selectedNode;
if (selectedElement.getNodeName().equals("file")) //$NON-NLS-1$
addFile(elementsToExport, selectedElement);
else if (selectedElement.getNodeName().equals("folder")) //$NON-NLS-1$
addFolder(elementsToExport,selectedElement);
else if (selectedElement.getNodeName().equals("project")) //$NON-NLS-1$
addProject(elementsToExport ,selectedElement);
else if (selectedElement.getNodeName().equals("javaElement")) //$NON-NLS-1$
addJavaElement(elementsToExport, selectedElement);
// Note: Other file types are not handled by this writer
}
jarPackage.setElements(elementsToExport.toArray());
}
}
protected boolean getBooleanAttribute(Element element, String name, boolean defaultValue) throws IOException {
if (element.hasAttribute(name))
return getBooleanAttribute(element, name);
else
return defaultValue;
}
protected boolean getBooleanAttribute(Element element, String name) throws IOException {
String value= element.getAttribute(name);
if (value != null && value.equalsIgnoreCase("true")) //$NON-NLS-1$
return true;
if (value != null && value.equalsIgnoreCase("false")) //$NON-NLS-1$
return false;
throw new IOException(JarPackagerMessages.getString("JarPackageReader.error.illegalValueForBooleanAttribute")); //$NON-NLS-1$
}
private void addFile(Set selectedElements, Element element) throws IOException {
IPath path= getPath(element);
if (path != null) {
IFile file= JavaPlugin.getWorkspace().getRoot().getFile(path);
if (file != null)
selectedElements.add(file);
}
}
private void addFolder(Set selectedElements, Element element) throws IOException {
IPath path= getPath(element);
if (path != null) {
IFolder folder= JavaPlugin.getWorkspace().getRoot().getFolder(path);
if (folder != null)
selectedElements.add(folder);
}
}
private void addProject(Set selectedElements, Element element) throws IOException {
String name= element.getAttribute("name"); //$NON-NLS-1$
if (name.equals("")) //$NON-NLS-1$
throw new IOException(JarPackagerMessages.getString("JarPackageReader.error.tagNameNotFound")); //$NON-NLS-1$
IProject project= JavaPlugin.getWorkspace().getRoot().getProject(name);
if (project != null)
selectedElements.add(project);
}
private IPath getPath(Element element) throws IOException {
String pathString= element.getAttribute("path"); //$NON-NLS-1$
if (pathString.equals("")) //$NON-NLS-1$
throw new IOException(JarPackagerMessages.getString("JarPackageReader.error.tagPathNotFound")); //$NON-NLS-1$
return new Path(element.getAttribute("path")); //$NON-NLS-1$
}
private void addJavaElement(Set selectedElements, Element element) throws IOException {
String handleId= element.getAttribute("handleIdentifier"); //$NON-NLS-1$
if (handleId.equals("")) //$NON-NLS-1$
throw new IOException(JarPackagerMessages.getString("JarPackageReader.error.tagHandleIdentifierNotFoundOrEmpty")); //$NON-NLS-1$
IJavaElement je= JavaCore.create(handleId);
if (je == null)
addWarning(JarPackagerMessages.getString("JarPackageReader.warning.javaElementDoesNotExist"), null); //$NON-NLS-1$
else
selectedElements.add(je);
}
private IPackageFragment[] getPackages(NodeList list) throws IOException {
if (list.getLength() > 1)
throw new IOException(JarPackagerMessages.getFormattedString("JarPackageReader.error.duplicateTag", list.item(0).getNodeName())); //$NON-NLS-1$
if (list.getLength() == 0)
return null; // optional entry is not present
NodeList packageNodes= list.item(0).getChildNodes();
List packages= new ArrayList(packageNodes.getLength());
for (int i= 0; i < packageNodes.getLength(); i++) {
Node packageNode= packageNodes.item(i);
if (packageNode.getNodeType() == Node.ELEMENT_NODE && packageNode.getNodeName().equals("package")) { //$NON-NLS-1$
String handleId= ((Element)packageNode).getAttribute("handleIdentifier"); //$NON-NLS-1$
if (handleId.equals("")) //$NON-NLS-1$
throw new IOException(JarPackagerMessages.getString("JarPackageReader.error.tagHandleIdentifierNotFoundOrEmpty")); //$NON-NLS-1$
IJavaElement je= JavaCore.create(handleId);
if (je != null && je.getElementType() == IJavaElement.PACKAGE_FRAGMENT)
packages.add(je);
else
addWarning(JarPackagerMessages.getString("JarPackageReader.warning.javaElementDoesNotExist"), null); //$NON-NLS-1$
}
}
return (IPackageFragment[])packages.toArray(new IPackageFragment[packages.size()]);
}
private IType getMainClass(Element element) {
String handleId= element.getAttribute("mainClassHandleIdentifier"); //$NON-NLS-1$
if (handleId.equals("")) //$NON-NLS-1$
return null; // Main-Class entry is optional or can be empty
IJavaElement je= JavaCore.create(handleId);
if (je != null && je.getElementType() == IJavaElement.TYPE)
return (IType)je;
addWarning(JarPackagerMessages.getString("JarPackageReader.warning.mainClassDoesNotExist"), null); //$NON-NLS-1$
return null;
}
/**
* Returns the status of the reader.
* If there were any errors, the result is a status object containing
* individual status objects for each error.
* If there were no errors, the result is a status object with error code <code>OK</code>.
*
* @return the status of this operation
*/
public IStatus getStatus() {
if (fWarnings.getChildren().length == 0)
return new Status(IStatus.OK, JavaPlugin.getPluginId(), 0, "", null); //$NON-NLS-1$
else
return fWarnings;
}
/**
* Adds a new warning to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
protected void addWarning(String message, Throwable error) {
fWarnings.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), 0, message, error));
}
}
|
48,852 |
Bug 48852 Found the followng exception in the log
|
I20031216 java.lang.IllegalArgumentException: at org.eclipse.core.internal.runtime.Assert.isLegal(Assert.java:56) at org.eclipse.core.internal.runtime.Assert.isLegal(Assert.java:41) at org.eclipse.core.runtime.Status.setMessage(Status.java:156) at org.eclipse.core.runtime.Status.<init>(Status.java:75) at org.eclipse.ui.editors.text.TextFileDocumentProvider.executeOperation (TextFileDocumentProvider.java:396) at org.eclipse.ui.editors.text.TextFileDocumentProvider.validateState (TextFileDocumentProvider.java:812) at org.eclipse.ui.texteditor.AbstractTextEditor.validateState (AbstractTextEditor.java:3035) at org.eclipse.ui.texteditor.AbstractTextEditor$16.run (AbstractTextEditor.java:3080) at org.eclipse.swt.custom.BusyIndicator.showWhile (BusyIndicator.java:84) at org.eclipse.ui.texteditor.AbstractTextEditor.validateEditorInputState (AbstractTextEditor.java:3075) at org.eclipse.ui.texteditor.AbstractTextEditor$ElementStateListener$Validator.ver ifyText(AbstractTextEditor.java:212) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:193) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:664) at org.eclipse.swt.custom.StyledText.modifyContent (StyledText.java:5947) at org.eclipse.swt.custom.StyledText.sendKeyEvent(StyledText.java:6931) at org.eclipse.swt.custom.StyledText.doContent(StyledText.java:2554) at org.eclipse.swt.custom.StyledText.handleKey(StyledText.java:5300) at org.eclipse.swt.custom.StyledText.handleKeyDown (StyledText.java:5323) at org.eclipse.swt.custom.StyledText$8.handleEvent (StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1716) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1712) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3036) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2939) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1369) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1990) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:233) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:84) 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:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:280) at org.eclipse.core.launcher.Main.run(Main.java:741) at org.eclipse.core.launcher.Main.main(Main.java:582)
|
verified fixed
|
0486978
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T14:30:20Z | 2003-12-16T15:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarPackageWriter.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.jarpackager;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.ui.jarpackager.IJarDescriptionWriter;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Writes a JarPackage to an underlying OutputStream
*/
public class JarPackageWriter extends Object implements IJarDescriptionWriter {
protected OutputStream fOutputStream;
/**
* Create a JarPackageWriter on the given output stream.
* It is the clients responsibility to close the output stream.
*/
public JarPackageWriter(OutputStream outputStream) {
Assert.isNotNull(outputStream);
fOutputStream= new BufferedOutputStream(outputStream);
}
public void write(JarPackageData jarPackage) throws CoreException {
try {
writeXML(jarPackage);
} catch (IOException ex) {
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, ex.getLocalizedMessage(), ex));
}
}
/**
* Writes a XML representation of the JAR specification
* to to the underlying stream.
*
* @exception IOException if writing to the underlying stream fails
*/
public void writeXML(JarPackageData jarPackage) throws IOException {
Assert.isNotNull(jarPackage);
DocumentBuilder docBuilder= null;
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
factory.setValidating(false);
try {
docBuilder= factory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
throw new IOException(JarPackagerMessages.getString("JarWriter.error.couldNotGetXmlBuilder")); //$NON-NLS-1$
}
Document document= docBuilder.newDocument();
// Create the document
Element xmlJarDesc= document.createElement(JarPackagerUtil.DESCRIPTION_EXTENSION);
document.appendChild(xmlJarDesc);
xmlWriteJarLocation(jarPackage, document, xmlJarDesc);
xmlWriteOptions(jarPackage, document, xmlJarDesc);
if (jarPackage.areClassFilesExported())
xmlWriteManifest(jarPackage, document, xmlJarDesc);
xmlWriteSelectedElements(jarPackage, document, xmlJarDesc);
try {
// Write the document to the stream
Transformer transformer=TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); //$NON-NLS-1$ //$NON-NLS-2$
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(fOutputStream);
transformer.transform(source, result);
} catch (TransformerException e) {
throw new IOException(JarPackagerMessages.getString("JarWriter.error.couldNotTransformToXML")); //$NON-NLS-1$
}
}
private void xmlWriteJarLocation(JarPackageData jarPackage, Document document, Element xmlJarDesc) throws DOMException {
Element jar= document.createElement(JarPackagerUtil.JAR_EXTENSION);
xmlJarDesc.appendChild(jar);
jar.setAttribute("path", jarPackage.getJarLocation().toString()); //$NON-NLS-1$
}
private void xmlWriteOptions(JarPackageData jarPackage, Document document, Element xmlJarDesc) throws DOMException {
Element options= document.createElement("options"); //$NON-NLS-1$
xmlJarDesc.appendChild(options);
options.setAttribute("overwrite", "" + jarPackage.allowOverwrite()); //$NON-NLS-2$ //$NON-NLS-1$
options.setAttribute("compress", "" + jarPackage.isCompressed()); //$NON-NLS-2$ //$NON-NLS-1$
options.setAttribute("exportErrors", "" + jarPackage.areErrorsExported()); //$NON-NLS-2$ //$NON-NLS-1$
options.setAttribute("exportWarnings", "" + jarPackage.exportWarnings()); //$NON-NLS-2$ //$NON-NLS-1$
options.setAttribute("saveDescription", "" + jarPackage.isDescriptionSaved()); //$NON-NLS-2$ //$NON-NLS-1$
options.setAttribute("descriptionLocation", jarPackage.getDescriptionLocation().toString()); //$NON-NLS-1$
options.setAttribute("useSourceFolders", "" + jarPackage.useSourceFolderHierarchy()); //$NON-NLS-2$ //$NON-NLS-1$
options.setAttribute("buildIfNeeded", "" + jarPackage.isBuildingIfNeeded()); //$NON-NLS-2$ //$NON-NLS-1$
}
private void xmlWriteManifest(JarPackageData jarPackage, Document document, Element xmlJarDesc) throws DOMException {
Element manifest= document.createElement("manifest"); //$NON-NLS-1$
xmlJarDesc.appendChild(manifest);
manifest.setAttribute("manifestVersion", jarPackage.getManifestVersion()); //$NON-NLS-1$
manifest.setAttribute("usesManifest", "" + jarPackage.usesManifest()); //$NON-NLS-2$ //$NON-NLS-1$
manifest.setAttribute("reuseManifest", "" + jarPackage.isManifestReused()); //$NON-NLS-2$ //$NON-NLS-1$
manifest.setAttribute("saveManifest", "" + jarPackage.isManifestSaved()); //$NON-NLS-2$ //$NON-NLS-1$
manifest.setAttribute("generateManifest", "" + jarPackage.isManifestGenerated()); //$NON-NLS-2$ //$NON-NLS-1$
manifest.setAttribute("manifestLocation", jarPackage.getManifestLocation().toString()); //$NON-NLS-1$
if (jarPackage.getManifestMainClass() != null)
manifest.setAttribute("mainClassHandleIdentifier", jarPackage.getManifestMainClass().getHandleIdentifier()); //$NON-NLS-1$
xmlWriteSealingInfo(jarPackage, document, manifest);
}
private void xmlWriteSealingInfo(JarPackageData jarPackage, Document document, Element manifest) throws DOMException {
Element sealing= document.createElement("sealing"); //$NON-NLS-1$
manifest.appendChild(sealing);
sealing.setAttribute("sealJar", "" + jarPackage.isJarSealed()); //$NON-NLS-2$ //$NON-NLS-1$
Element packagesToSeal= document.createElement("packagesToSeal"); //$NON-NLS-1$
sealing.appendChild(packagesToSeal);
add(jarPackage.getPackagesToSeal(), packagesToSeal, document);
Element packagesToUnSeal= document.createElement("packagesToUnSeal"); //$NON-NLS-1$
sealing.appendChild(packagesToUnSeal);
add(jarPackage.getPackagesToUnseal(), packagesToUnSeal, document);
}
private void xmlWriteSelectedElements(JarPackageData jarPackage, Document document, Element xmlJarDesc) throws DOMException {
Element selectedElements= document.createElement("selectedElements"); //$NON-NLS-1$
xmlJarDesc.appendChild(selectedElements);
selectedElements.setAttribute("exportClassFiles", "" + jarPackage.areClassFilesExported()); //$NON-NLS-2$ //$NON-NLS-1$
selectedElements.setAttribute("exportJavaFiles", "" + jarPackage.areJavaFilesExported()); //$NON-NLS-2$ //$NON-NLS-1$
Object[] elements= jarPackage.getElements();
for (int i= 0; i < elements.length; i++) {
Object element= elements[i];
if (element instanceof IResource)
add((IResource)element, selectedElements, document);
else if (element instanceof IJavaElement)
add((IJavaElement)element, selectedElements, document);
// Note: Other file types are not handled by this writer
}
}
/**
* Writes a String representation of the JAR specification
* to to the underlying stream.
* @exception IOException Writing to the underlying stream.
*/
public void writeString(JarPackageData jarPackage) throws IOException {
Assert.isNotNull(jarPackage);
OutputStreamWriter streamWriter= new OutputStreamWriter(fOutputStream);
BufferedWriter writer= new BufferedWriter(streamWriter);
writer.write(JarPackagerMessages.getString("JarWriter.output.title")); //$NON-NLS-1$
writer.newLine();
writer.write(JarPackagerMessages.getFormattedString("JarWriter.output.exportBin", jarPackage.areClassFilesExported())); //$NON-NLS-1$
writer.newLine();
writer.write(JarPackagerMessages.getFormattedString("JarWriter.output.exportJava", jarPackage.areJavaFilesExported())); //$NON-NLS-1$
writer.newLine();
writer.write(JarPackagerMessages.getFormattedString("JarWriter.output.jarFileName", jarPackage.getJarLocation().toOSString())); //$NON-NLS-1$
writer.newLine();
writer.write(JarPackagerMessages.getFormattedString("JarWriter.output.compressed", jarPackage.isCompressed())); //$NON-NLS-1$
writer.newLine();
writer.write(JarPackagerMessages.getFormattedString("JarWriter.output.overwrite", jarPackage.allowOverwrite())); //$NON-NLS-1$
writer.newLine();
writer.write(JarPackagerMessages.getFormattedString("JarWriter.output.saveDescription", jarPackage.isDescriptionSaved())); //$NON-NLS-1$
writer.newLine();
writer.write(JarPackagerMessages.getFormattedString("JarWriter.output.descriptionFile", jarPackage.getDescriptionLocation())); //$NON-NLS-1$
writer.newLine();
writer.write(JarPackagerMessages.getString("JarWriter.output.lineSeparator")); //$NON-NLS-1$
writer.newLine();
writer.write(JarPackagerMessages.getFormattedString("JarWriter.output.generateManifest", jarPackage.isManifestGenerated())); //$NON-NLS-1$
writer.newLine();
writer.write(JarPackagerMessages.getFormattedString("JarWriter.output.saveManifest", jarPackage.isManifestSaved())); //$NON-NLS-1$
writer.newLine();
writer.write(JarPackagerMessages.getFormattedString("JarWriter.output.reuseManifest", jarPackage.isManifestReused())); //$NON-NLS-1$
writer.newLine();
writer.write(JarPackagerMessages.getFormattedString("JarWriter.output.manifestName", jarPackage.getManifestLocation())); //$NON-NLS-1$
writer.newLine();
writer.write(JarPackagerMessages.getFormattedString("JarWriter.output.jarSealed", jarPackage.isJarSealed())); //$NON-NLS-1$
writer.newLine();
writer.write(JarPackagerMessages.getFormattedString("JarWriter.output.mainClass", JarPackagerUtil.getMainClassName(jarPackage))); //$NON-NLS-1$
writer.flush();
}
/**
* Closes this stream.
* It is the client's responsibility to close the stream.
*
* @throws CoreException
*/
public void close() throws CoreException {
if (fOutputStream != null) {
try {
fOutputStream.close();
} catch (IOException ex) {
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, ex.getLocalizedMessage(), ex));
}
}
}
private void add(IResource resource, Element parent, Document document) {
Element element= null;
if (resource.getType() == IResource.PROJECT) {
element= document.createElement("project"); //$NON-NLS-1$
parent.appendChild(element);
element.setAttribute("name", resource.getName()); //$NON-NLS-1$
return;
}
if (resource.getType() == IResource.FILE)
element= document.createElement("file"); //$NON-NLS-1$
else if (resource.getType() == IResource.FOLDER)
element= document.createElement("folder"); //$NON-NLS-1$
parent.appendChild(element);
element.setAttribute("path", resource.getFullPath().toString()); //$NON-NLS-1$
}
private void add(IJavaElement javaElement, Element parent, Document document) {
Element element= document.createElement("javaElement"); //$NON-NLS-1$
parent.appendChild(element);
element.setAttribute("handleIdentifier", javaElement.getHandleIdentifier()); //$NON-NLS-1$
}
private void add(IPackageFragment[] packages, Element parent, Document document) {
for (int i= 0; i < packages.length; i++) {
Element pkg= document.createElement("package"); //$NON-NLS-1$
parent.appendChild(pkg);
pkg.setAttribute("handleIdentifier", packages[i].getHandleIdentifier()); //$NON-NLS-1$
}
}
/*
* This writer always returns OK
*/
public IStatus getStatus() {
return new Status(IStatus.OK, JavaPlugin.getPluginId(), 0, "", null); //$NON-NLS-1$
}
}
|
48,852 |
Bug 48852 Found the followng exception in the log
|
I20031216 java.lang.IllegalArgumentException: at org.eclipse.core.internal.runtime.Assert.isLegal(Assert.java:56) at org.eclipse.core.internal.runtime.Assert.isLegal(Assert.java:41) at org.eclipse.core.runtime.Status.setMessage(Status.java:156) at org.eclipse.core.runtime.Status.<init>(Status.java:75) at org.eclipse.ui.editors.text.TextFileDocumentProvider.executeOperation (TextFileDocumentProvider.java:396) at org.eclipse.ui.editors.text.TextFileDocumentProvider.validateState (TextFileDocumentProvider.java:812) at org.eclipse.ui.texteditor.AbstractTextEditor.validateState (AbstractTextEditor.java:3035) at org.eclipse.ui.texteditor.AbstractTextEditor$16.run (AbstractTextEditor.java:3080) at org.eclipse.swt.custom.BusyIndicator.showWhile (BusyIndicator.java:84) at org.eclipse.ui.texteditor.AbstractTextEditor.validateEditorInputState (AbstractTextEditor.java:3075) at org.eclipse.ui.texteditor.AbstractTextEditor$ElementStateListener$Validator.ver ifyText(AbstractTextEditor.java:212) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:193) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:664) at org.eclipse.swt.custom.StyledText.modifyContent (StyledText.java:5947) at org.eclipse.swt.custom.StyledText.sendKeyEvent(StyledText.java:6931) at org.eclipse.swt.custom.StyledText.doContent(StyledText.java:2554) at org.eclipse.swt.custom.StyledText.handleKey(StyledText.java:5300) at org.eclipse.swt.custom.StyledText.handleKeyDown (StyledText.java:5323) at org.eclipse.swt.custom.StyledText$8.handleEvent (StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1716) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1712) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3036) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2939) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1369) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1990) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:233) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:84) 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:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:280) at org.eclipse.core.launcher.Main.run(Main.java:741) at org.eclipse.core.launcher.Main.main(Main.java:582)
|
verified fixed
|
0486978
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T14:30:20Z | 2003-12-16T15:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitDocumentProvider.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.javaeditor;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IMarkerDelta;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultLineTracker;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ILineTracker;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationModelEvent;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelListener;
import org.eclipse.jface.text.source.IAnnotationModelListenerExtension;
import org.eclipse.jface.text.source.IAnnotationPresentation;
import org.eclipse.ui.editors.text.FileDocumentProvider;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
import org.eclipse.ui.texteditor.DefaultAnnotation;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.MarkerUtilities;
import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaModelStatusConstants;
import org.eclipse.jdt.core.IProblemRequestor;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.JavaUIStatus;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
import org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension;
public class CompilationUnitDocumentProvider extends FileDocumentProvider implements ICompilationUnitDocumentProvider {
/**
* Here for visibility issues only.
*/
protected class _FileSynchronizer extends FileSynchronizer {
public _FileSynchronizer(IFileEditorInput fileEditorInput) {
super(fileEditorInput);
}
}
/**
* Bundle of all required informations to allow working copy management.
*/
protected class CompilationUnitInfo extends FileInfo {
ICompilationUnit fCopy;
public CompilationUnitInfo(IDocument document, IAnnotationModel model, _FileSynchronizer fileSynchronizer, ICompilationUnit copy) {
super(document, model, fileSynchronizer);
fCopy= copy;
}
public void setModificationStamp(long timeStamp) {
fModificationStamp= timeStamp;
}
}
/**
* Annotation representating an <code>IProblem</code>.
*/
static protected class ProblemAnnotation extends Annotation implements IJavaAnnotation, IAnnotationPresentation {
private static Image fgQuickFixImage;
private static Image fgQuickFixErrorImage;
private static boolean fgQuickFixImagesInitialized= false;
private ICompilationUnit fCompilationUnit;
private List fOverlaids;
private IProblem fProblem;
private Image fImage;
private boolean fQuickFixImagesInitialized= false;
public ProblemAnnotation(IProblem problem, ICompilationUnit cu) {
fProblem= problem;
fCompilationUnit= cu;
if (IProblem.Task == fProblem.getID()) {
setType(JavaMarkerAnnotation.TASK_ANNOTATION_TYPE);
setLayer(DefaultAnnotation.TASK_LAYER + 1);
} else if (fProblem.isWarning()) {
setType(JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE);
setLayer(DefaultAnnotation.WARNING_LAYER + 1);
} else if (fProblem.isError()) {
setType(JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE);
setLayer(DefaultAnnotation.ERROR_LAYER + 1);
} else {
setType(JavaMarkerAnnotation.INFO_ANNOTATION_TYPE);
setLayer(DefaultAnnotation.INFO_LAYER + 1);
}
}
private void initializeImages() {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=18936
if (!fQuickFixImagesInitialized) {
if (isProblem() && indicateQuixFixableProblems() && JavaCorrectionProcessor.hasCorrections(this)) { // no light bulb for tasks
if (!fgQuickFixImagesInitialized) {
fgQuickFixImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM);
fgQuickFixErrorImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_ERROR);
fgQuickFixImagesInitialized= true;
}
if (JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(getType()))
fImage= fgQuickFixErrorImage;
else
fImage= fgQuickFixImage;
}
fQuickFixImagesInitialized= true;
}
}
private boolean indicateQuixFixableProblems() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION);
}
/*
* @see Annotation#paint
*/
public void paint(GC gc, Canvas canvas, Rectangle r) {
initializeImages();
if (fImage != null)
drawImage(fImage, gc, canvas, r, SWT.CENTER, SWT.TOP);
}
/*
* @see IJavaAnnotation#getImage(Display)
*/
public Image getImage(Display display) {
initializeImages();
return fImage;
}
/*
* @see IJavaAnnotation#getMessage()
*/
public String getText() {
return fProblem.getMessage();
}
/*
* @see IJavaAnnotation#getArguments()
*/
public String[] getArguments() {
return isProblem() ? fProblem.getArguments() : null;
}
/*
* @see IJavaAnnotation#getId()
*/
public int getId() {
return fProblem.getID();
}
/*
* @see IJavaAnnotation#isProblem()
*/
public boolean isProblem() {
String type= getType();
return JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE.equals(type) || JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(type);
}
/*
* @see IJavaAnnotation#hasOverlay()
*/
public boolean hasOverlay() {
return false;
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation#getOverlay()
*/
public IJavaAnnotation getOverlay() {
return null;
}
/*
* @see IJavaAnnotation#addOverlaid(IJavaAnnotation)
*/
public void addOverlaid(IJavaAnnotation annotation) {
if (fOverlaids == null)
fOverlaids= new ArrayList(1);
fOverlaids.add(annotation);
}
/*
* @see IJavaAnnotation#removeOverlaid(IJavaAnnotation)
*/
public void removeOverlaid(IJavaAnnotation annotation) {
if (fOverlaids != null) {
fOverlaids.remove(annotation);
if (fOverlaids.size() == 0)
fOverlaids= null;
}
}
/*
* @see IJavaAnnotation#getOverlaidIterator()
*/
public Iterator getOverlaidIterator() {
if (fOverlaids != null)
return fOverlaids.iterator();
return null;
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation#getCompilationUnit()
*/
public ICompilationUnit getCompilationUnit() {
return fCompilationUnit;
}
}
/**
* Internal structure for mapping positions to some value.
* The reason for this specific structure is that positions can
* change over time. Thus a lookup is based on value and not
* on hash value.
*/
protected static class ReverseMap {
static class Entry {
Position fPosition;
Object fValue;
}
private List fList= new ArrayList(2);
private int fAnchor= 0;
public ReverseMap() {
}
public Object get(Position position) {
Entry entry;
// behind anchor
int length= fList.size();
for (int i= fAnchor; i < length; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position)) {
fAnchor= i;
return entry.fValue;
}
}
// before anchor
for (int i= 0; i < fAnchor; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position)) {
fAnchor= i;
return entry.fValue;
}
}
return null;
}
private int getIndex(Position position) {
Entry entry;
int length= fList.size();
for (int i= 0; i < length; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position))
return i;
}
return -1;
}
public void put(Position position, Object value) {
int index= getIndex(position);
if (index == -1) {
Entry entry= new Entry();
entry.fPosition= position;
entry.fValue= value;
fList.add(entry);
} else {
Entry entry= (Entry) fList.get(index);
entry.fValue= value;
}
}
public void remove(Position position) {
int index= getIndex(position);
if (index > -1)
fList.remove(index);
}
public void clear() {
fList.clear();
}
}
/**
* Annotation model dealing with java marker annotations and temporary problems.
* Also acts as problem requestor for its compilation unit. Initialiy inactive. Must explicitly be
* activated.
*/
protected class CompilationUnitAnnotationModel extends ResourceMarkerAnnotationModel implements IProblemRequestor, IProblemRequestorExtension {
private IFileEditorInput fInput;
private List fCollectedProblems;
private List fGeneratedAnnotations;
private IProgressMonitor fProgressMonitor;
private boolean fIsActive= false;
private ReverseMap fReverseMap= new ReverseMap();
private List fPreviouslyOverlaid= null;
private List fCurrentlyOverlaid= new ArrayList();
private boolean fIncludesProblemAnnotationChanges= false;
public CompilationUnitAnnotationModel(IFileEditorInput input) {
super(input.getFile());
fInput= input;
}
protected MarkerAnnotation createMarkerAnnotation(IMarker marker) {
String markerType= MarkerUtilities.getMarkerType(marker);
if (markerType != null && markerType.startsWith(JavaMarkerAnnotation.JAVA_MARKER_TYPE_PREFIX))
return new JavaMarkerAnnotation(marker);
return super.createMarkerAnnotation(marker);
}
/*
* @see org.eclipse.jface.text.source.AnnotationModel#createAnnotationModelEvent()
*/
protected AnnotationModelEvent createAnnotationModelEvent() {
return new CompilationUnitAnnotationModelEvent(this, getResource());
}
protected Position createPositionFromProblem(IProblem problem) {
int start= problem.getSourceStart();
if (start < 0)
return null;
int length= problem.getSourceEnd() - problem.getSourceStart() + 1;
if (length < 0)
return null;
return new Position(start, length);
}
protected void update(IMarkerDelta[] markerDeltas) {
super.update(markerDeltas);
if (fIncludesProblemAnnotationChanges) {
try {
ICompilationUnit workingCopy= getWorkingCopy(fInput);
if (workingCopy != null)
workingCopy.reconcile(true, null);
} catch (JavaModelException ex) {
if (!ex.isDoesNotExist())
handleCoreException(ex, ex.getMessage());
}
}
}
/*
* @see IProblemRequestor#beginReporting()
*/
public void beginReporting() {
ICompilationUnit unit= getWorkingCopy(fInput);
if (unit != null && unit.getJavaProject().isOnClasspath(unit))
fCollectedProblems= new ArrayList();
else
fCollectedProblems= null;
}
/*
* @see IProblemRequestor#acceptProblem(IProblem)
*/
public void acceptProblem(IProblem problem) {
if (isActive())
fCollectedProblems.add(problem);
}
/*
* @see IProblemRequestor#endReporting()
*/
public void endReporting() {
if (!isActive())
return;
if (fProgressMonitor != null && fProgressMonitor.isCanceled())
return;
boolean isCanceled= false;
boolean temporaryProblemsChanged= false;
synchronized (fAnnotations) {
fPreviouslyOverlaid= fCurrentlyOverlaid;
fCurrentlyOverlaid= new ArrayList();
if (fGeneratedAnnotations.size() > 0) {
temporaryProblemsChanged= true;
removeAnnotations(fGeneratedAnnotations, false, true);
fGeneratedAnnotations.clear();
}
if (fCollectedProblems != null && fCollectedProblems.size() > 0) {
ICompilationUnit cu= getWorkingCopy(fInput);
Iterator e= fCollectedProblems.iterator();
while (e.hasNext()) {
IProblem problem= (IProblem) e.next();
if (fProgressMonitor != null && fProgressMonitor.isCanceled()) {
isCanceled= true;
break;
}
Position position= createPositionFromProblem(problem);
if (position != null) {
try {
ProblemAnnotation annotation= new ProblemAnnotation(problem, cu);
addAnnotation(annotation, position, false);
overlayMarkers(position, annotation);
fGeneratedAnnotations.add(annotation);
temporaryProblemsChanged= true;
} catch (BadLocationException x) {
// ignore invalid position
}
}
}
fCollectedProblems.clear();
}
removeMarkerOverlays(isCanceled);
fPreviouslyOverlaid.clear();
fPreviouslyOverlaid= null;
}
if (temporaryProblemsChanged)
fireModelChanged();
}
private void removeMarkerOverlays(boolean isCanceled) {
if (isCanceled) {
fCurrentlyOverlaid.addAll(fPreviouslyOverlaid);
} else if (fPreviouslyOverlaid != null) {
Iterator e= fPreviouslyOverlaid.iterator();
while (e.hasNext()) {
JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) e.next();
annotation.setOverlay(null);
}
}
}
/**
* Overlays value with problem annotation.
* @param problemAnnotation
*/
private void setOverlay(Object value, ProblemAnnotation problemAnnotation) {
if (value instanceof JavaMarkerAnnotation) {
JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) value;
if (annotation.isProblem()) {
annotation.setOverlay(problemAnnotation);
fPreviouslyOverlaid.remove(annotation);
fCurrentlyOverlaid.add(annotation);
}
}
}
private void overlayMarkers(Position position, ProblemAnnotation problemAnnotation) {
Object value= getAnnotations(position);
if (value instanceof List) {
List list= (List) value;
for (Iterator e = list.iterator(); e.hasNext();)
setOverlay(e.next(), problemAnnotation);
} else {
setOverlay(value, problemAnnotation);
}
}
/**
* Tells this annotation model to collect temporary problems from now on.
*/
private void startCollectingProblems() {
fCollectedProblems= new ArrayList();
fGeneratedAnnotations= new ArrayList();
}
/**
* Tells this annotation model to no longer collect temporary problems.
*/
private void stopCollectingProblems() {
if (fGeneratedAnnotations != null) {
removeAnnotations(fGeneratedAnnotations, true, true);
fGeneratedAnnotations.clear();
}
fCollectedProblems= null;
fGeneratedAnnotations= null;
}
/*
* @see org.eclipse.jface.text.source.AnnotationModel#fireModelChanged(org.eclipse.jface.text.source.AnnotationModelEvent)
*/
protected void fireModelChanged(AnnotationModelEvent event) {
if (event instanceof CompilationUnitAnnotationModelEvent) {
CompilationUnitAnnotationModelEvent e= (CompilationUnitAnnotationModelEvent) event;
fIncludesProblemAnnotationChanges= e.includesProblemMarkerAnnotationChanges();
}
super.fireModelChanged(event);
}
/*
* @see IProblemRequestor#isActive()
*/
public boolean isActive() {
return fIsActive && (fCollectedProblems != null);
}
/*
* @see IProblemRequestorExtension#setProgressMonitor(IProgressMonitor)
*/
public void setProgressMonitor(IProgressMonitor monitor) {
fProgressMonitor= monitor;
}
/*
* @see IProblemRequestorExtension#setIsActive(boolean)
*/
public void setIsActive(boolean isActive) {
if (fIsActive != isActive) {
fIsActive= isActive;
if (fIsActive)
startCollectingProblems();
else
stopCollectingProblems();
}
}
private Object getAnnotations(Position position) {
return fReverseMap.get(position);
}
/*
* @see AnnotationModel#addAnnotation(Annotation, Position, boolean)
*/
protected void addAnnotation(Annotation annotation, Position position, boolean fireModelChanged) throws BadLocationException {
super.addAnnotation(annotation, position, fireModelChanged);
Object cached= fReverseMap.get(position);
if (cached == null)
fReverseMap.put(position, annotation);
else if (cached instanceof List) {
List list= (List) cached;
list.add(annotation);
} else if (cached instanceof Annotation) {
List list= new ArrayList(2);
list.add(cached);
list.add(annotation);
fReverseMap.put(position, list);
}
}
/*
* @see AnnotationModel#removeAllAnnotations(boolean)
*/
protected void removeAllAnnotations(boolean fireModelChanged) {
super.removeAllAnnotations(fireModelChanged);
fReverseMap.clear();
}
/*
* @see AnnotationModel#removeAnnotation(Annotation, boolean)
*/
protected void removeAnnotation(Annotation annotation, boolean fireModelChanged) {
Position position= getPosition(annotation);
Object cached= fReverseMap.get(position);
if (cached instanceof List) {
List list= (List) cached;
list.remove(annotation);
if (list.size() == 1) {
fReverseMap.put(position, list.get(0));
list.clear();
}
} else if (cached instanceof Annotation) {
fReverseMap.remove(position);
}
super.removeAnnotation(annotation, fireModelChanged);
}
}
protected static class GlobalAnnotationModelListener implements IAnnotationModelListener, IAnnotationModelListenerExtension {
private ListenerList fListenerList;
public GlobalAnnotationModelListener() {
fListenerList= new ListenerList();
}
/**
* @see IAnnotationModelListener#modelChanged(IAnnotationModel)
*/
public void modelChanged(IAnnotationModel model) {
Object[] listeners= fListenerList.getListeners();
for (int i= 0; i < listeners.length; i++) {
((IAnnotationModelListener) listeners[i]).modelChanged(model);
}
}
/**
* @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent)
*/
public void modelChanged(AnnotationModelEvent event) {
Object[] listeners= fListenerList.getListeners();
for (int i= 0; i < listeners.length; i++) {
Object curr= listeners[i];
if (curr instanceof IAnnotationModelListenerExtension) {
((IAnnotationModelListenerExtension) curr).modelChanged(event);
}
}
}
public void addListener(IAnnotationModelListener listener) {
fListenerList.add(listener);
}
public void removeListener(IAnnotationModelListener listener) {
fListenerList.remove(listener);
}
}
/** Preference key for temporary problems */
private final static String HANDLE_TEMPORARY_PROBLEMS= PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS;
/** Indicates whether the save has been initialized by this provider */
private boolean fIsAboutToSave= false;
/** The save policy used by this provider */
private ISavePolicy fSavePolicy;
/** Internal property changed listener */
private IPropertyChangeListener fPropertyListener;
/** Annotation model listener added to all created CU annotation models */
private GlobalAnnotationModelListener fGlobalAnnotationModelListener;
/**
* Constructor
*/
public CompilationUnitDocumentProvider() {
fPropertyListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty()))
enableHandlingTemporaryProblems();
}
};
fGlobalAnnotationModelListener= new GlobalAnnotationModelListener();
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyListener);
}
/**
* Creates a compilation unit from the given file.
*
* @param file the file from which to create the compilation unit
*/
protected ICompilationUnit createCompilationUnit(IFile file) {
Object element= JavaCore.create(file);
if (element instanceof ICompilationUnit)
return (ICompilationUnit) element;
return null;
}
/*
* @see AbstractDocumentProvider#createElementInfo(Object)
*/
protected ElementInfo createElementInfo(Object element) throws CoreException {
if ( !(element instanceof IFileEditorInput))
return super.createElementInfo(element);
IFileEditorInput input= (IFileEditorInput) element;
ICompilationUnit original= createCompilationUnit(input.getFile());
if (original != null) {
try {
try {
refreshFile(input.getFile());
} catch (CoreException x) {
handleCoreException(x, JavaEditorMessages.getString("CompilationUnitDocumentProvider.error.createElementInfo")); //$NON-NLS-1$
}
IAnnotationModel m= createCompilationUnitAnnotationModel(input);
IProblemRequestor r= m instanceof IProblemRequestor ? (IProblemRequestor) m : null;
ICompilationUnit c= null;
if (JavaPlugin.USE_WORKING_COPY_OWNERS) {
original.becomeWorkingCopy(r, getProgressMonitor());
c= original;
} else {
c= (ICompilationUnit) original.getSharedWorkingCopy(getProgressMonitor(), JavaPlugin.getDefault().getBufferFactory(), r);
}
DocumentAdapter a= null;
try {
a= (DocumentAdapter) c.getBuffer();
} catch (ClassCastException x) {
IStatus status= new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IJavaStatusConstants.TEMPLATE_IO_EXCEPTION, "Shared working copy has wrong buffer", x); //$NON-NLS-1$
throw new CoreException(status);
}
_FileSynchronizer f= new _FileSynchronizer(input);
f.install();
CompilationUnitInfo info= new CompilationUnitInfo(a.getDocument(), m, f, c);
info.setModificationStamp(computeModificationStamp(input.getFile()));
info.fStatus= a.getStatus();
info.fEncoding= getPersistedEncoding(input);
if (r instanceof IProblemRequestorExtension) {
IProblemRequestorExtension extension= (IProblemRequestorExtension) r;
extension.setIsActive(isHandlingTemporaryProblems());
}
m.addAnnotationModelListener(fGlobalAnnotationModelListener);
return info;
} catch (JavaModelException x) {
throw new CoreException(x.getStatus());
}
} else {
return super.createElementInfo(element);
}
}
/*
* @see AbstractDocumentProvider#disposeElementInfo(Object, ElementInfo)
*/
protected void disposeElementInfo(Object element, ElementInfo info) {
if (info instanceof CompilationUnitInfo) {
CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
if (JavaPlugin.USE_WORKING_COPY_OWNERS) {
try {
cuInfo.fCopy.discardWorkingCopy();
} catch (JavaModelException x) {
handleCoreException(x, x.getMessage());
}
} else {
cuInfo.fCopy.destroy();
}
cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener);
}
super.disposeElementInfo(element, info);
}
/*
* @see AbstractDocumentProvider#doSaveDocument(IProgressMonitor, Object, IDocument, boolean)
*/
protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException {
ElementInfo elementInfo= getElementInfo(element);
if (elementInfo instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo) elementInfo;
synchronized (info.fCopy) {
info.fCopy.reconcile();
}
ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement();
IResource resource= original.getResource();
if (resource == null) {
// underlying resource has been deleted, just recreate file, ignore the rest
super.doSaveDocument(monitor, element, document, overwrite);
return;
}
if (resource != null && !overwrite)
checkSynchronizationState(info.fModificationStamp, resource);
if (fSavePolicy != null)
fSavePolicy.preSave(info.fCopy);
// inform about the upcoming content change
fireElementStateChanging(element);
try {
fIsAboutToSave= true;
// commit working copy
if (JavaPlugin.USE_WORKING_COPY_OWNERS)
info.fCopy.commitWorkingCopy(overwrite, monitor);
else
info.fCopy.commit(overwrite, monitor);
} catch (CoreException x) {
// inform about the failure
fireElementStateChangeFailed(element);
throw x;
} catch (RuntimeException x) {
// inform about the failure
fireElementStateChangeFailed(element);
throw x;
} finally {
fIsAboutToSave= false;
}
// If here, the dirty state of the editor will change to "not dirty".
// Thus, the state changing flag will be reset.
AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel;
model.updateMarkers(info.fDocument);
if (resource != null)
info.setModificationStamp(computeModificationStamp(resource));
if (fSavePolicy != null) {
ICompilationUnit unit= fSavePolicy.postSave(original);
if (unit != null) {
IResource r= unit.getResource();
IMarker[] markers= r.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO);
if (markers != null && markers.length > 0) {
for (int i= 0; i < markers.length; i++)
model.updateMarker(markers[i], info.fDocument, null);
}
}
}
} else {
super.doSaveDocument(monitor, element, document, overwrite);
}
}
/**
* Replaces createAnnotionModel of the super class.
*/
protected IAnnotationModel createCompilationUnitAnnotationModel(Object element) throws CoreException {
if ( !(element instanceof IFileEditorInput))
throw new CoreException(JavaUIStatus.createError(
IJavaModelStatusConstants.INVALID_RESOURCE_TYPE, "", null)); //$NON-NLS-1$
IFileEditorInput input= (IFileEditorInput) element;
return new CompilationUnitAnnotationModel(input);
}
/*
* @see org.eclipse.ui.editors.text.StorageDocumentProvider#createEmptyDocument()
*/
protected IDocument createEmptyDocument() {
return new PartiallySynchronizedDocument();
}
/*
* @see org.eclipse.ui.texteditor.AbstractDocumentProvider#doResetDocument(java.lang.Object, org.eclipse.core.runtime.IProgressMonitor)
*/
protected void doResetDocument(Object element, IProgressMonitor monitor) throws CoreException {
if (element == null)
return;
ElementInfo elementInfo= getElementInfo(element);
if (elementInfo instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo) elementInfo;
IDocument document;
IStatus status= null;
try {
ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement();
IResource resource= original.getResource();
if (resource instanceof IFile) {
IFile file= (IFile) resource;
try {
refreshFile(file, monitor);
} catch (CoreException x) {
handleCoreException(x, JavaEditorMessages.getString("CompilationUnitDocumentProvider.error.resetDocument")); //$NON-NLS-1$
}
IFileEditorInput input= new FileEditorInput(file);
document= super.createDocument(input);
} else {
document= createEmptyDocument();
}
} catch (CoreException x) {
document= createEmptyDocument();
status= x.getStatus();
}
fireElementContentAboutToBeReplaced(element);
removeUnchangedElementListeners(element, info);
info.fDocument.set(document.get());
info.fCanBeSaved= false;
info.fStatus= status;
addUnchangedElementListeners(element, info);
fireElementContentReplaced(element);
fireElementDirtyStateChanged(element, false);
} else {
super.doResetDocument(element, monitor);
}
}
/**
* Returns the preference whether handling temporary problems is enabled.
*/
protected boolean isHandlingTemporaryProblems() {
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
return store.getBoolean(HANDLE_TEMPORARY_PROBLEMS);
}
/**
* Switches the state of problem acceptance according to the value in the preference store.
*/
protected void enableHandlingTemporaryProblems() {
boolean enable= isHandlingTemporaryProblems();
for (Iterator iter= getConnectedElements(); iter.hasNext();) {
ElementInfo element= getElementInfo(iter.next());
if (element instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo)element;
if (info.fModel instanceof IProblemRequestorExtension) {
IProblemRequestorExtension extension= (IProblemRequestorExtension) info.fModel;
extension.setIsActive(enable);
}
}
}
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#saveDocumentContent(org.eclipse.core.runtime.IProgressMonitor, java.lang.Object, org.eclipse.jface.text.IDocument, boolean)
*/
public void saveDocumentContent(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException {
if (!fIsAboutToSave)
return;
if (element instanceof IFileEditorInput) {
IFileEditorInput input= (IFileEditorInput) element;
try {
String encoding= getEncoding(element);
if (encoding == null)
encoding= ResourcesPlugin.getEncoding();
InputStream stream= new ByteArrayInputStream(document.get().getBytes(encoding));
IFile file= input.getFile();
file.setContents(stream, overwrite, true, monitor);
} catch (IOException x) {
IStatus s= new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.OK, x.getMessage(), x);
throw new CoreException(s);
}
}
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#shutdown()
*/
public void shutdown() {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyListener);
Iterator e= getConnectedElements();
while (e.hasNext())
disconnect(e.next());
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#addGlobalAnnotationModelListener(org.eclipse.jface.text.source.IAnnotationModelListener)
*/
public void addGlobalAnnotationModelListener(IAnnotationModelListener listener) {
fGlobalAnnotationModelListener.addListener(listener);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#removeGlobalAnnotationModelListener(org.eclipse.jface.text.source.IAnnotationModelListener)
*/
public void removeGlobalAnnotationModelListener(IAnnotationModelListener listener) {
fGlobalAnnotationModelListener.removeListener(listener);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#getWorkingCopy(java.lang.Object)
*/
public ICompilationUnit getWorkingCopy(Object element) {
ElementInfo elementInfo= getElementInfo(element);
if (elementInfo instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo) elementInfo;
return info.fCopy;
}
return null;
}
/*
* @see org.eclipse.ui.texteditor.IDocumentProviderExtension3#createEmptyDocument(java.lang.Object)
*/
public IDocument createEmptyDocument(Object element) {
return createEmptyDocument();
}
/*
* @see org.eclipse.ui.editors.text.StorageDocumentProvider#setupDocument(java.lang.Object, org.eclipse.jface.text.IDocument)
*/
protected void setupDocument(Object element, IDocument document) {
if (document != null) {
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
tools.setupJavaDocumentPartitioner(document, IJavaPartitions.JAVA_PARTITIONING);
}
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#createLineTracker(java.lang.Object)
*/
public ILineTracker createLineTracker(Object element) {
return new DefaultLineTracker();
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#setSavePolicy(org.eclipse.jdt.internal.ui.javaeditor.ISavePolicy)
*/
public void setSavePolicy(ISavePolicy savePolicy) {
fSavePolicy= savePolicy;
}
/*
* Here for visibility reasons.
* @see AbstractDocumentProvider#createDocument(Object)
*/
public IDocument createDocument(Object element) throws CoreException {
return super.createDocument(element);
}
}
|
48,871 |
Bug 48871 NPE in JavaAnnotationHover when hovering over left ruler
|
I200312160010 + export from 1158. I just found this in the log but could not reproduce. The caret was in the method name of a declaration ... private boolean accessesAnnonymousFields() { ... and I hovered over the left ruler. After the NPE was logged, the hover over the left ruler didn't appear any more. It only came back after closing and repoening the editor. I have "Mark occurrences in file" and "Enable light bulb for quick assist" switched on and the method was new and marked by QuickDiff in a block of added lines. Error Dec 16, 2003 17:15:02.738 java.lang.NullPointerException java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.JavaAnnotationHover.isDuplicateJavaAnnotation(JavaAnnotationHover.java:154) at org.eclipse.jdt.internal.ui.text.JavaAnnotationHover.getJavaAnnotationsForLine(JavaAnnotationHover.java:135) at org.eclipse.jdt.internal.ui.text.JavaAnnotationHover.getHoverInfo(JavaAnnotationHover.java:178) at org.eclipse.jface.text.source.AnnotationBarHoverManager.computeInformation(AnnotationBarHoverManager.java:100) at org.eclipse.jface.text.AbstractInformationControlManager.doShowInformation(AbstractInformationControlManager.java:661) at org.eclipse.jface.text.AbstractHoverInformationControlManager$MouseTracker.mouseHover(AbstractHoverInformationControlManager.java:298) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:215) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2311) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1992) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:233) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:84) 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:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:280) at org.eclipse.core.launcher.Main.run(Main.java:741) at org.eclipse.core.launcher.Main.main(Main.java:582)
|
verified fixed
|
2eb76ff
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T14:53:06Z | 2003-12-16T15:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaAnnotationHover.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;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationHover;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.AnnotationPreferenceLookup;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
/**
* Determines all markers for the given line and collects, concatenates, and formates
* their messages.
*/
public class JavaAnnotationHover implements IAnnotationHover {
private static class JavaAnnotationHoverType {
}
public static final JavaAnnotationHoverType OVERVIEW_RULER_HOVER= new JavaAnnotationHoverType();
public static final JavaAnnotationHoverType TEXT_RULER_HOVER= new JavaAnnotationHoverType();
public static final JavaAnnotationHoverType VERTICAL_RULER_HOVER= new JavaAnnotationHoverType();
private AnnotationPreferenceLookup fPreferenceLookup= new AnnotationPreferenceLookup();
private IPreferenceStore fStore= JavaPlugin.getDefault().getPreferenceStore();
private JavaAnnotationHoverType fType;
public JavaAnnotationHover(JavaAnnotationHoverType type) {
Assert.isTrue(OVERVIEW_RULER_HOVER.equals(type) || TEXT_RULER_HOVER.equals(type) || VERTICAL_RULER_HOVER.equals(type));
fType= type;
}
/**
* Returns the distance to the ruler line.
*/
protected int compareRulerLine(Position position, IDocument document, int line) {
if (position.getOffset() > -1 && position.getLength() > -1) {
try {
int javaAnnotationLine= document.getLineOfOffset(position.getOffset());
if (line == javaAnnotationLine)
return 1;
if (javaAnnotationLine <= line && line <= document.getLineOfOffset(position.getOffset() + position.getLength()))
return 2;
} catch (BadLocationException x) {
}
}
return 0;
}
/**
* Selects a set of markers from the two lists. By default, it just returns
* the set of exact matches.
*/
protected List select(List exactMatch, List including) {
return exactMatch;
}
/**
* Returns one marker which includes the ruler's line of activity.
*/
protected List getJavaAnnotationsForLine(ISourceViewer viewer, int line) {
IDocument document= viewer.getDocument();
IAnnotationModel model= viewer.getAnnotationModel();
if (model == null)
return null;
List exact= new ArrayList();
List including= new ArrayList();
Iterator e= model.getAnnotationIterator();
HashMap messagesAtPosition= new HashMap();
while (e.hasNext()) {
Annotation annotation= (Annotation) e.next();
Position position= model.getPosition(annotation);
if (position == null)
continue;
AnnotationPreference preference= getAnnotationPreference(annotation);
if (preference == null)
continue;
if (OVERVIEW_RULER_HOVER.equals(fType)) {
String key= preference.getOverviewRulerPreferenceKey();
if (key == null || !fStore.getBoolean(key))
continue;
} else if (TEXT_RULER_HOVER.equals(fType)) {
String key= preference.getTextPreferenceKey();
if (key != null) {
if (!fStore.getBoolean(key))
continue;
} else {
key= preference.getHighlightPreferenceKey();
if (key == null || !fStore.getBoolean(key))
continue;
}
} else if (VERTICAL_RULER_HOVER.equals(fType)) {
String key= preference.getVerticalRulerPreferenceKey();
// backward compatibility
if (key != null && !fStore.getBoolean(key))
continue;
}
if (isDuplicateJavaAnnotation(messagesAtPosition, position, annotation.getText()))
continue;
switch (compareRulerLine(position, document, line)) {
case 1:
exact.add(annotation);
break;
case 2:
including.add(annotation);
break;
}
}
return select(exact, including);
}
private boolean isDuplicateJavaAnnotation(Map messagesAtPosition, Position position, String message) {
if (messagesAtPosition.containsKey(position)) {
Object value= messagesAtPosition.get(position);
if (message.equals(value))
return true;
if (value instanceof List) {
List messages= (List)value;
if (messages.contains(message))
return true;
else
messages.add(message);
} else {
ArrayList messages= new ArrayList();
messages.add(value);
messages.add(message);
messagesAtPosition.put(position, messages);
}
} else
messagesAtPosition.put(position, message);
return false;
}
/*
* @see IVerticalRulerHover#getHoverInfo(ISourceViewer, int)
*/
public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) {
List javaAnnotations= getJavaAnnotationsForLine(sourceViewer, lineNumber);
if (javaAnnotations != null) {
if (javaAnnotations.size() == 1) {
// optimization
Annotation annotation= (Annotation) javaAnnotations.get(0);
String message= annotation.getText();
if (message != null && message.trim().length() > 0)
return formatSingleMessage(message);
} else {
List messages= new ArrayList();
Iterator e= javaAnnotations.iterator();
while (e.hasNext()) {
Annotation annotation= (Annotation) e.next();
String message= annotation.getText();
if (message != null && message.trim().length() > 0)
messages.add(message.trim());
}
if (messages.size() == 1)
return formatSingleMessage((String) messages.get(0));
if (messages.size() > 1)
return formatMultipleMessages(messages);
}
}
return null;
}
/*
* Formats a message as HTML text.
*/
private String formatSingleMessage(String message) {
StringBuffer buffer= new StringBuffer();
HTMLPrinter.addPageProlog(buffer);
HTMLPrinter.addParagraph(buffer, HTMLPrinter.convertToHTMLContent(message));
HTMLPrinter.addPageEpilog(buffer);
return buffer.toString();
}
/*
* Formats several message as HTML text.
*/
private String formatMultipleMessages(List messages) {
StringBuffer buffer= new StringBuffer();
HTMLPrinter.addPageProlog(buffer);
HTMLPrinter.addParagraph(buffer, HTMLPrinter.convertToHTMLContent(JavaUIMessages.getString("JavaAnnotationHover.multipleMarkersAtThisLine"))); //$NON-NLS-1$
HTMLPrinter.startBulletList(buffer);
Iterator e= messages.iterator();
while (e.hasNext())
HTMLPrinter.addBullet(buffer, HTMLPrinter.convertToHTMLContent((String) e.next()));
HTMLPrinter.endBulletList(buffer);
HTMLPrinter.addPageEpilog(buffer);
return buffer.toString();
}
/**
* Returns the annotation preference for the given annotation.
*
* @param annotation the annotation
* @return the annotation preference or <code>null</code> if none
*/
private AnnotationPreference getAnnotationPreference(Annotation annotation) {
return fPreferenceLookup.getAnnotationPreference(annotation);
}
}
|
49,004 |
Bug 49004 primary_type_name misses the last character in the name
|
20031217 set template to try { ${line_selection}${cursor} } catch (${Exception} e) { // ${todo}: handle exception ${primary_type_name} } results in try { codeStream.invokespecial(this.binding); } catch (Exception e) { // TODO: handle exception CodeSnippetAllocationExpressio }
|
verified fixed
|
5d42efb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T15:08:21Z | 2003-12-17T14:06:40Z |
org.eclipse.jdt.ui/core
| |
49,004 |
Bug 49004 primary_type_name misses the last character in the name
|
20031217 set template to try { ${line_selection}${cursor} } catch (${Exception} e) { // ${todo}: handle exception ${primary_type_name} } results in try { codeStream.invokespecial(this.binding); } catch (Exception e) { // TODO: handle exception CodeSnippetAllocationExpressio }
|
verified fixed
|
5d42efb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-17T15:08:21Z | 2003-12-17T14:06:40Z |
extension/org/eclipse/jdt/internal/corext/template/java/CompilationUnitContextType.java
| |
47,617 |
Bug 47617 Error during Java AST creation.
|
I am using M5 under Sun JDK 1.4.2_02. I got the following error while opening my workspace. It happened while the automatic startup refresh was in progress. The log entry is attached. !SESSION Nov 27, 2003 06:13:53.142 -------------------------------------------- - java.version=1.4.2 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_US Command-line arguments: -os win32 -ws win32 -arch x86 -data e:\ThoughtWorkspace -showlocation -install file:E:/Eclipse-M5-3.0/eclipse/ !ENTRY org.eclipse.core.runtime 4 2 Nov 27, 2003 06:13:53.142 !MESSAGE An internal error occurred during: "Java AST creation". !STACK 0 java.util.ConcurrentModificationException at java.util.AbstractList$Itr.checkForComodification (AbstractList.java:448) at java.util.AbstractList$Itr.next(AbstractList.java:419) at org.eclipse.jdt.internal.ui.javaeditor.filebuffers.CompilationUnitDocumentProvi der2$CompilationUnitAnnotationModel.endReporting (CompilationUnitDocumentProvider2.java:468) at org.eclipse.jdt.internal.core.JavaModelManager$PerWorkingCopyInfo.endReporting (JavaModelManager.java:516) at org.eclipse.jdt.internal.core.CompilationUnit.buildStructure (CompilationUnit.java:143) at org.eclipse.jdt.internal.core.Openable.generateInfos (Openable.java:200) at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed (JavaElement.java:487) at org.eclipse.jdt.internal.core.JavaElement.getElementInfo (JavaElement.java:279) at org.eclipse.jdt.internal.core.JavaElement.getElementInfo (JavaElement.java:265) at org.eclipse.jdt.internal.core.Openable.getBuffer(Openable.java:227) at org.eclipse.jdt.internal.core.CompilationUnit.getSource (CompilationUnit.java:756) at org.eclipse.jdt.core.dom.AST.parseCompilationUnit(AST.java:330) at org.eclipse.jdt.core.dom.AST.parseCompilationUnit(AST.java:247) at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartLis tenerGroup.computeAST(SelectionListenerWithASTManager.java:106) at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartLis tenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:116) at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$1.run (SelectionListenerWithASTManager.java:92) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:62)
|
resolved fixed
|
51271af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-19T10:18:06Z | 2003-11-27T10:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/SelectionListenerWithASTManager.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 java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISelectionService;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
/**
* Infrastructure to share an AST for editor post selection listeners.
*/
public class SelectionListenerWithASTManager {
private static SelectionListenerWithASTManager fgDefault;
/**
* @return Returns the default manager instance.
*/
public static SelectionListenerWithASTManager getDefault() {
if (fgDefault == null) {
fgDefault= new SelectionListenerWithASTManager();
}
return fgDefault;
}
private static class PartListenerGroup {
private IEditorPart fPart;
private Job fCurrentJob;
private ListenerList fAstListeners;
public PartListenerGroup(IEditorPart part) {
fPart= part;
fCurrentJob= null;
fAstListeners= new ListenerList();
}
public boolean isEmpty() {
return fAstListeners.isEmpty();
}
public void install(ISelectionListenerWithAST listener) {
fAstListeners.add(listener);
}
public void uninstall(ISelectionListenerWithAST listener) {
fAstListeners.remove(listener);
}
public void fireSelectionChanged(final ITextSelection selection) {
if (fCurrentJob != null) {
fCurrentJob.cancel();
fCurrentJob= null;
}
fCurrentJob= new Job(JavaUIMessages.getString("SelectionListenerWithASTManager.job.title")) { //$NON-NLS-1$
public IStatus run(IProgressMonitor monitor) {
synchronized (PartListenerGroup.this) {
if (this != fCurrentJob) {
return Status.OK_STATUS;
}
calculateASTandInform(selection);
return Status.OK_STATUS;
}
}
};
fCurrentJob.setPriority(Job.DECORATE);
fCurrentJob.schedule();
}
private CompilationUnit computeAST() {
IEditorInput editorInput= fPart.getEditorInput();
if (editorInput != null) {
IJavaElement element= (IJavaElement) editorInput.getAdapter(IJavaElement.class);
if (element instanceof ICompilationUnit) {
return AST.parseCompilationUnit((ICompilationUnit) element, true);
}
if (element instanceof IClassFile) {
return AST.parseCompilationUnit((IClassFile) element, true);
}
}
return null;
}
protected void calculateASTandInform(ITextSelection selection) {
CompilationUnit astRoot= computeAST();
if (astRoot != null) {
Object[] listeners= fAstListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
((ISelectionListenerWithAST) listeners[i]).selectionChanged(fPart, selection, astRoot);
}
}
}
}
private static class WorkbenchWindowListener implements ISelectionListener {
private ISelectionService fSelectionService;
private Map fPartListeners; // key: IEditorPart, value: PartListenerGroup
public WorkbenchWindowListener(ISelectionService service) {
fSelectionService= service;
fPartListeners= new HashMap();
}
public boolean isEmpty() {
return fPartListeners.isEmpty();
}
public void install(IEditorPart part, ISelectionListenerWithAST listener) {
if (fPartListeners.isEmpty()) {
fSelectionService.addPostSelectionListener(this);
}
PartListenerGroup listenerGroup= (PartListenerGroup) fPartListeners.get(part);
if (listenerGroup == null) {
listenerGroup= new PartListenerGroup(part);
fPartListeners.put(part, listenerGroup);
}
listenerGroup.install(listener);
}
public void uninstall(IEditorPart part, ISelectionListenerWithAST listener) {
PartListenerGroup listenerGroup= (PartListenerGroup) fPartListeners.get(part);
if (listenerGroup == null) {
return;
}
listenerGroup.uninstall(listener);
if (listenerGroup.isEmpty()) {
fPartListeners.remove(part);
if (fPartListeners.isEmpty()) {
fSelectionService.removePostSelectionListener(this);
}
}
}
/* (non-Javadoc)
* @see org.eclipse.ui.ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if (part instanceof IEditorPart && selection instanceof ITextSelection) { // only editor parts are interesting
PartListenerGroup listenerGroup= (PartListenerGroup) fPartListeners.get(part);
if (listenerGroup != null) {
listenerGroup.fireSelectionChanged((ITextSelection) selection);
}
}
}
}
private Map fListenerGroups;
private SelectionListenerWithASTManager() {
fListenerGroups= new HashMap();
}
/**
* Registers a selection listener for the given editor part.
* @param part The editor part to listen to.
* @param listener The listener to register.
*/
public void addListener(IEditorPart part, ISelectionListenerWithAST listener) {
ISelectionService service= part.getSite().getWorkbenchWindow().getSelectionService();
WorkbenchWindowListener windowListener= (WorkbenchWindowListener) fListenerGroups.get(service);
if (windowListener == null) {
windowListener= new WorkbenchWindowListener(service);
fListenerGroups.put(service, windowListener);
}
windowListener.install(part, listener);
}
/**
* Unregisters a selection listener.
* @param part The editor part the listener was registered.
* @param listener The listener to unregister.
*/
public void removeListener(IEditorPart part, ISelectionListenerWithAST listener) {
ISelectionService service= part.getSite().getWorkbenchWindow().getSelectionService();
WorkbenchWindowListener windowListener= (WorkbenchWindowListener) fListenerGroups.get(service);
if (windowListener != null) {
windowListener.uninstall(part, listener);
if (windowListener.isEmpty()) {
fListenerGroups.remove(service);
}
}
}
}
|
49,084 |
Bug 49084 formatter StringIndexOutOfBoundsException
|
java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.charAt(String.java:444) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.isDifferent(CodeFormatterUtil.java:395) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.commentDifferent(CodeFormatterUtil.java:353) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.emulateNewWithOld(CodeFormatterUtil.java:317) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format2(CodeFormatterUtil.java:187) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format(CodeFormatterUtil.java:101) at org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy.format(JavaFormattingStrategy.java:86) at org.eclipse.jface.text.formatter.ContentFormatter2.format(ContentFormatter2.java:806) at org.eclipse.jface.text.formatter.ContentFormatter2.formatMaster(ContentFormatter2.java:661) at org.eclipse.jface.text.formatter.ContentFormatter2.format(ContentFormatter2.java:487) at org.eclipse.jface.text.source.SourceViewer.doOperation(SourceViewer.java:668) at org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer.doOperation(JavaSourceViewer.java:124) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$AdaptedSourceViewer.doOperation(CompilationUnitEditor.java:174) at org.eclipse.ui.texteditor.TextOperationAction$1.run(TextOperationAction.java:122) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.ui.texteditor.TextOperationAction.run(TextOperationAction.java:120) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:509) at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:461) at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:408) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2294) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1975) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:242) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:84) 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:324) at org.eclipse.core.internal.boot.OSGiBootLoader.basicRun(OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) 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:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Against 3.0 i20031211 see attached source to format.
|
resolved fixed
|
69f144c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-19T14:30:18Z | 2003-12-17T22:26:40Z |
org.eclipse.jdt.ui/core
| |
49,084 |
Bug 49084 formatter StringIndexOutOfBoundsException
|
java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.charAt(String.java:444) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.isDifferent(CodeFormatterUtil.java:395) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.commentDifferent(CodeFormatterUtil.java:353) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.emulateNewWithOld(CodeFormatterUtil.java:317) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format2(CodeFormatterUtil.java:187) at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.format(CodeFormatterUtil.java:101) at org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy.format(JavaFormattingStrategy.java:86) at org.eclipse.jface.text.formatter.ContentFormatter2.format(ContentFormatter2.java:806) at org.eclipse.jface.text.formatter.ContentFormatter2.formatMaster(ContentFormatter2.java:661) at org.eclipse.jface.text.formatter.ContentFormatter2.format(ContentFormatter2.java:487) at org.eclipse.jface.text.source.SourceViewer.doOperation(SourceViewer.java:668) at org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer.doOperation(JavaSourceViewer.java:124) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$AdaptedSourceViewer.doOperation(CompilationUnitEditor.java:174) at org.eclipse.ui.texteditor.TextOperationAction$1.run(TextOperationAction.java:122) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.ui.texteditor.TextOperationAction.run(TextOperationAction.java:120) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:509) at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:461) at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:408) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2294) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1975) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:242) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:84) 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:324) at org.eclipse.core.internal.boot.OSGiBootLoader.basicRun(OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) 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:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Against 3.0 i20031211 see attached source to format.
|
resolved fixed
|
69f144c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-19T14:30:18Z | 2003-12-17T22:26:40Z |
extension/org/eclipse/jdt/internal/corext/util/CodeFormatterUtil.java
| |
48,999 |
Bug 48999 Anonym type can have field as parent
|
JavaElementLabels does only the 'is parent method' test
|
resolved fixed
|
39cf123
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-19T15:45:28Z | 2003-12-17T14:06:40Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/JavaElementLabelsTest.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.tests.core;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
public class JavaElementLabelsTest extends CoreTests {
private static final Class THIS= JavaElementLabelsTest.class;
private IJavaProject fJProject1;
public JavaElementLabelsTest(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 JavaElementLabelsTest("testOrganizeImportOnRange2"));
return new ProjectTestSetup(suite);
}
}
protected void setUp() throws Exception {
fJProject1= ProjectTestSetup.getProject();
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
store.setValue(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES, false);
}
protected void tearDown() throws Exception {
JavaProjectHelper.clear(fJProject1, ProjectTestSetup.getDefaultClasspath());
}
public void testTypeLabelOuter() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("org.test", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package org.test;\n");
buf.append("public class Outer {\n");
buf.append("}\n");
String content= buf.toString();
ICompilationUnit cu= pack1.createCompilationUnit("Outer.java", content, false, null);
IJavaElement elem= cu.getElementAt(content.indexOf("Outer"));
String lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_FULLY_QUALIFIED);
assertEqualString(lab, "org.test.Outer");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_CONTAINER_QUALIFIED);
assertEqualString(lab, "Outer");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_POST_QUALIFIED);
assertEqualString(lab, "Outer - org.test");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.APPEND_ROOT_PATH);
assertEqualString(lab, "org.test.Outer - TestSetupProject/src");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.PREPEND_ROOT_PATH);
assertEqualString(lab, "TestSetupProject/src - org.test.Outer");
}
public void testTypeLabelInner() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("org.test", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package org.test;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class Outer {\n");
buf.append(" public void foo(Vector vec) {\n");
buf.append(" }\n");
buf.append(" public class Inner {\n");
buf.append(" public int inner(Vector vec) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String content= buf.toString();
ICompilationUnit cu= pack1.createCompilationUnit("Outer.java", content, false, null);
IJavaElement elem= cu.getElementAt(content.indexOf("Inner"));
String lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_FULLY_QUALIFIED);
assertEqualString(lab, "org.test.Outer.Inner");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_CONTAINER_QUALIFIED);
assertEqualString(lab, "Outer.Inner");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_POST_QUALIFIED);
assertEqualString(lab, "Inner - org.test.Outer");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.APPEND_ROOT_PATH);
assertEqualString(lab, "org.test.Outer.Inner - TestSetupProject/src");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.PREPEND_ROOT_PATH);
assertEqualString(lab, "TestSetupProject/src - org.test.Outer.Inner");
}
public void testTypeLabelLocal() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("org.test", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package org.test;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class Outer {\n");
buf.append(" public void foo(Vector vec) {\n");
buf.append(" public class Local {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String content= buf.toString();
ICompilationUnit cu= pack1.createCompilationUnit("Outer.java", content, false, null);
IJavaElement elem= cu.getElementAt(content.indexOf("Local"));
String lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_FULLY_QUALIFIED);
assertEqualString(lab, "org.test.Outer.foo(..).Local");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_CONTAINER_QUALIFIED);
assertEqualString(lab, "Outer.foo(..).Local");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_POST_QUALIFIED);
assertEqualString(lab, "Local - org.test.Outer.foo(..)");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.APPEND_ROOT_PATH);
assertEqualString(lab, "org.test.Outer.foo(..).Local - TestSetupProject/src");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.PREPEND_ROOT_PATH);
assertEqualString(lab, "TestSetupProject/src - org.test.Outer.foo(..).Local");
}
public void testTypeLabelAnonymous() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("org.test", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package org.test;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class Outer {\n");
buf.append(" public void foo(Vector vec) {\n");
buf.append(" new Object() {\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
String content= buf.toString();
ICompilationUnit cu= pack1.createCompilationUnit("Outer.java", content, false, null);
IJavaElement elem= cu.getElementAt(content.indexOf("Object"));
String lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_FULLY_QUALIFIED);
assertEqualString(lab, "org.test.Outer.foo(..).new Object() {..}");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_CONTAINER_QUALIFIED);
assertEqualString(lab, "Outer.foo(..).new Object() {..}");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_POST_QUALIFIED);
assertEqualString(lab, "new Object() {..} - org.test.Outer.foo(..)");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.APPEND_ROOT_PATH);
assertEqualString(lab, "org.test.Outer.foo(..).new Object() {..} - TestSetupProject/src");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.PREPEND_ROOT_PATH);
assertEqualString(lab, "TestSetupProject/src - org.test.Outer.foo(..).new Object() {..}");
}
public void testTypeLabelAnonymousInAnonymous() throws Exception {
IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
IPackageFragment pack1= sourceFolder.createPackageFragment("org.test", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package org.test;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class Outer {\n");
buf.append(" public void foo(Vector vec) {\n");
buf.append(" new Object() {\n");
buf.append(" public void xoo() {\n");
buf.append(" new Serializable() {\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
String content= buf.toString();
ICompilationUnit cu= pack1.createCompilationUnit("Outer.java", content, false, null);
IJavaElement elem= cu.getElementAt(content.indexOf("Serializable"));
String lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_FULLY_QUALIFIED);
assertEqualString(lab, "org.test.Outer.foo(..).new Object() {..}.xoo().new Serializable() {..}");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_CONTAINER_QUALIFIED);
assertEqualString(lab, "Outer.foo(..).new Object() {..}.xoo().new Serializable() {..}");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_POST_QUALIFIED);
assertEqualString(lab, "new Serializable() {..} - org.test.Outer.foo(..).new Object() {..}.xoo()");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.APPEND_ROOT_PATH);
assertEqualString(lab, "org.test.Outer.foo(..).new Object() {..}.xoo().new Serializable() {..} - TestSetupProject/src");
lab= JavaElementLabels.getTextLabel(elem, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.PREPEND_ROOT_PATH);
assertEqualString(lab, "TestSetupProject/src - org.test.Outer.foo(..).new Object() {..}.xoo().new Serializable() {..}");
}
}
|
48,999 |
Bug 48999 Anonym type can have field as parent
|
JavaElementLabels does only the 'is parent method' test
|
resolved fixed
|
39cf123
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-19T15:45:28Z | 2003-12-17T14:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementLabels.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.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IInitializer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.ILocalVariable;
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.core.Signature;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
public class JavaElementLabels {
/**
* Method names contain parameter types.
* e.g. <code>foo(int)</code>
*/
public final static int M_PARAMETER_TYPES= 1 << 0;
/**
* Method names contain parameter names.
* e.g. <code>foo(index)</code>
*/
public final static int M_PARAMETER_NAMES= 1 << 1;
/**
* Method names contain thrown exceptions.
* e.g. <code>foo throws IOException</code>
*/
public final static int M_EXCEPTIONS= 1 << 2;
/**
* Method names contain return type (appended)
* e.g. <code>foo : int</code>
*/
public final static int M_APP_RETURNTYPE= 1 << 3;
/**
* Method names contain return type (appended)
* e.g. <code>int foo</code>
*/
public final static int M_PRE_RETURNTYPE= 1 << 4;
/**
* Method names are fully qualified.
* e.g. <code>java.util.Vector.size</code>
*/
public final static int M_FULLY_QUALIFIED= 1 << 5;
/**
* Method names are post qualified.
* e.g. <code>size - java.util.Vector</code>
*/
public final static int M_POST_QUALIFIED= 1 << 6;
/**
* Initializer names are fully qualified.
* e.g. <code>java.util.Vector.{ ... }</code>
*/
public final static int I_FULLY_QUALIFIED= 1 << 7;
/**
* Type names are post qualified.
* e.g. <code>{ ... } - java.util.Map</code>
*/
public final static int I_POST_QUALIFIED= 1 << 8;
/**
* Field names contain the declared type (appended)
* e.g. <code>fHello : int</code>
*/
public final static int F_APP_TYPE_SIGNATURE= 1 << 9;
/**
* Field names contain the declared type (prepended)
* e.g. <code>int fHello</code>
*/
public final static int F_PRE_TYPE_SIGNATURE= 1 << 10;
/**
* Fields names are fully qualified.
* e.g. <code>java.lang.System.out</code>
*/
public final static int F_FULLY_QUALIFIED= 1 << 11;
/**
* Fields names are post qualified.
* e.g. <code>out - java.lang.System</code>
*/
public final static int F_POST_QUALIFIED= 1 << 12;
/**
* Type names are fully qualified.
* e.g. <code>java.util.Map.MapEntry</code>
*/
public final static int T_FULLY_QUALIFIED= 1 << 13;
/**
* Type names are type container qualified.
* e.g. <code>Map.MapEntry</code>
*/
public final static int T_CONTAINER_QUALIFIED= 1 << 14;
/**
* Type names are post qualified.
* e.g. <code>MapEntry - java.util.Map</code>
*/
public final static int T_POST_QUALIFIED= 1 << 15;
/**
* Declarations (import container / declarartion, package declarartion) are qualified.
* e.g. <code>java.util.Vector.class/import container</code>
*/
public final static int D_QUALIFIED= 1 << 16;
/**
* Declarations (import container / declarartion, package declarartion) are post qualified.
* e.g. <code>import container - java.util.Vector.class</code>
*/
public final static int D_POST_QUALIFIED= 1 << 17;
/**
* Class file names are fully qualified.
* e.g. <code>java.util.Vector.class</code>
*/
public final static int CF_QUALIFIED= 1 << 18;
/**
* Class file names are post qualified.
* e.g. <code>Vector.class - java.util</code>
*/
public final static int CF_POST_QUALIFIED= 1 << 19;
/**
* Compilation unit names are fully qualified.
* e.g. <code>java.util.Vector.java</code>
*/
public final static int CU_QUALIFIED= 1 << 20;
/**
* Compilation unit names are post qualified.
* e.g. <code>Vector.java - java.util</code>
*/
public final static int CU_POST_QUALIFIED= 1 << 21;
/**
* Package names are qualified.
* e.g. <code>MyProject/src/java.util</code>
*/
public final static int P_QUALIFIED= 1 << 22;
/**
* Package names are post qualified.
* e.g. <code>java.util - MyProject/src</code>
*/
public final static int P_POST_QUALIFIED= 1 << 23;
/**
* Package Fragment Roots contain variable name if from a variable.
* e.g. <code>JRE_LIB - c:\java\lib\rt.jar</code>
*/
public final static int ROOT_VARIABLE= 1 << 24;
/**
* Package Fragment Roots contain the project name if not an archive (prepended).
* e.g. <code>MyProject/src</code>
*/
public final static int ROOT_QUALIFIED= 1 << 25;
/**
* Package Fragment Roots contain the project name if not an archive (appended).
* e.g. <code>src - MyProject</code>
*/
public final static int ROOT_POST_QUALIFIED= 1 << 26;
/**
* Add root path to all elements except Package Fragment Roots and Java projects.
* e.g. <code>java.lang.Vector - c:\java\lib\rt.jar</code>
* Option only applies to getElementLabel
*/
public final static int APPEND_ROOT_PATH= 1 << 27;
/**
* Add root path to all elements except Package Fragment Roots and Java projects.
* e.g. <code>java.lang.Vector - c:\java\lib\rt.jar</code>
* Option only applies to getElementLabel
*/
public final static int PREPEND_ROOT_PATH= 1 << 28;
/**
* Package names are compressed.
* e.g. <code>o*.e*.search</code>
*/
public final static int P_COMPRESSED= 1 << 29;
/**
* Post qualify referenced package fragement roots. For example
* <code>jdt.jar - org.eclipse.jdt.ui</code> if the jar is referenced
* from another project.
*/
public final static int REFERENCED_ROOT_POST_QUALIFIED= 1 << 30;
/**
* Qualify all elements
*/
public final static int ALL_FULLY_QUALIFIED= F_FULLY_QUALIFIED | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FULLY_QUALIFIED | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED | P_QUALIFIED | ROOT_QUALIFIED;
/**
* Post qualify all elements
*/
public final static int ALL_POST_QUALIFIED= F_POST_QUALIFIED | M_POST_QUALIFIED | I_POST_QUALIFIED | T_POST_QUALIFIED | D_POST_QUALIFIED | CF_POST_QUALIFIED | CU_POST_QUALIFIED | P_POST_QUALIFIED | ROOT_POST_QUALIFIED;
/**
* Default options (M_PARAMETER_TYPES enabled)
*/
public final static int ALL_DEFAULT= M_PARAMETER_TYPES;
/**
* Default qualify options (All except Root and Package)
*/
public final static int DEFAULT_QUALIFIED= F_FULLY_QUALIFIED | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FULLY_QUALIFIED | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED;
/**
* Default post qualify options (All except Root and Package)
*/
public final static int DEFAULT_POST_QUALIFIED= F_POST_QUALIFIED | M_POST_QUALIFIED | I_POST_QUALIFIED | T_POST_QUALIFIED | D_POST_QUALIFIED | CF_POST_QUALIFIED | CU_POST_QUALIFIED;
public final static String CONCAT_STRING= JavaUIMessages.getString("JavaElementLabels.concat_string"); // " - "; //$NON-NLS-1$
public final static String COMMA_STRING= JavaUIMessages.getString("JavaElementLabels.comma_string"); // ", "; //$NON-NLS-1$
public final static String DECL_STRING= JavaUIMessages.getString("JavaElementLabels.declseparator_string"); // " "; // use for return type //$NON-NLS-1$
public final static String DEFAULT_PACKAGE= JavaUIMessages.getString("JavaElementLabels.default_package"); // "(default package)" //$NON-NLS-1$
/*
* Package name compression
*/
private static String fgPkgNamePattern= ""; //$NON-NLS-1$
private static String fgPkgNamePrefix;
private static String fgPkgNamePostfix;
private static int fgPkgNameChars;
private static int fgPkgNameLength= -1;
private JavaElementLabels() {
}
private static boolean getFlag(int flags, int flag) {
return (flags & flag) != 0;
}
public static String getTextLabel(Object obj, int flags) {
if (obj instanceof IJavaElement) {
return getElementLabel((IJavaElement) obj, flags);
} else if (obj instanceof IAdaptable) {
IWorkbenchAdapter wbadapter= (IWorkbenchAdapter) ((IAdaptable)obj).getAdapter(IWorkbenchAdapter.class);
if (wbadapter != null) {
return wbadapter.getLabel(obj);
}
}
return ""; //$NON-NLS-1$
}
/**
* Returns the label for a Java element. Flags as defined above.
*/
public static String getElementLabel(IJavaElement element, int flags) {
StringBuffer buf= new StringBuffer(60);
getElementLabel(element, flags, buf);
return buf.toString();
}
/**
* Returns the label for a Java element. Flags as defined above.
*/
public static void getElementLabel(IJavaElement element, int flags, StringBuffer buf) {
int type= element.getElementType();
IPackageFragmentRoot root= null;
if (type != IJavaElement.JAVA_MODEL && type != IJavaElement.JAVA_PROJECT && type != IJavaElement.PACKAGE_FRAGMENT_ROOT)
root= JavaModelUtil.getPackageFragmentRoot(element);
if (root != null && getFlag(flags, PREPEND_ROOT_PATH)) {
getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf);
buf.append(CONCAT_STRING);
}
switch (type) {
case IJavaElement.METHOD:
getMethodLabel((IMethod) element, flags, buf);
break;
case IJavaElement.FIELD:
getFieldLabel((IField) element, flags, buf);
break;
case IJavaElement.LOCAL_VARIABLE:
getLocalVariableLabel((ILocalVariable) element, flags, buf);
break;
case IJavaElement.INITIALIZER:
getInitializerLabel((IInitializer) element, flags, buf);
break;
case IJavaElement.TYPE:
getTypeLabel((IType) element, flags, buf);
break;
case IJavaElement.CLASS_FILE:
getClassFileLabel((IClassFile) element, flags, buf);
break;
case IJavaElement.COMPILATION_UNIT:
getCompilationUnitLabel((ICompilationUnit) element, flags, buf);
break;
case IJavaElement.PACKAGE_FRAGMENT:
getPackageFragmentLabel((IPackageFragment) element, flags, buf);
break;
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
getPackageFragmentRootLabel((IPackageFragmentRoot) element, flags, buf);
break;
case IJavaElement.IMPORT_CONTAINER:
case IJavaElement.IMPORT_DECLARATION:
case IJavaElement.PACKAGE_DECLARATION:
getDeclararionLabel(element, flags, buf);
break;
case IJavaElement.JAVA_PROJECT:
case IJavaElement.JAVA_MODEL:
buf.append(element.getElementName());
break;
default:
buf.append(element.getElementName());
}
if (root != null && getFlag(flags, APPEND_ROOT_PATH)) {
buf.append(CONCAT_STRING);
getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf);
}
}
/**
* Appends the label for a method to a StringBuffer. Considers the M_* flags.
*/
public static void getMethodLabel(IMethod method, int flags, StringBuffer buf) {
try {
// return type
if (getFlag(flags, M_PRE_RETURNTYPE) && method.exists() && !method.isConstructor()) {
buf.append(Signature.getSimpleName(Signature.toString(method.getReturnType())));
buf.append(' ');
}
// qualification
if (getFlag(flags, M_FULLY_QUALIFIED)) {
getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
buf.append('.');
}
buf.append(method.getElementName());
// parameters
buf.append('(');
if (getFlag(flags, M_PARAMETER_TYPES | M_PARAMETER_NAMES)) {
String[] types= getFlag(flags, M_PARAMETER_TYPES) ? method.getParameterTypes() : null;
String[] names= (getFlag(flags, M_PARAMETER_NAMES) && method.exists()) ? method.getParameterNames() : null;
int nParams= types != null ? types.length : names.length;
for (int i= 0; i < nParams; i++) {
if (i > 0) {
buf.append(COMMA_STRING); //$NON-NLS-1$
}
if (types != null) {
buf.append(Signature.getSimpleName(Signature.toString(types[i])));
}
if (names != null) {
if (types != null) {
buf.append(' ');
}
buf.append(names[i]);
}
}
} else {
if (method.getParameterTypes().length > 0) {
buf.append(".."); //$NON-NLS-1$
}
}
buf.append(')');
if (getFlag(flags, M_EXCEPTIONS) && method.exists()) {
String[] types= method.getExceptionTypes();
if (types.length > 0) {
buf.append(" throws "); //$NON-NLS-1$
for (int i= 0; i < types.length; i++) {
if (i > 0) {
buf.append(COMMA_STRING);
}
buf.append(Signature.getSimpleName(Signature.toString(types[i])));
}
}
}
if (getFlag(flags, M_APP_RETURNTYPE) && method.exists() && !method.isConstructor()) {
buf.append(DECL_STRING);
buf.append(Signature.getSimpleName(Signature.toString(method.getReturnType())));
}
// post qualification
if (getFlag(flags, M_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
}
} catch (JavaModelException e) {
JavaPlugin.log(e); // NotExistsException will not reach this point
}
}
/**
* Appends the label for a field to a StringBuffer. Considers the F_* flags.
*/
public static void getFieldLabel(IField field, int flags, StringBuffer buf) {
try {
if (getFlag(flags, F_PRE_TYPE_SIGNATURE) && field.exists()) {
buf.append(Signature.toString(field.getTypeSignature()));
buf.append(' ');
}
// qualification
if (getFlag(flags, F_FULLY_QUALIFIED)) {
getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
buf.append('.');
}
buf.append(field.getElementName());
if (getFlag(flags, F_APP_TYPE_SIGNATURE) && field.exists()) {
buf.append(DECL_STRING);
buf.append(Signature.toString(field.getTypeSignature()));
}
// post qualification
if (getFlag(flags, F_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
}
} catch (JavaModelException e) {
JavaPlugin.log(e); // NotExistsException will not reach this point
}
}
/**
* Appends the label for a local variable to a StringBuffer.
*
* @since 3.0
*/
public static void getLocalVariableLabel(ILocalVariable localVariable, int flags, StringBuffer buf) {
buf.append(Signature.toString(localVariable.getTypeSignature()));
buf.append(' ');
buf.append(localVariable.getElementName());
buf.append(CONCAT_STRING);
getElementLabel(localVariable.getParent(), M_PARAMETER_TYPES | M_FULLY_QUALIFIED | T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
}
/**
* Appends the label for a initializer to a StringBuffer. Considers the I_* flags.
*/
public static void getInitializerLabel(IInitializer initializer, int flags, StringBuffer buf) {
// qualification
if (getFlag(flags, I_FULLY_QUALIFIED)) {
getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
buf.append('.');
}
buf.append(JavaUIMessages.getString("JavaElementLabels.initializer")); //$NON-NLS-1$
// post qualification
if (getFlag(flags, I_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
}
}
/**
* Appends the label for a type to a StringBuffer. Considers the T_* flags.
*/
public static void getTypeLabel(IType type, int flags, StringBuffer buf) {
if (getFlag(flags, T_FULLY_QUALIFIED)) {
IPackageFragment pack= type.getPackageFragment();
if (!pack.isDefaultPackage()) {
getPackageFragmentLabel(pack, (flags & P_COMPRESSED), buf);
buf.append('.');
}
}
if (getFlag(flags, T_FULLY_QUALIFIED | T_CONTAINER_QUALIFIED)) {
IType declaringType= type.getDeclaringType();
if (declaringType != null) {
getTypeLabel(declaringType, T_CONTAINER_QUALIFIED, buf);
buf.append('.');
}
IJavaElement parent= type.getParent();
if (parent instanceof IMethod) {
getMethodLabel((IMethod) parent, 0, buf);
buf.append('.');
}
}
String typeName= type.getElementName();
if (typeName.length() == 0) { // anonymous
try {
String superclassName= Signature.getSimpleName(type.getSuperclassName());
typeName= JavaUIMessages.getFormattedString("JavaElementLabels.anonym_type" , superclassName); //$NON-NLS-1$
} catch (JavaModelException e) {
//ignore
typeName= JavaUIMessages.getString("JavaElementLabels.anonym"); //$NON-NLS-1$
}
}
buf.append(typeName);
// post qualification
if (getFlag(flags, T_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
IType declaringType= type.getDeclaringType();
if (declaringType != null) {
getTypeLabel(declaringType, T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
IJavaElement parent= type.getParent();
if (parent instanceof IMethod) {
buf.append('.');
getMethodLabel((IMethod) parent, 0, buf);
}
} else {
getPackageFragmentLabel(type.getPackageFragment(), (flags & P_COMPRESSED), buf);
}
}
}
/**
* Appends the label for a declaration to a StringBuffer. Considers the D_* flags.
*/
public static void getDeclararionLabel(IJavaElement declaration, int flags, StringBuffer buf) {
if (getFlag(flags, D_QUALIFIED)) {
IJavaElement openable= (IJavaElement) declaration.getOpenable();
if (openable != null) {
buf.append(getElementLabel(openable, CF_QUALIFIED | CU_QUALIFIED));
buf.append('/');
}
}
if (declaration.getElementType() == IJavaElement.IMPORT_CONTAINER) {
buf.append(JavaUIMessages.getString("JavaElementLabels.import_container")); //$NON-NLS-1$
} else {
buf.append(declaration.getElementName());
}
// post qualification
if (getFlag(flags, D_POST_QUALIFIED)) {
IJavaElement openable= (IJavaElement) declaration.getOpenable();
if (openable != null) {
buf.append(CONCAT_STRING);
buf.append(getElementLabel(openable, CF_QUALIFIED | CU_QUALIFIED));
}
}
}
/**
* Appends the label for a class file to a StringBuffer. Considers the CF_* flags.
*/
public static void getClassFileLabel(IClassFile classFile, int flags, StringBuffer buf) {
if (getFlag(flags, CF_QUALIFIED)) {
IPackageFragment pack= (IPackageFragment) classFile.getParent();
if (!pack.isDefaultPackage()) {
buf.append(pack.getElementName());
buf.append('.');
}
}
buf.append(classFile.getElementName());
if (getFlag(flags, CF_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getPackageFragmentLabel((IPackageFragment) classFile.getParent(), 0, buf);
}
}
/**
* Appends the label for a compilation unit to a StringBuffer. Considers the CU_* flags.
*/
public static void getCompilationUnitLabel(ICompilationUnit cu, int flags, StringBuffer buf) {
if (getFlag(flags, CU_QUALIFIED)) {
IPackageFragment pack= (IPackageFragment) cu.getParent();
if (!pack.isDefaultPackage()) {
buf.append(pack.getElementName());
buf.append('.');
}
}
buf.append(cu.getElementName());
if (getFlag(flags, CU_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getPackageFragmentLabel((IPackageFragment) cu.getParent(), 0, buf);
}
}
/**
* Appends the label for a package fragment to a StringBuffer. Considers the P_* flags.
*/
public static void getPackageFragmentLabel(IPackageFragment pack, int flags, StringBuffer buf) {
if (getFlag(flags, P_QUALIFIED)) {
getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, buf);
buf.append('/');
}
refreshPackageNamePattern();
if (pack.isDefaultPackage()) {
buf.append(DEFAULT_PACKAGE);
} else if (getFlag(flags, P_COMPRESSED) && fgPkgNameLength >= 0) {
String name= pack.getElementName();
int start= 0;
int dot= name.indexOf('.', start);
while (dot > 0) {
if (dot - start > fgPkgNameLength-1) {
buf.append(fgPkgNamePrefix);
if (fgPkgNameChars > 0)
buf.append(name.substring(start, Math.min(start+ fgPkgNameChars, dot)));
buf.append(fgPkgNamePostfix);
} else
buf.append(name.substring(start, dot + 1));
start= dot + 1;
dot= name.indexOf('.', start);
}
buf.append(name.substring(start));
} else {
buf.append(pack.getElementName());
}
if (getFlag(flags, P_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, buf);
}
}
/**
* Appends the label for a package fragment root to a StringBuffer. Considers the ROOT_* flags.
*/
public static void getPackageFragmentRootLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
if (root.isArchive())
getArchiveLabel(root, flags, buf);
else
getFolderLabel(root, flags, buf);
}
private static void getArchiveLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
// Handle variables different
if (getFlag(flags, ROOT_VARIABLE) && getVariableLabel(root, flags, buf))
return;
boolean external= root.isExternal();
if (external)
getExternalArchiveLabel(root, flags, buf);
else
getInternalArchiveLabel(root, flags, buf);
}
private static boolean getVariableLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
try {
IClasspathEntry rawEntry= root.getRawClasspathEntry();
if (rawEntry != null) {
if (rawEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
buf.append(rawEntry.getPath().makeRelative());
buf.append(CONCAT_STRING);
if (root.isExternal())
buf.append(root.getPath().toOSString());
else
buf.append(root.getPath().makeRelative().toString());
return true;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e); // problems with class path
}
return false;
}
private static void getExternalArchiveLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
IPath path= root.getPath();
if (getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED)) {
int segements= path.segmentCount();
if (segements > 0) {
buf.append(path.segment(segements - 1));
if (segements > 1 || path.getDevice() != null) {
buf.append(CONCAT_STRING);
buf.append(path.removeLastSegments(1).toOSString());
}
} else {
buf.append(path.toOSString());
}
} else {
buf.append(path.toOSString());
}
}
private static void getInternalArchiveLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
IResource resource= root.getResource();
boolean rootQualified= getFlag(flags, ROOT_QUALIFIED);
boolean referencedQualified= getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED) && JavaModelUtil.isReferenced(root) && resource != null;
if (rootQualified) {
buf.append(root.getPath().makeRelative().toString());
} else {
buf.append(root.getElementName());
if (referencedQualified) {
buf.append(CONCAT_STRING);
buf.append(resource.getParent().getFullPath().makeRelative().toString());
} else if (getFlag(flags, ROOT_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
buf.append(root.getParent().getPath().makeRelative().toString());
}
}
}
private static void getFolderLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
IResource resource= root.getResource();
boolean rootQualified= getFlag(flags, ROOT_QUALIFIED);
boolean referencedQualified= getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED) && JavaModelUtil.isReferenced(root) && resource != null;
if (rootQualified) {
buf.append(root.getPath().makeRelative().toString());
} else {
if (resource != null)
buf.append(resource.getProjectRelativePath().toString());
else
buf.append(root.getElementName());
if (referencedQualified) {
buf.append(CONCAT_STRING);
buf.append(resource.getProject().getName());
} else if (getFlag(flags, ROOT_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
buf.append(root.getParent().getElementName());
}
}
}
private static void refreshPackageNamePattern() {
String pattern= getPkgNamePatternForPackagesView();
if (pattern.equals(fgPkgNamePattern))
return;
else if (pattern.equals("")) { //$NON-NLS-1$
fgPkgNamePattern= ""; //$NON-NLS-1$
fgPkgNameLength= -1;
return;
}
fgPkgNamePattern= pattern;
int i= 0;
fgPkgNameChars= 0;
fgPkgNamePrefix= ""; //$NON-NLS-1$
fgPkgNamePostfix= ""; //$NON-NLS-1$
while (i < pattern.length()) {
char ch= pattern.charAt(i);
if (Character.isDigit(ch)) {
fgPkgNameChars= ch-48;
if (i > 0)
fgPkgNamePrefix= pattern.substring(0, i);
if (i >= 0)
fgPkgNamePostfix= pattern.substring(i+1);
fgPkgNameLength= fgPkgNamePrefix.length() + fgPkgNameChars + fgPkgNamePostfix.length();
return;
}
i++;
}
fgPkgNamePrefix= pattern;
fgPkgNameLength= pattern.length();
}
private static String getPkgNamePatternForPackagesView() {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
if (!store.getBoolean(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES))
return ""; //$NON-NLS-1$
return store.getString(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW);
}
}
|
48,995 |
Bug 48995 Types aren't filtered for 'explicit import' QuickFix [quick fix]
|
I20031216 With this snippet use QF on List: import java.util.*; import org.eclipse.swt.widgets.*; public class Import { public static void main(String[] args) { List l; } }
|
resolved fixed
|
63c4c35
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-19T16:04:17Z | 2003-12-17T11:20:00Z |
org.eclipse.jdt.ui/core
| |
48,995 |
Bug 48995 Types aren't filtered for 'explicit import' QuickFix [quick fix]
|
I20031216 With this snippet use QF on List: import java.util.*; import org.eclipse.swt.widgets.*; public class Import { public static void main(String[] args) { List l; } }
|
resolved fixed
|
63c4c35
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-19T16:04:17Z | 2003-12-17T11:20:00Z |
extension/org/eclipse/jdt/internal/corext/util/TypeFilter.java
| |
48,995 |
Bug 48995 Types aren't filtered for 'explicit import' QuickFix [quick fix]
|
I20031216 With this snippet use QF on List: import java.util.*; import org.eclipse.swt.widgets.*; public class Import { public static void main(String[] args) { List l; } }
|
resolved fixed
|
63c4c35
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-19T16:04:17Z | 2003-12-17T11:20:00Z |
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 <[email protected]> - 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.text.edits.ReplaceEdit;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.core.resources.IFile;
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.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.ASTNodeConstants;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
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.textmanipulation.TextBuffer;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.corext.util.WorkingCopyUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
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) throws CoreException {
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= new ASTRewrite(statement.getParent());
rewrite.markAsRemoved(statement);
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);
proposal.ensureNoModifications();
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, senderBinding.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);
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
}
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 ReplaceCorrectionProposal(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 variablefragment
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;
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 simlar 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 {
TextBuffer buffer= null;
try {
buffer= TextBuffer.acquire((IFile)WorkingCopyUtil.getOriginal(cu).getResource());
CUCorrectionProposal proposal= new CUCorrectionProposal("", cu, 0); //$NON-NLS-1$
ImportRewrite importRewrite= new ImportRewrite(cu, JavaPreferencesSettings.getCodeGenerationSettings());
String simpleName= importRewrite.addImport(fullName);
TextEdit root= proposal.getRootTextEdit();
if (!importRewrite.isEmpty()) {
root.addChild(importRewrite.createEdit(buffer)); //$NON-NLS-1$
}
String packName= Signature.getQualifier(fullName);
String[] arg= { simpleName, packName };
if (node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) { // import only
proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL));
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importtype.description", arg)); //$NON-NLS-1$
proposal.setRelevance(relevance + 20);
} else {
root.addChild(new ReplaceEdit(node.getStartPosition(), node.getLength(), simpleName)); //$NON-NLS-1$
if (packName.length() == 0) {
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.nopack.description", simpleName)); //$NON-NLS-1$
} else {
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.description", arg)); //$NON-NLS-1$
}
proposal.setRelevance(relevance);
}
return proposal;
} finally {
if (buffer != null)
TextBuffer.release(buffer);
}
}
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 sugest 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 ReplaceCorrectionProposal(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) throws CoreException {
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= new ASTRewrite(expression.getParent());
CastExpression newCast= ast.newCastExpression();
newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType()));
newCast.setExpression((Expression) rewrite.createCopy(accessExpression));
ParenthesizedExpression parents= ast.newParenthesizedExpression();
parents.setExpression(newCast);
ASTNode node= rewrite.createCopy(expression.getExpression());
rewrite.markAsReplaced(expression, node);
rewrite.markAsReplaced(accessExpression, parents);
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);
proposal.ensureNoModifications();
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));
proposal.ensureNoModifications();
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, 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
{
ASTNode selectedNode= problem.getCoveringNode(astRoot);
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
for (int i= diff - 1; i >= 0; i--) {
rewrite.markAsRemoved((Expression) arguments.get(indexSkipped[i]));
}
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);
proposal.ensureNoModifications();
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 (isDifferentCU && 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, 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;
}
}
CompilationUnit unit= AST.parsePartialCompilationUnit(targetCU, 0, true);
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 missmatching: 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= LocalCorrectionsSubProcessor.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$
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
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= new ASTRewrite(arg1.getParent());
rewrite.markAsReplaced(arg1, rewrite.createCopy(arg2));
rewrite.markAsReplaced(arg2, rewrite.createCopy(arg1));
{
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);
proposal.ensureNoModifications();
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, 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, 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= new ASTRewrite(invocationNode.getParent());
AST ast= invocationNode.getAST();
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.ensureNoModifications();
proposals.add(proposal);
String qualifier= proposal.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.markAsInsert(invocationNode, ASTNodeConstants.EXPRESSION, newExpression, null);
}
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) {
String qualifiedTypeName= JavaModelUtil.getFullyQualifiedName((IType) curr);
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);
TextBuffer buffer= null;
try {
buffer= TextBuffer.acquire((IFile)WorkingCopyUtil.getOriginal(cu).getResource());
ImportRewrite importRewrite= new ImportRewrite(cu, JavaPreferencesSettings.getCodeGenerationSettings());
importRewrite.addImport(qualifiedTypeName);
importRewrite.setFindAmbiguosImports(true);
proposal.getRootTextEdit().addChild(importRewrite.createEdit(buffer));
proposals.add(proposal);
} finally {
if (buffer != null)
TextBuffer.release(buffer);
}
}
}
}
}
|
48,615 |
Bug 48615 Javadoc formatting messes up non-javadoc comments.
| null |
resolved fixed
|
8092859
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-19T16:10:21Z | 2003-12-11T22:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/CommentFormattingStrategy.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.comment;
import java.util.LinkedList;
import java.util.Map;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.TypedPosition;
import org.eclipse.jface.text.formatter.ContentFormatter2;
import org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy;
import org.eclipse.jface.text.formatter.FormattingContext;
import org.eclipse.jface.text.formatter.FormattingContextProperties;
import org.eclipse.jface.text.formatter.IFormattingContext;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
/**
* Formatting strategy for general source code comments.
* <p>
* This strategy implements <code>IFormattingStrategyExtension</code>. It
* must be registered with a content formatter implementing <code>IContentFormatterExtension2<code>
* to take effect.
*
* @since 3.0
*/
public class CommentFormattingStrategy extends ContextBasedFormattingStrategy {
/**
* Returns the indentation of the line at the specified offset.
*
* @param document
* Document which owns the line
* @param region
* Comment region which owns the line
* @param offset
* Offset where to determine the indentation
* @return The indentation of the line
*/
public static String getLineIndentation(final IDocument document, final CommentRegion region, final int offset) {
String result= ""; //$NON-NLS-1$
try {
final IRegion line= document.getLineInformationOfOffset(offset);
final int begin= line.getOffset();
final int end= Math.min(offset, line.getOffset() + line.getLength());
boolean useTab= JavaCore.TAB.equals(JavaCore.getOption(JavaCore.FORMATTER_TAB_CHAR));
result= region.stringToIndent(document.get(begin, end - begin), useTab);
} catch (BadLocationException exception) {
// Ignore and return empty
}
return result;
}
/**
* Content formatter with which this formatting strategy has been
* registered
*/
private final ContentFormatter2 fFormatter;
/** Partitions to be formatted by this strategy */
private final LinkedList fPartitions= new LinkedList();
/**
* Creates a new comment formatting strategy.
*
* @param formatter
* The content formatter with which this formatting strategy has
* been registered
* @param viewer
* The source viewer where to apply the formatting strategy
*/
public CommentFormattingStrategy(final ContentFormatter2 formatter, final ISourceViewer viewer) {
super(viewer);
fFormatter= formatter;
}
/*
* @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#format()
*/
public void format() {
super.format();
Assert.isLegal(fPartitions.size() > 0);
final IDocument document= getViewer().getDocument();
final TypedPosition position= (TypedPosition)fPartitions.removeFirst();
try {
final ITypedRegion partition= TextUtilities.getPartition(document, fFormatter.getDocumentPartitioning(), position.getOffset());
final String type= partition.getType();
position.offset= partition.getOffset();
position.length= partition.getLength();
final Map preferences= getPreferences();
final boolean format= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_FORMAT));
final boolean header= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_FORMATHEADER));
if (format && (header || position.getOffset() != 0 || !type.equals(IJavaPartitions.JAVA_DOC))) {
final CommentRegion region= CommentObjectFactory.createRegion(this, position, TextUtilities.getDefaultLineDelimiter(document));
final String indentation= getLineIndentation(document, region, position.getOffset());
region.format(indentation);
}
} catch (BadLocationException exception) {
// Should not happen
}
}
/*
* @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#formatterStarts(org.eclipse.jface.text.formatter.IFormattingContext)
*/
public void formatterStarts(IFormattingContext context) {
super.formatterStarts(context);
final FormattingContext current= (FormattingContext)context;
fPartitions.addLast(current.getProperty(FormattingContextProperties.CONTEXT_PARTITION));
}
/*
* @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#formatterStops()
*/
public void formatterStops() {
super.formatterStops();
fPartitions.clear();
}
/**
* Returns the content formatter with which this formatting strategy has
* been registered.
*
* @return The content formatter
*/
public final ContentFormatter2 getFormatter() {
return fFormatter;
}
}
|
47,665 |
Bug 47665 Hierarchy perspective outline is missing 'Link with editor' [type hierarchy]
|
M5 build. I launch type hierarchies in their own perspective in their own window, like the old Smalltalk days. ;) But when I select F4 to open a hierarchy on a method, the method is not selected in the outliner of the new hierarchy perspective, nor is there a 'link with editor' option.
|
resolved fixed
|
3d77c7a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-20T19:58:26Z | 2003-11-27T19:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/OpenTypeHierarchyUtil.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.util;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.WorkbenchException;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
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.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.actions.OpenActionUtil;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart;
public class OpenTypeHierarchyUtil {
private OpenTypeHierarchyUtil() {
}
public static TypeHierarchyViewPart open(IJavaElement element, IWorkbenchWindow window) {
IJavaElement[] candidates= getCandidates(element);
if (candidates != null) {
return open(candidates, window);
}
return null;
}
public static TypeHierarchyViewPart open(IJavaElement[] candidates, IWorkbenchWindow window) {
Assert.isTrue(candidates != null && candidates.length != 0);
IJavaElement input= null;
if (candidates.length > 1) {
String title= JavaUIMessages.getString("OpenTypeHierarchyUtil.selectionDialog.title"); //$NON-NLS-1$
String message= JavaUIMessages.getString("OpenTypeHierarchyUtil.selectionDialog.message"); //$NON-NLS-1$
input= OpenActionUtil.selectJavaElement(candidates, window.getShell(), title, message);
} else {
input= candidates[0];
}
if (input == null)
return null;
try {
if (PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.OPEN_TYPE_HIERARCHY))) {
return openInPerspective(window, input);
} else {
return openInViewPart(window, input);
}
} catch (WorkbenchException e) {
ExceptionHandler.handle(e, window.getShell(),
JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_perspective"), //$NON-NLS-1$
e.getMessage());
} catch (JavaModelException e) {
ExceptionHandler.handle(e, window.getShell(),
JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_editor"), //$NON-NLS-1$
e.getMessage());
}
return null;
}
private static TypeHierarchyViewPart openInViewPart(IWorkbenchWindow window, IJavaElement input) {
IWorkbenchPage page= window.getActivePage();
try {
TypeHierarchyViewPart result= (TypeHierarchyViewPart) page.findView(JavaUI.ID_TYPE_HIERARCHY);
if (result != null) {
result.clearNeededRefresh(); // avoid refresh of old hierarchy on 'becomes visible'
}
result= (TypeHierarchyViewPart) page.showView(JavaUI.ID_TYPE_HIERARCHY);
result.setInputElement(input);
if (input instanceof IMember) {
result.selectMember((IMember) input);
openEditor(input, false);
}
return result;
} catch (CoreException e) {
ExceptionHandler.handle(e, window.getShell(),
JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_view"), e.getMessage()); //$NON-NLS-1$
}
return null;
}
private static TypeHierarchyViewPart openInPerspective(IWorkbenchWindow window, IJavaElement input) throws WorkbenchException, JavaModelException {
IWorkbench workbench= JavaPlugin.getDefault().getWorkbench();
// The problem is that the input element can be a working copy. So we first convert it to the original element if
// it exists.
IJavaElement perspectiveInput= input;
if (input instanceof IMember) {
input= JavaModelUtil.toOriginal((IMember)input);
if (input.getElementType() != IJavaElement.TYPE) {
perspectiveInput= ((IMember)input).getDeclaringType();
} else {
perspectiveInput= input;
}
}
IWorkbenchPage page= workbench.showPerspective(JavaUI.ID_HIERARCHYPERSPECTIVE, window, perspectiveInput);
TypeHierarchyViewPart part= (TypeHierarchyViewPart) page.findView(JavaUI.ID_TYPE_HIERARCHY);
if (part != null) {
part.clearNeededRefresh(); // avoid refresh of old hierarchy on 'becomes visible'
}
part= (TypeHierarchyViewPart) page.showView(JavaUI.ID_TYPE_HIERARCHY);
part.setInputElement(perspectiveInput);
if (input instanceof IMember) {
openEditor(input, false);
}
return part;
}
private static void openEditor(Object input, boolean activate) throws PartInitException, JavaModelException {
IEditorPart part= EditorUtility.openInEditor(input, activate);
if (input instanceof IJavaElement)
EditorUtility.revealInEditor(part, (IJavaElement) input);
}
/**
* Converts the input to a possible input candidates
*/
public static IJavaElement[] getCandidates(Object input) {
if (!(input instanceof IJavaElement)) {
return null;
}
try {
IJavaElement elem= (IJavaElement) input;
switch (elem.getElementType()) {
case IJavaElement.INITIALIZER:
case IJavaElement.METHOD:
case IJavaElement.FIELD:
case IJavaElement.TYPE:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
case IJavaElement.JAVA_PROJECT:
return new IJavaElement[] { elem };
case IJavaElement.PACKAGE_FRAGMENT:
if (((IPackageFragment)elem).containsJavaResources())
return new IJavaElement[] {elem};
break;
case IJavaElement.PACKAGE_DECLARATION:
return new IJavaElement[] { elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT) };
case IJavaElement.IMPORT_DECLARATION:
IImportDeclaration decl= (IImportDeclaration) elem;
if (decl.isOnDemand()) {
elem= JavaModelUtil.findTypeContainer(elem.getJavaProject(), Signature.getQualifier(elem.getElementName()));
} else {
elem= elem.getJavaProject().findType(elem.getElementName());
}
if (elem == null)
return null;
return new IJavaElement[] {elem};
case IJavaElement.CLASS_FILE:
return new IJavaElement[] { ((IClassFile)input).getType() };
case IJavaElement.COMPILATION_UNIT: {
ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
IType[] types= cu.getTypes();
if (types.length > 0) {
return types;
}
}
break;
}
default:
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return null;
}
}
|
49,177 |
Bug 49177 Quick Hierarchy gives NullPointerException [type hierarchy]
|
I200312182000 Reproduce: 1) Open JavaPreview.java 2) Goto line 83 3) Place cursor on 'preferenceStore' 4) Open quick hierarchy (ctrl-t) 5) check log: !ENTRY org.eclipse.ui 4 4 Dec 19, 2003 16:08:26.575 !MESSAGE Action for command 'org.eclipse.jdt.ui.edit.text.java.open.hierarchy' failed to execute properly. !ENTRY org.eclipse.ui 4 0 Dec 19, 2003 16:08:26.575 !MESSAGE Action for command 'org.eclipse.jdt.ui.edit.text.java.open.hierarchy' failed to execute properly. !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels.getElementLabel(JavaElementLabels.java:305) at org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels.getElementLabel(JavaElementLabels.java:297) at org.eclipse.jdt.internal.ui.typehierarchy.HierarchyInformationControl.getHeaderLabel(HierarchyInformationControl.java:392) at org.eclipse.jdt.internal.ui.typehierarchy.HierarchyInformationControl.setInput(HierarchyInformationControl.java:322) at org.eclipse.jface.text.AbstractInformationControlManager.internalShowInformationControl(AbstractInformationControlManager.java:698) at org.eclipse.jface.text.AbstractInformationControlManager.presentInformation(AbstractInformationControlManager.java:677) at org.eclipse.jface.text.AbstractInformationControlManager.setInformation(AbstractInformationControlManager.java:240) at org.eclipse.jface.text.information.InformationPresenter.computeInformation(InformationPresenter.java:341) at org.eclipse.jface.text.AbstractInformationControlManager.doShowInformation(AbstractInformationControlManager.java:661) at org.eclipse.jface.text.AbstractInformationControlManager.showInformation(AbstractInformationControlManager.java:651) at org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer.doOperation(JavaSourceViewer.java:120) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$AdaptedSourceViewer.doOperation(CompilationUnitEditor.java:187) at org.eclipse.ui.texteditor.TextOperationAction$1.run(TextOperationAction.java:122) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.ui.texteditor.TextOperationAction.run(TextOperationAction.java:120) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.internal.commands.ActionHandler.execute(ActionHandler.java:40) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.executeCommand(WorkbenchKeyboard.java:390) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.press(WorkbenchKeyboard.java:763) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.processKeyEvent(WorkbenchKeyboard.java:803) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.filterKeySequenceBindings(WorkbenchKeyboard.java:486) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.access$0(WorkbenchKeyboard.java:421) at org.eclipse.ui.internal.keys.WorkbenchKeyboard$1.handleEvent(WorkbenchKeyboard.java:215) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Display.filterEvent(Display.java:692) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:846) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1716) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1712) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3036) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2939) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1369) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1990) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:226) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:85) 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:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:279) at org.eclipse.core.launcher.Main.run(Main.java:742) at org.eclipse.core.launcher.Main.main(Main.java:581)
|
resolved fixed
|
da4f951
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-22T09:30:05Z | 2003-12-19T16:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/HierarchyInformationControl.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.typehierarchy;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommand;
import org.eclipse.ui.commands.ICommandManager;
import org.eclipse.ui.commands.IKeySequenceBinding;
import org.eclipse.ui.keys.CharacterKey;
import org.eclipse.ui.keys.KeySequence;
import org.eclipse.ui.keys.KeyStroke;
import org.eclipse.ui.keys.ModifierKey;
import org.eclipse.ui.keys.NaturalKey;
import org.eclipse.ui.keys.SpecialKey;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
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.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.AbstractInformationControl;
import org.eclipse.jdt.internal.ui.typehierarchy.SuperTypeHierarchyViewer.SuperTypeHierarchyContentProvider;
import org.eclipse.jdt.internal.ui.typehierarchy.TraditionalHierarchyViewer.TraditionalHierarchyContentProvider;
import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
*
*/
public class HierarchyInformationControl extends AbstractInformationControl {
private TypeHierarchyLifeCycle fLifeCycle;
private HierarchyLabelProvider fLabelProvider;
private Label fHeaderLabel;
private Label fStatusTextLabel;
private Font fStatusTextFont;
private KeyAdapter fKeyAdapter;
private Object[] fOtherExpandedElements;
private TypeHierarchyContentProvider fOtherContentProvider;
private IMethod fFocus; // method to filter for or null if type hierarchy
private boolean fDoFilter;
private KeySequence[] fKeySequences;
public HierarchyInformationControl(Shell parent, int shellStyle, int treeStyle) {
super(parent, shellStyle, treeStyle);
fOtherExpandedElements= null;
fKeySequences= null;
fDoFilter= true;
}
private KeySequence[] getKeySequences() {
if (fKeySequences == null) {
ICommandManager commandManager = PlatformUI.getWorkbench().getCommandManager();
ICommand command = commandManager.getCommand(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
if (command.isDefined()) {
List list= command.getKeySequenceBindings();
if (!list.isEmpty()) {
fKeySequences= new KeySequence[list.size()];
for (int i= 0; i < fKeySequences.length; i++) {
fKeySequences[i]= ((IKeySequenceBinding) list.get(i)).getKeySequence();
}
return fKeySequences;
}
}
// default key is F12
fKeySequences= new KeySequence[] {
KeySequence.getInstance(KeyStroke.getInstance(SpecialKey.F12))
};
}
return fKeySequences;
}
private KeyAdapter getKeyAdapter() {
if (fKeyAdapter == null) {
fKeyAdapter= new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int accelerator = convertEventToUnmodifiedAccelerator(e);
KeySequence keySequence = KeySequence.getInstance(convertAcceleratorToKeyStroke(accelerator));
KeySequence[] sequences= getKeySequences();
for (int i= 0; i < sequences.length; i++) {
if (sequences[i].equals(keySequence)) {
toggleHierarchy();
return;
}
}
}
};
}
return fKeyAdapter;
}
protected Text createFilterText(Composite parent) {
fHeaderLabel= new Label(parent, SWT.NONE);
// text set later
fHeaderLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
fHeaderLabel.setFont(JFaceResources.getBannerFont());
Text text= super.createFilterText(parent);
text.addKeyListener(getKeyAdapter());
return text;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.JavaOutlineInformationControl#createTreeViewer(org.eclipse.swt.widgets.Composite, int)
*/
protected TreeViewer createTreeViewer(Composite parent, int style) {
Tree tree= new Tree(parent, SWT.SINGLE | (style & ~SWT.MULTI));
tree.setLayoutData(new GridData(GridData.FILL_BOTH));
TreeViewer treeViewer= new TreeViewer(tree);
treeViewer.addFilter(new ViewerFilter() {
public boolean select(Viewer viewer, Object parentElement, Object element) {
return element instanceof IType;
}
});
fLifeCycle= new TypeHierarchyLifeCycle(false);
treeViewer.setSorter(new HierarchyViewerSorter(fLifeCycle));
treeViewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
fLabelProvider= new HierarchyLabelProvider(fLifeCycle);
fLabelProvider.setFilter(new ViewerFilter() {
public boolean select(Viewer viewer, Object parentElement, Object element) {
return hasFocusMethod((IType) element);
}
});
fLabelProvider.setTextFlags(JavaElementLabels.ALL_DEFAULT | JavaElementLabels.T_POST_QUALIFIED);
treeViewer.setLabelProvider(new DecoratingJavaLabelProvider(fLabelProvider, true, false));
treeViewer.getTree().addKeyListener(getKeyAdapter());
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout(1, false);
layout.marginHeight= 0;
layout.marginWidth= 0;
composite.setLayout(layout);
composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Horizontal separator line
Label separator= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT);
separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Status field label
fStatusTextLabel= new Label(parent, SWT.RIGHT);
fStatusTextLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
fStatusTextLabel.setText(getInfoLabel());
Font font= fStatusTextLabel.getFont();
Display display= parent.getDisplay();
FontData[] fontDatas= font.getFontData();
for (int i= 0; i < fontDatas.length; i++)
fontDatas[i].setHeight(fontDatas[i].getHeight() * 9 / 10);
fStatusTextFont= new Font(display, fontDatas);
fStatusTextLabel.setFont(fStatusTextFont);
// Regarding the color see bug 41128
fStatusTextLabel.setForeground(display.getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW));
return treeViewer;
}
protected boolean hasFocusMethod(IType type) {
if (fFocus == null) {
return true;
}
IMethod[] methods= type.findMethods(fFocus);
if (methods != null && methods.length > 0) {
try {
// check visibility
IPackageFragment pack= (IPackageFragment) fFocus.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
for (int i= 0; i < methods.length; i++) {
IMethod curr= methods[i];
if (JavaModelUtil.isVisibleInHierarchy(curr, pack)) {
return true;
}
}
} catch (JavaModelException e) {
// ignore
JavaPlugin.log(e);
}
}
return false;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.AbstractInformationControl#setForegroundColor(org.eclipse.swt.graphics.Color)
*/
public void setForegroundColor(Color foreground) {
super.setForegroundColor(foreground);
fHeaderLabel.setForeground(foreground);
fStatusTextLabel.getParent().setForeground(foreground);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.AbstractInformationControl#setBackgroundColor(org.eclipse.swt.graphics.Color)
*/
public void setBackgroundColor(Color background) {
super.setBackgroundColor(background);
fHeaderLabel.setBackground(background);
fStatusTextLabel.setBackground(background);
fStatusTextLabel.getParent().setBackground(background);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.AbstractInformationControl#dispose()
*/
public void dispose() {
if (fStatusTextFont != null && !fStatusTextFont.isDisposed())
fStatusTextFont.dispose();
super.dispose();
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.JavaOutlineInformationControl#setInput(java.lang.Object)
*/
public void setInput(Object information) {
if (!(information instanceof IJavaElement)) {
inputChanged(null, null);
return;
}
IJavaElement input= null;
IMethod locked= null;
try {
IJavaElement elem= (IJavaElement) information;
switch (elem.getElementType()) {
case IJavaElement.JAVA_PROJECT :
case IJavaElement.PACKAGE_FRAGMENT_ROOT :
case IJavaElement.PACKAGE_FRAGMENT :
case IJavaElement.TYPE :
input= elem;
break;
case IJavaElement.COMPILATION_UNIT :
input= ((ICompilationUnit) elem).findPrimaryType();
break;
case IJavaElement.CLASS_FILE :
input= ((IClassFile) elem).getType();
break;
case IJavaElement.METHOD :
IMethod method= (IMethod) elem;
if (!method.isConstructor()) {
locked= method;
}
input= method.getDeclaringType();
break;
case IJavaElement.FIELD :
case IJavaElement.INITIALIZER :
input= ((IMember) elem).getDeclaringType();
break;
case IJavaElement.PACKAGE_DECLARATION :
input= elem.getParent().getParent();
break;
case IJavaElement.IMPORT_DECLARATION :
IImportDeclaration decl= (IImportDeclaration) elem;
if (decl.isOnDemand()) {
input= JavaModelUtil.findTypeContainer(decl.getJavaProject(), Signature.getQualifier(decl.getElementName()));
} else {
input= decl.getJavaProject().findType(decl.getElementName());
}
break;
default :
input= null;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
fHeaderLabel.setText(getHeaderLabel(locked == null ? input : locked));
try {
fLifeCycle.ensureRefreshedTypeHierarchy(input, JavaPlugin.getActiveWorkbenchWindow());
} catch (InvocationTargetException e1) {
input= null;
} catch (InterruptedException e1) {
dispose();
return;
}
IMember[] memberFilter= locked != null ? new IMember[] { locked } : null;
TraditionalHierarchyContentProvider contentProvider= new TraditionalHierarchyContentProvider(fLifeCycle);
contentProvider.setMemberFilter(memberFilter);
getTreeViewer().setContentProvider(contentProvider);
fOtherContentProvider= new SuperTypeHierarchyContentProvider(fLifeCycle);
fOtherContentProvider.setMemberFilter(memberFilter);
fFocus= locked;
Object[] topLevelObjects= contentProvider.getElements(fLifeCycle);
if (topLevelObjects.length > 0 && contentProvider.getChildren(topLevelObjects[0]).length > 40) {
fDoFilter= false;
} else {
getTreeViewer().addFilter(new NamePatternFilter());
}
Object selection= null;
if (input instanceof IMember) {
selection= input;
} else if (topLevelObjects.length > 0) {
selection= topLevelObjects[0];
}
inputChanged(fLifeCycle, selection);
}
protected void stringMatcherUpdated() {
if (fDoFilter) {
super.stringMatcherUpdated(); // refresh the view
} else {
selectFirstMatch();
}
}
protected void toggleHierarchy() {
TreeViewer treeViewer= getTreeViewer();
Object[] expandedElements= treeViewer.getExpandedElements();
TypeHierarchyContentProvider contentProvider= (TypeHierarchyContentProvider) treeViewer.getContentProvider();
treeViewer.setContentProvider(fOtherContentProvider);
treeViewer.refresh();
if (fOtherExpandedElements != null) {
treeViewer.setExpandedElements(fOtherExpandedElements);
} else {
treeViewer.expandAll();
}
fOtherContentProvider= contentProvider;
fOtherExpandedElements= expandedElements;
fStatusTextLabel.setText(getInfoLabel());
}
private String getHeaderLabel(IJavaElement input) {
if (input instanceof IMethod) {
String[] args= { input.getParent().getElementName(), JavaElementLabels.getElementLabel(input, JavaElementLabels.ALL_DEFAULT) };
return TypeHierarchyMessages.getFormattedString("HierarchyInformationControl.methodhierarchy.label", args); //$NON-NLS-1$
} else {
String arg= JavaElementLabels.getElementLabel(input, JavaElementLabels.DEFAULT_QUALIFIED);
return TypeHierarchyMessages.getFormattedString("HierarchyInformationControl.hierarchy.label", arg); //$NON-NLS-1$
}
}
private String getInfoLabel() {
KeySequence[] sequences= getKeySequences();
String keyName= sequences[0].format();
if (fOtherContentProvider instanceof TraditionalHierarchyContentProvider) {
return TypeHierarchyMessages.getFormattedString("HierarchyInformationControl.toggle.traditionalhierarchy.label", keyName); //$NON-NLS-1$
} else {
return TypeHierarchyMessages.getFormattedString("HierarchyInformationControl.toggle.superhierarchy.label", keyName); //$NON-NLS-1$
}
}
/*
* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.AbstractInformationControl#getSelectedElement()
*/
protected Object getSelectedElement() {
Object selectedElement= super.getSelectedElement();
if (selectedElement instanceof IType && fFocus != null) {
IMethod[] methods= ((IType) selectedElement).findMethods(fFocus);
if (methods != null && methods.length > 0) {
return methods[0];
}
}
return selectedElement;
}
/*
* Copied from KeySupport
*/
protected KeyStroke convertAcceleratorToKeyStroke(int accelerator) {
final SortedSet modifierKeys = new TreeSet();
NaturalKey naturalKey = null;
if ((accelerator & SWT.ALT) != 0)
modifierKeys.add(ModifierKey.ALT);
if ((accelerator & SWT.COMMAND) != 0)
modifierKeys.add(ModifierKey.COMMAND);
if ((accelerator & SWT.CTRL) != 0)
modifierKeys.add(ModifierKey.CTRL);
if ((accelerator & SWT.SHIFT) != 0)
modifierKeys.add(ModifierKey.SHIFT);
if (((accelerator & SWT.KEY_MASK) == 0) && (accelerator != 0)) {
// There were only accelerators
naturalKey = null;
} else {
// There were other keys.
accelerator &= SWT.KEY_MASK;
switch (accelerator) {
case SWT.ARROW_DOWN :
naturalKey = SpecialKey.ARROW_DOWN;
break;
case SWT.ARROW_LEFT :
naturalKey = SpecialKey.ARROW_LEFT;
break;
case SWT.ARROW_RIGHT :
naturalKey = SpecialKey.ARROW_RIGHT;
break;
case SWT.ARROW_UP :
naturalKey = SpecialKey.ARROW_UP;
break;
case SWT.END :
naturalKey = SpecialKey.END;
break;
case SWT.F1 :
naturalKey = SpecialKey.F1;
break;
case SWT.F10 :
naturalKey = SpecialKey.F10;
break;
case SWT.F11 :
naturalKey = SpecialKey.F11;
break;
case SWT.F12 :
naturalKey = SpecialKey.F12;
break;
case SWT.F2 :
naturalKey = SpecialKey.F2;
break;
case SWT.F3 :
naturalKey = SpecialKey.F3;
break;
case SWT.F4 :
naturalKey = SpecialKey.F4;
break;
case SWT.F5 :
naturalKey = SpecialKey.F5;
break;
case SWT.F6 :
naturalKey = SpecialKey.F6;
break;
case SWT.F7 :
naturalKey = SpecialKey.F7;
break;
case SWT.F8 :
naturalKey = SpecialKey.F8;
break;
case SWT.F9 :
naturalKey = SpecialKey.F9;
break;
case SWT.HOME :
naturalKey = SpecialKey.HOME;
break;
case SWT.INSERT :
naturalKey = SpecialKey.INSERT;
break;
case SWT.PAGE_DOWN :
naturalKey = SpecialKey.PAGE_DOWN;
break;
case SWT.PAGE_UP :
naturalKey = SpecialKey.PAGE_UP;
break;
default :
naturalKey = CharacterKey.getInstance((char) (accelerator & 0xFFFF));
}
}
return KeyStroke.getInstance(modifierKeys, naturalKey);
}
/*
* Copied from KeySupport
*/
protected int convertEventToUnmodifiedAccelerator(KeyEvent e) {
int modifiers = e.stateMask & SWT.MODIFIER_MASK;
char ch = (char) e.keyCode;
return modifiers + (Character.isLetter(ch) ? Character.toUpperCase(ch) : ch);
}
}
|
41,523 |
Bug 41523 Keep Order of libs when editing library [build path]
|
When I edit a library in the Properties dialog of my project using "Properties"->"Java Build Path"->"Libraries"->"Edit", e.g. changing the JRE from 1.4 to 1.3, or changing from an old version of a JAR to a newer one, the changed library is at the last position in the classpath. It should kept at the position it was.
|
resolved fixed
|
b04b6c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-22T17:59:25Z | 2003-08-14T08:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/CPListElement.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.wizards.buildpaths;
import java.net.URL;
import java.util.ArrayList;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaUI;
public class CPListElement {
public static final String SOURCEATTACHMENT= "sourcepath"; //$NON-NLS-1$
public static final String SOURCEATTACHMENTROOT= "rootpath"; //$NON-NLS-1$
public static final String JAVADOC= "javadoc"; //$NON-NLS-1$
public static final String OUTPUT= "output"; //$NON-NLS-1$
public static final String EXCLUSION= "exclusion"; //$NON-NLS-1$
private IJavaProject fProject;
private int fEntryKind;
private IPath fPath;
private IResource fResource;
private boolean fIsExported;
private boolean fIsMissing;
private CPListElement fParentContainer;
private IClasspathEntry fCachedEntry;
private ArrayList fChildren;
public CPListElement(IJavaProject project, int entryKind, IPath path, IResource res) {
fProject= project;
fEntryKind= entryKind;
fPath= path;
fChildren= new ArrayList();
fResource= res;
fIsExported= false;
fIsMissing= false;
fCachedEntry= null;
fParentContainer= null;
switch (entryKind) {
case IClasspathEntry.CPE_SOURCE:
createAttributeElement(OUTPUT, null);
createAttributeElement(EXCLUSION, new Path[0]);
break;
case IClasspathEntry.CPE_LIBRARY:
case IClasspathEntry.CPE_VARIABLE:
createAttributeElement(SOURCEATTACHMENT, null);
createAttributeElement(JAVADOC, null);
break;
case IClasspathEntry.CPE_PROJECT:
break;
case IClasspathEntry.CPE_CONTAINER:
try {
IClasspathContainer container= JavaCore.getClasspathContainer(fPath, fProject);
if (container != null) {
IClasspathEntry[] entries= container.getClasspathEntries();
for (int i= 0; i < entries.length; i++) {
CPListElement curr= createFromExisting(entries[i], fProject);
curr.setParentContainer(this);
fChildren.add(curr);
}
}
} catch (JavaModelException e) {
}
break;
default:
}
}
public IClasspathEntry getClasspathEntry() {
if (fCachedEntry == null) {
fCachedEntry= newClasspathEntry();
}
return fCachedEntry;
}
private IClasspathEntry newClasspathEntry() {
switch (fEntryKind) {
case IClasspathEntry.CPE_SOURCE:
IPath outputLocation= (IPath) getAttribute(OUTPUT);
IPath[] exclusionPattern= (IPath[]) getAttribute(EXCLUSION);
return JavaCore.newSourceEntry(fPath, exclusionPattern, outputLocation);
case IClasspathEntry.CPE_LIBRARY:
IPath attach= (IPath) getAttribute(SOURCEATTACHMENT);
return JavaCore.newLibraryEntry(fPath, attach, null, isExported());
case IClasspathEntry.CPE_PROJECT:
return JavaCore.newProjectEntry(fPath, isExported());
case IClasspathEntry.CPE_CONTAINER:
return JavaCore.newContainerEntry(fPath, isExported());
case IClasspathEntry.CPE_VARIABLE:
IPath varAttach= (IPath) getAttribute(SOURCEATTACHMENT);
return JavaCore.newVariableEntry(fPath, varAttach, null, isExported());
default:
return null;
}
}
/**
* Gets the classpath entry path.
* @see IClasspathEntry#getPath()
*/
public IPath getPath() {
return fPath;
}
/**
* Gets the classpath entry kind.
* @see IClasspathEntry#getEntryKind()
*/
public int getEntryKind() {
return fEntryKind;
}
/**
* Entries without resource are either non existing or a variable entry
* External jars do not have a resource
*/
public IResource getResource() {
return fResource;
}
public CPListElementAttribute setAttribute(String key, Object value) {
CPListElementAttribute attribute= findAttributeElement(key);
if (attribute == null) {
return null;
}
attribute.setValue(value);
attributeChanged(key);
return attribute;
}
private CPListElementAttribute findAttributeElement(String key) {
for (int i= 0; i < fChildren.size(); i++) {
Object curr= fChildren.get(i);
if (curr instanceof CPListElementAttribute) {
CPListElementAttribute elem= (CPListElementAttribute) curr;
if (key.equals(elem.getKey())) {
return elem;
}
}
}
return null;
}
public Object getAttribute(String key) {
CPListElementAttribute attrib= findAttributeElement(key);
if (attrib != null) {
return attrib.getValue();
}
return null;
}
private void createAttributeElement(String key, Object value) {
fChildren.add(new CPListElementAttribute(this, key, value));
}
public Object[] getChildren(boolean hideOutputFolder) {
if (hideOutputFolder && fEntryKind == IClasspathEntry.CPE_SOURCE) {
return new Object[] { findAttributeElement(EXCLUSION) };
}
return fChildren.toArray();
}
private void setParentContainer(CPListElement element) {
fParentContainer= element;
}
public CPListElement getParentContainer() {
return fParentContainer;
}
private void attributeChanged(String key) {
fCachedEntry= null;
}
/*
* @see Object#equals(java.lang.Object)
*/
public boolean equals(Object other) {
if (other != null && other.getClass().equals(getClass())) {
CPListElement elem= (CPListElement)other;
return elem.fEntryKind == fEntryKind && elem.fPath.equals(fPath);
}
return false;
}
/*
* @see Object#hashCode()
*/
public int hashCode() {
return fPath.hashCode() + fEntryKind;
}
/**
* Returns if a entry is missing.
* @return Returns a boolean
*/
public boolean isMissing() {
return fIsMissing;
}
/**
* Sets the 'missing' state of the entry.
*/
public void setIsMissing(boolean isMissing) {
fIsMissing= isMissing;
}
/**
* Returns if a entry is exported (only applies to libraries)
* @return Returns a boolean
*/
public boolean isExported() {
return fIsExported;
}
/**
* Sets the export state of the entry.
*/
public void setExported(boolean isExported) {
if (isExported != fIsExported) {
fIsExported = isExported;
attributeChanged(null);
}
}
/**
* Gets the project.
* @return Returns a IJavaProject
*/
public IJavaProject getJavaProject() {
return fProject;
}
public static CPListElement createFromExisting(IClasspathEntry curr, IJavaProject project) {
IPath path= curr.getPath();
IWorkspaceRoot root= project.getProject().getWorkspace().getRoot();
// get the resource
IResource res= null;
boolean isMissing= false;
URL javaDocLocation= null;
switch (curr.getEntryKind()) {
case IClasspathEntry.CPE_CONTAINER:
res= null;
try {
isMissing= (JavaCore.getClasspathContainer(path, project) == null);
} catch (JavaModelException e) {
isMissing= true;
}
break;
case IClasspathEntry.CPE_VARIABLE:
IPath resolvedPath= JavaCore.getResolvedVariablePath(path);
res= null;
isMissing= root.findMember(resolvedPath) == null && !resolvedPath.toFile().isFile();
javaDocLocation= JavaUI.getLibraryJavadocLocation(resolvedPath);
break;
case IClasspathEntry.CPE_LIBRARY:
res= root.findMember(path);
if (res == null) {
if (!ArchiveFileFilter.isArchivePath(path)) {
if (root.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()
&& root.getProject(path.segment(0)).exists()) {
res= root.getFolder(path);
}
}
isMissing= !path.toFile().isFile(); // look for external JARs
}
javaDocLocation= JavaUI.getLibraryJavadocLocation(path);
break;
case IClasspathEntry.CPE_SOURCE:
res= root.findMember(path);
if (res == null) {
if (root.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()) {
res= root.getFolder(path);
}
isMissing= true;
}
break;
case IClasspathEntry.CPE_PROJECT:
res= root.findMember(path);
isMissing= (res == null);
break;
}
CPListElement elem= new CPListElement(project, curr.getEntryKind(), path, res);
elem.setExported(curr.isExported());
elem.setAttribute(SOURCEATTACHMENT, curr.getSourceAttachmentPath());
elem.setAttribute(JAVADOC, javaDocLocation);
elem.setAttribute(OUTPUT, curr.getOutputLocation());
elem.setAttribute(EXCLUSION, curr.getExclusionPatterns());
if (project.exists()) {
elem.setIsMissing(isMissing);
}
return elem;
}
}
|
41,523 |
Bug 41523 Keep Order of libs when editing library [build path]
|
When I edit a library in the Properties dialog of my project using "Properties"->"Java Build Path"->"Libraries"->"Edit", e.g. changing the JRE from 1.4 to 1.3, or changing from an old version of a JAR to a newer one, the changed library is at the last position in the classpath. It should kept at the position it was.
|
resolved fixed
|
b04b6c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-22T17:59:25Z | 2003-08-14T08:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/LibrariesWorkbookPage.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.wizards.buildpaths;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.views.navigator.ResourceSorter;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.IUIConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusDialog;
import org.eclipse.jdt.internal.ui.preferences.JavadocConfigurationBlock;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField;
public class LibrariesWorkbookPage extends BuildPathBasePage {
private ListDialogField fClassPathList;
private IJavaProject fCurrJProject;
private TreeListDialogField fLibrariesList;
private IWorkspaceRoot fWorkspaceRoot;
private IDialogSettings fDialogSettings;
private Control fSWTControl;
private final int IDX_ADDJAR= 0;
private final int IDX_ADDEXT= 1;
private final int IDX_ADDVAR= 2;
private final int IDX_ADDLIB= 3;
private final int IDX_ADDFOL= 4;
private final int IDX_EDIT= 6;
private final int IDX_REMOVE= 7;
public LibrariesWorkbookPage(IWorkspaceRoot root, ListDialogField classPathList) {
fClassPathList= classPathList;
fWorkspaceRoot= root;
fSWTControl= null;
fDialogSettings= JavaPlugin.getDefault().getDialogSettings();
String[] buttonLabels= new String[] {
/* IDX_ADDJAR*/ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addjar.button"), //$NON-NLS-1$
/* IDX_ADDEXT */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addextjar.button"), //$NON-NLS-1$
/* IDX_ADDVAR */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addvariable.button"), //$NON-NLS-1$
/* IDX_ADDLIB */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addlibrary.button"), //$NON-NLS-1$
/* IDX_ADDFOL */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addclassfolder.button"), //$NON-NLS-1$
/* */ null,
/* IDX_EDIT */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.edit.button"), //$NON-NLS-1$
/* IDX_REMOVE */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.remove.button") //$NON-NLS-1$
};
LibrariesAdapter adapter= new LibrariesAdapter();
fLibrariesList= new TreeListDialogField(adapter, buttonLabels, new CPListLabelProvider());
fLibrariesList.setDialogFieldListener(adapter);
fLibrariesList.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.libraries.label")); //$NON-NLS-1$
fLibrariesList.enableButton(IDX_REMOVE, false);
fLibrariesList.enableButton(IDX_EDIT, false);
fLibrariesList.setViewerSorter(new CPListElementSorter());
}
public void init(IJavaProject jproject) {
fCurrJProject= jproject;
updateLibrariesList();
}
private void updateLibrariesList() {
List cpelements= fClassPathList.getElements();
List libelements= new ArrayList(cpelements.size());
int nElements= cpelements.size();
for (int i= 0; i < nElements; i++) {
CPListElement cpe= (CPListElement)cpelements.get(i);
if (isEntryKind(cpe.getEntryKind())) {
libelements.add(cpe);
}
}
fLibrariesList.setElements(libelements);
}
// -------- ui creation
public Control getControl(Composite parent) {
PixelConverter converter= new PixelConverter(parent);
Composite composite= new Composite(parent, SWT.NONE);
LayoutUtil.doDefaultLayout(composite, new DialogField[] { fLibrariesList }, true);
LayoutUtil.setHorizontalGrabbing(fLibrariesList.getTreeControl(null));
int buttonBarWidth= converter.convertWidthInCharsToPixels(24);
fLibrariesList.setButtonsMinWidth(buttonBarWidth);
fLibrariesList.getTreeViewer().setSorter(new CPListElementSorter());
fSWTControl= composite;
return composite;
}
private Shell getShell() {
if (fSWTControl != null) {
return fSWTControl.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
private class LibrariesAdapter implements IDialogFieldListener, ITreeListAdapter {
private final Object[] EMPTY_ARR= new Object[0];
// -------- IListAdapter --------
public void customButtonPressed(TreeListDialogField field, int index) {
libaryPageCustomButtonPressed(field, index);
}
public void selectionChanged(TreeListDialogField field) {
libaryPageSelectionChanged(field);
}
public void doubleClicked(TreeListDialogField field) {
libaryPageDoubleClicked(field);
}
public void keyPressed(TreeListDialogField field, KeyEvent event) {
libaryPageKeyPressed(field, event);
}
public Object[] getChildren(TreeListDialogField field, Object element) {
if (element instanceof CPListElement) {
return ((CPListElement) element).getChildren(false);
}
return EMPTY_ARR;
}
public Object getParent(TreeListDialogField field, Object element) {
if (element instanceof CPListElementAttribute) {
return ((CPListElementAttribute) element).getParent();
}
return null;
}
public boolean hasChildren(TreeListDialogField field, Object element) {
return (element instanceof CPListElement);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
libaryPageDialogFieldChanged(field);
}
}
private void libaryPageCustomButtonPressed(DialogField field, int index) {
CPListElement[] libentries= null;
switch (index) {
case IDX_ADDJAR: /* add jar */
libentries= openJarFileDialog(null);
break;
case IDX_ADDEXT: /* add external jar */
libentries= openExtJarFileDialog(null);
break;
case IDX_ADDVAR: /* add variable */
libentries= openVariableSelectionDialog(null);
break;
case IDX_ADDLIB: /* addvanced */
libentries= openContainerSelectionDialog(null);
break;
case IDX_ADDFOL: /* addvanced */
libentries= openClassFolderDialog(null);
break;
case IDX_EDIT: /* edit */
editEntry();
return;
case IDX_REMOVE: /* remove */
removeEntry();
return;
}
if (libentries != null) {
int nElementsChosen= libentries.length;
// remove duplicates
List cplist= fLibrariesList.getElements();
List elementsToAdd= new ArrayList(nElementsChosen);
for (int i= 0; i < nElementsChosen; i++) {
CPListElement curr= libentries[i];
if (!cplist.contains(curr) && !elementsToAdd.contains(curr)) {
elementsToAdd.add(curr);
curr.setAttribute(CPListElement.SOURCEATTACHMENT, guessAttachment(curr));
curr.setAttribute(CPListElement.JAVADOC, JavaUI.getLibraryJavadocLocation(curr.getPath()));
}
}
fLibrariesList.addElements(elementsToAdd);
fLibrariesList.postSetSelection(new StructuredSelection(libentries));
}
}
protected void libaryPageDoubleClicked(TreeListDialogField field) {
List selection= fLibrariesList.getSelectedElements();
if (canEdit(selection)) {
editEntry();
}
}
protected void libaryPageKeyPressed(TreeListDialogField field, KeyEvent event) {
if (field == fLibrariesList) {
if (event.character == SWT.DEL && event.stateMask == 0) {
List selection= field.getSelectedElements();
if (canRemove(selection)) {
removeEntry();
}
}
}
}
private void removeEntry() {
List selElements= fLibrariesList.getSelectedElements();
for (int i= selElements.size() - 1; i >= 0 ; i--) {
Object elem= selElements.get(i);
if (elem instanceof CPListElementAttribute) {
CPListElementAttribute attrib= (CPListElementAttribute) elem;
attrib.getParent().setAttribute(attrib.getKey(), null);
selElements.remove(i);
}
}
if (selElements.isEmpty()) {
fLibrariesList.refresh();
fClassPathList.dialogFieldChanged(); // validate
} else {
fLibrariesList.removeElements(selElements);
}
}
private boolean canRemove(List selElements) {
if (selElements.size() == 0) {
return false;
}
for (int i= 0; i < selElements.size(); i++) {
Object elem= selElements.get(i);
if (elem instanceof CPListElementAttribute) {
if (((CPListElementAttribute)elem).getValue() == null) {
return false;
}
} else if (elem instanceof CPListElement) {
CPListElement curr= (CPListElement) elem;
if (curr.getParentContainer() != null) {
return false;
}
}
}
return true;
}
/**
* Method editEntry.
*/
private void editEntry() {
List selElements= fLibrariesList.getSelectedElements();
if (selElements.size() != 1) {
return;
}
Object elem= selElements.get(0);
if (fLibrariesList.getIndexOfElement(elem) != -1) {
editElementEntry((CPListElement) elem);
} else if (elem instanceof CPListElementAttribute) {
editAttributeEntry((CPListElementAttribute) elem);
}
}
private void editAttributeEntry(CPListElementAttribute elem) {
String key= elem.getKey();
if (key.equals(CPListElement.SOURCEATTACHMENT)) {
CPListElement selElement= elem.getParent();
IPath containerPath= null;
boolean applyChanges= false;
CPListElement parentContainer= selElement.getParentContainer();
if (parentContainer != null) {
containerPath= parentContainer.getPath();
applyChanges= true;
}
SourceAttachmentDialog dialog= new SourceAttachmentDialog(getShell(), selElement.getClasspathEntry(), containerPath, fCurrJProject, applyChanges);
if (dialog.open() == Window.OK) {
selElement.setAttribute(CPListElement.SOURCEATTACHMENT, dialog.getSourceAttachmentPath());
fLibrariesList.refresh();
fClassPathList.refresh(); // images
}
} else if (key.equals(CPListElement.JAVADOC)) {
CPListElement selElement= elem.getParent();
JavadocPropertyDialog dialog= new JavadocPropertyDialog(getShell(), selElement);
if (dialog.open() == Window.OK) {
selElement.setAttribute(CPListElement.JAVADOC, dialog.getJavaDocLocation());
fLibrariesList.refresh();
}
}
}
private void editElementEntry(CPListElement elem) {
CPListElement[] res= null;
switch (elem.getEntryKind()) {
case IClasspathEntry.CPE_CONTAINER:
res= openContainerSelectionDialog(elem);
break;
case IClasspathEntry.CPE_LIBRARY:
IResource resource= elem.getResource();
if (resource == null) {
res= openExtJarFileDialog(elem);
} else if (resource.getType() == IResource.FOLDER) {
if (resource.exists()) {
res= openClassFolderDialog(elem);
} else {
res= openNewClassFolderDialog(elem);
}
} else if (resource.getType() == IResource.FILE) {
res= openJarFileDialog(elem);
}
break;
case IClasspathEntry.CPE_VARIABLE:
res= openVariableSelectionDialog(elem);
break;
}
if (res != null && res.length > 0) {
fLibrariesList.replaceElement(elem, res[0]);
}
}
private void libaryPageSelectionChanged(DialogField field) {
List selElements= fLibrariesList.getSelectedElements();
fLibrariesList.enableButton(IDX_EDIT, canEdit(selElements));
fLibrariesList.enableButton(IDX_REMOVE, canRemove(selElements));
}
private boolean canEdit(List selElements) {
if (selElements.size() != 1) {
return false;
}
Object elem= selElements.get(0);
if (fLibrariesList.getIndexOfElement(elem) != -1) {
return true;
}
if (elem instanceof CPListElementAttribute) {
return true;
}
return false;
}
private void libaryPageDialogFieldChanged(DialogField field) {
if (fCurrJProject != null) {
// already initialized
updateClasspathList();
}
}
private void updateClasspathList() {
List projelements= fLibrariesList.getElements();
boolean remove= false;
List cpelements= fClassPathList.getElements();
// backwards, as entries will be deleted
for (int i= cpelements.size() - 1; i >= 0; i--) {
CPListElement cpe= (CPListElement)cpelements.get(i);
int kind= cpe.getEntryKind();
if (isEntryKind(kind)) {
if (!projelements.remove(cpe)) {
cpelements.remove(i);
remove= true;
}
}
}
for (int i= 0; i < projelements.size(); i++) {
cpelements.add(projelements.get(i));
}
if (remove || (projelements.size() > 0)) {
fClassPathList.setElements(cpelements);
}
}
private CPListElement[] openNewClassFolderDialog(CPListElement existing) {
String title= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.NewClassFolderDialog.new.title") : NewWizardMessages.getString("LibrariesWorkbookPage.NewClassFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
IProject currProject= fCurrJProject.getProject();
NewContainerDialog dialog= new NewContainerDialog(getShell(), title, currProject, getUsedContainers(existing), existing);
IPath projpath= currProject.getFullPath();
dialog.setMessage(NewWizardMessages.getFormattedString("LibrariesWorkbookPage.NewClassFolderDialog.description", projpath.toString())); //$NON-NLS-1$
if (dialog.open() == Window.OK) {
IFolder folder= dialog.getFolder();
return new CPListElement[] { newCPLibraryElement(folder) };
}
return null;
}
private CPListElement[] openClassFolderDialog(CPListElement existing) {
Class[] acceptedClasses= new Class[] { IFolder.class };
TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, existing == null);
acceptedClasses= new Class[] { IProject.class, IFolder.class };
ViewerFilter filter= new TypedViewerFilter(acceptedClasses, getUsedContainers(existing));
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
String title= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.new.title") : NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
String message= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.new.description") : NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.edit.description"); //$NON-NLS-1$ //$NON-NLS-2$
FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp);
dialog.setValidator(validator);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.addFilter(filter);
dialog.setInput(fWorkspaceRoot);
dialog.setSorter(new ResourceSorter(ResourceSorter.NAME));
if (existing == null) {
dialog.setInitialSelection(fCurrJProject.getProject());
} else {
dialog.setInitialSelection(existing.getResource());
}
if (dialog.open() == Window.OK) {
Object[] elements= dialog.getResult();
CPListElement[] res= new CPListElement[elements.length];
for (int i= 0; i < res.length; i++) {
IResource elem= (IResource) elements[i];
res[i]= newCPLibraryElement(elem);
}
return res;
}
return null;
}
private CPListElement[] openJarFileDialog(CPListElement existing) {
Class[] acceptedClasses= new Class[] { IFile.class };
TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, existing == null);
ViewerFilter filter= new ArchiveFileFilter(getUsedJARFiles(existing), true);
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
String title= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.new.title") : NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
String message= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.new.description") : NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.edit.description"); //$NON-NLS-1$ //$NON-NLS-2$
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp);
dialog.setValidator(validator);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.addFilter(filter);
dialog.setInput(fWorkspaceRoot);
dialog.setSorter(new ResourceSorter(ResourceSorter.NAME));
if (existing == null) {
dialog.setInitialSelection(fCurrJProject.getProject());
} else {
dialog.setInitialSelection(existing.getResource());
}
if (dialog.open() == Window.OK) {
Object[] elements= dialog.getResult();
CPListElement[] res= new CPListElement[elements.length];
for (int i= 0; i < res.length; i++) {
IResource elem= (IResource)elements[i];
res[i]= newCPLibraryElement(elem);
}
return res;
}
return null;
}
private IContainer[] getUsedContainers(CPListElement existing) {
ArrayList res= new ArrayList();
if (fCurrJProject.exists()) {
try {
IPath outputLocation= fCurrJProject.getOutputLocation();
if (outputLocation != null) {
IResource resource= fWorkspaceRoot.findMember(outputLocation);
if (resource instanceof IFolder) { // != Project
res.add(resource);
}
}
} catch (JavaModelException e) {
// ignore it here, just log
JavaPlugin.log(e.getStatus());
}
}
List cplist= fLibrariesList.getElements();
for (int i= 0; i < cplist.size(); i++) {
CPListElement elem= (CPListElement)cplist.get(i);
if (elem.getEntryKind() == IClasspathEntry.CPE_LIBRARY && (elem != existing)) {
IResource resource= elem.getResource();
if (resource instanceof IContainer && !resource.equals(existing)) {
res.add(resource);
}
}
}
return (IContainer[]) res.toArray(new IContainer[res.size()]);
}
private IFile[] getUsedJARFiles(CPListElement existing) {
List res= new ArrayList();
List cplist= fLibrariesList.getElements();
for (int i= 0; i < cplist.size(); i++) {
CPListElement elem= (CPListElement)cplist.get(i);
if (elem.getEntryKind() == IClasspathEntry.CPE_LIBRARY && (elem != existing)) {
IResource resource= elem.getResource();
if (resource instanceof IFile) {
res.add(resource);
}
}
}
return (IFile[]) res.toArray(new IFile[res.size()]);
}
private CPListElement newCPLibraryElement(IResource res) {
return new CPListElement(fCurrJProject, IClasspathEntry.CPE_LIBRARY, res.getFullPath(), res);
}
private CPListElement[] openExtJarFileDialog(CPListElement existing) {
String lastUsedPath;
if (existing != null) {
lastUsedPath= existing.getPath().removeLastSegments(1).toOSString();
} else {
lastUsedPath= fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTEXTJAR);
if (lastUsedPath == null) {
lastUsedPath= ""; //$NON-NLS-1$
}
}
String title= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.ExtJARArchiveDialog.new.title") : NewWizardMessages.getString("LibrariesWorkbookPage.ExtJARArchiveDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
FileDialog dialog= new FileDialog(getShell(), existing == null ? SWT.MULTI : SWT.SINGLE);
dialog.setText(title);
dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$
dialog.setFilterPath(lastUsedPath);
if (existing != null) {
dialog.setFileName(existing.getPath().lastSegment());
}
String res= dialog.open();
if (res == null) {
return null;
}
String[] fileNames= dialog.getFileNames();
int nChosen= fileNames.length;
IPath filterPath= new Path(dialog.getFilterPath());
CPListElement[] elems= new CPListElement[nChosen];
for (int i= 0; i < nChosen; i++) {
IPath path= filterPath.append(fileNames[i]).makeAbsolute();
elems[i]= new CPListElement(fCurrJProject, IClasspathEntry.CPE_LIBRARY, path, null);
}
fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, filterPath.toOSString());
return elems;
}
private CPListElement[] openVariableSelectionDialog(CPListElement existing) {
if (existing == null) {
NewVariableEntryDialog dialog= new NewVariableEntryDialog(getShell());
dialog.setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.VariableSelectionDialog.new.title")); //$NON-NLS-1$
if (dialog.open() == Window.OK) {
List existingElements= fLibrariesList.getElements();
IPath[] paths= dialog.getResult();
ArrayList result= new ArrayList();
for (int i = 0; i < paths.length; i++) {
CPListElement elem= new CPListElement(fCurrJProject, IClasspathEntry.CPE_VARIABLE, paths[i], null);
IPath resolvedPath= JavaCore.getResolvedVariablePath(paths[i]);
elem.setIsMissing((resolvedPath == null) || !resolvedPath.toFile().exists());
if (!existingElements.contains(elem)) {
result.add(elem);
}
}
return (CPListElement[]) result.toArray(new CPListElement[result.size()]);
}
} else {
List existingElements= fLibrariesList.getElements();
ArrayList existingPaths= new ArrayList(existingElements.size());
for (int i= 0; i < existingElements.size(); i++) {
CPListElement elem= (CPListElement) existingElements.get(i);
if (elem.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
existingPaths.add(elem.getPath());
}
}
EditVariableEntryDialog dialog= new EditVariableEntryDialog(getShell(), existing.getPath(), existingPaths);
dialog.setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.VariableSelectionDialog.edit.title")); //$NON-NLS-1$
if (dialog.open() == Window.OK) {
CPListElement elem= new CPListElement(fCurrJProject, IClasspathEntry.CPE_VARIABLE, dialog.getPath(), null);
return new CPListElement[] { elem };
}
}
return null;
}
private CPListElement[] openContainerSelectionDialog(CPListElement existing) {
IClasspathEntry elem= null;
String title;
if (existing == null) {
title= NewWizardMessages.getString("LibrariesWorkbookPage.ContainerDialog.new.title"); //$NON-NLS-1$
} else {
title= NewWizardMessages.getString("LibrariesWorkbookPage.ContainerDialog.edit.title"); //$NON-NLS-1$
elem= existing.getClasspathEntry();
}
return openContainerDialog(title, new ClasspathContainerWizard(elem, fCurrJProject, getRawClasspath()));
}
private CPListElement[] openContainerDialog(String title, ClasspathContainerWizard wizard) {
wizard.setWindowTitle(title);
WizardDialog dialog= new WizardDialog(getShell(), wizard);
PixelConverter converter= new PixelConverter(getShell());
dialog.setMinimumPageSize(converter.convertWidthInCharsToPixels(40), converter.convertHeightInCharsToPixels(20));
dialog.create();
if (dialog.open() == Window.OK) {
IClasspathEntry created= wizard.getNewEntry();
if (created != null) {
CPListElement elem= new CPListElement(fCurrJProject, IClasspathEntry.CPE_CONTAINER, created.getPath(), null);
if (elem != null) {
return new CPListElement[] { elem };
}
}
}
return null;
}
private IPath guessAttachment(CPListElement elem) {
if (elem.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
return null;
}
try {
// try if the jar itself contains the source
IJavaModel jmodel= fCurrJProject.getJavaModel();
IJavaProject[] jprojects= jmodel.getJavaProjects();
for (int i= 0; i < jprojects.length; i++) {
IJavaProject curr= jprojects[i];
if (!curr.equals(fCurrJProject)) {
IClasspathEntry[] entries= curr.getRawClasspath();
for (int k= 0; k < entries.length; k++) {
IClasspathEntry entry= entries[k];
if (entry.getEntryKind() == elem.getEntryKind()
&& entry.getPath().equals(elem.getPath())) {
IPath attachPath= entry.getSourceAttachmentPath();
if (attachPath != null && !attachPath.isEmpty()) {
return attachPath;
}
}
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
return null;
}
private IClasspathEntry[] getRawClasspath() {
IClasspathEntry[] currEntries= new IClasspathEntry[fClassPathList.getSize()];
for (int i= 0; i < currEntries.length; i++) {
CPListElement curr= (CPListElement) fClassPathList.getElement(i);
currEntries[i]= curr.getClasspathEntry();
}
return currEntries;
}
private class JavadocPropertyDialog extends StatusDialog implements IStatusChangeListener {
private JavadocConfigurationBlock fJavadocConfigurationBlock;
public JavadocPropertyDialog(Shell parent, CPListElement element) {
super(parent);
setTitle(NewWizardMessages.getFormattedString("LibrariesWorkbookPage.JavadocPropertyDialog.title", element.getPath().toString())); //$NON-NLS-1$
URL initialLocation= JavaUI.getLibraryJavadocLocation(element.getPath());
fJavadocConfigurationBlock= new JavadocConfigurationBlock(parent, this, initialLocation, false);
}
protected Control createDialogArea(Composite parent) {
Composite composite= (Composite) super.createDialogArea(parent);
Control inner= fJavadocConfigurationBlock.createContents(composite);
inner.setLayoutData(new GridData(GridData.FILL_BOTH));
applyDialogFont(composite);
return composite;
}
public void statusChanged(IStatus status) {
updateStatus(status);
}
public URL getJavaDocLocation() {
return fJavadocConfigurationBlock.getJavadocLocation();
}
/*
* @see org.eclipse.jface.window.Window#configureShell(Shell)
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.JAVADOC_PROPERTY_DIALOG);
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathBasePage#isEntryKind(int)
*/
public boolean isEntryKind(int kind) {
return kind == IClasspathEntry.CPE_LIBRARY || kind == IClasspathEntry.CPE_VARIABLE || kind == IClasspathEntry.CPE_CONTAINER;
}
/*
* @see BuildPathBasePage#getSelection
*/
public List getSelection() {
return fLibrariesList.getSelectedElements();
}
/*
* @see BuildPathBasePage#setSelection
*/
public void setSelection(List selElements) {
fLibrariesList.selectElements(new StructuredSelection(selElements));
}
}
|
41,523 |
Bug 41523 Keep Order of libs when editing library [build path]
|
When I edit a library in the Properties dialog of my project using "Properties"->"Java Build Path"->"Libraries"->"Edit", e.g. changing the JRE from 1.4 to 1.3, or changing from an old version of a JAR to a newer one, the changed library is at the last position in the classpath. It should kept at the position it was.
|
resolved fixed
|
b04b6c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-22T17:59:25Z | 2003-08-14T08:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/SourceContainerWorkbookPage.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.wizards.buildpaths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.views.navigator.ResourceSorter;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField;
public class SourceContainerWorkbookPage extends BuildPathBasePage {
private ListDialogField fClassPathList;
private IJavaProject fCurrJProject;
private IPath fProjPath;
private Control fSWTControl;
private IWorkspaceRoot fWorkspaceRoot;
private TreeListDialogField fFoldersList;
private StringDialogField fOutputLocationField;
private SelectionButtonDialogField fUseFolderOutputs;
private final int IDX_ADD= 0;
private final int IDX_EDIT= 2;
private final int IDX_REMOVE= 3;
public SourceContainerWorkbookPage(IWorkspaceRoot root, ListDialogField classPathList, StringDialogField outputLocationField) {
fWorkspaceRoot= root;
fClassPathList= classPathList;
fOutputLocationField= outputLocationField;
fSWTControl= null;
SourceContainerAdapter adapter= new SourceContainerAdapter();
String[] buttonLabels;
buttonLabels= new String[] {
/* 0 = IDX_ADDEXIST */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.add.button"), //$NON-NLS-1$
/* 1 */ null,
/* 2 = IDX_EDIT */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.edit.button"), //$NON-NLS-1$
/* 3 = IDX_REMOVE */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.remove.button") //$NON-NLS-1$
};
fFoldersList= new TreeListDialogField(adapter, buttonLabels, new CPListLabelProvider());
fFoldersList.setDialogFieldListener(adapter);
fFoldersList.setLabelText(NewWizardMessages.getString("SourceContainerWorkbookPage.folders.label")); //$NON-NLS-1$
fFoldersList.setViewerSorter(new CPListElementSorter());
fFoldersList.enableButton(IDX_EDIT, false);
fUseFolderOutputs= new SelectionButtonDialogField(SWT.CHECK);
fUseFolderOutputs.setSelection(false);
fUseFolderOutputs.setLabelText(NewWizardMessages.getString("SourceContainerWorkbookPage.folders.check")); //$NON-NLS-1$
fUseFolderOutputs.setDialogFieldListener(adapter);
}
public void init(IJavaProject jproject) {
fCurrJProject= jproject;
fProjPath= fCurrJProject.getProject().getFullPath();
updateFoldersList();
}
private void updateFoldersList() {
ArrayList folders= new ArrayList();
boolean useFolderOutputs= false;
List cpelements= fClassPathList.getElements();
for (int i= 0; i < cpelements.size(); i++) {
CPListElement cpe= (CPListElement)cpelements.get(i);
if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
folders.add(cpe);
boolean hasOutputFolder= (cpe.getAttribute(CPListElement.OUTPUT) != null);
if (hasOutputFolder) {
useFolderOutputs= true;
}
}
}
fFoldersList.setElements(folders);
fUseFolderOutputs.setSelection(useFolderOutputs);
for (int i= 0; i < folders.size(); i++) {
CPListElement cpe= (CPListElement) folders.get(i);
IPath[] patterns= (IPath[]) cpe.getAttribute(CPListElement.EXCLUSION);
boolean hasOutputFolder= (cpe.getAttribute(CPListElement.OUTPUT) != null);
if (patterns.length > 0 || hasOutputFolder) {
fFoldersList.expandElement(cpe, 3);
}
}
}
public Control getControl(Composite parent) {
PixelConverter converter= new PixelConverter(parent);
Composite composite= new Composite(parent, SWT.NONE);
LayoutUtil.doDefaultLayout(composite, new DialogField[] { fFoldersList, fUseFolderOutputs }, true);
LayoutUtil.setHorizontalGrabbing(fFoldersList.getTreeControl(null));
int buttonBarWidth= converter.convertWidthInCharsToPixels(24);
fFoldersList.setButtonsMinWidth(buttonBarWidth);
fSWTControl= composite;
// expand
List elements= fFoldersList.getElements();
for (int i= 0; i < elements.size(); i++) {
CPListElement elem= (CPListElement) elements.get(i);
IPath[] patterns= (IPath[]) elem.getAttribute(CPListElement.EXCLUSION);
IPath output= (IPath) elem.getAttribute(CPListElement.OUTPUT);
if (patterns.length > 0 || output != null) {
fFoldersList.expandElement(elem, 3);
}
}
return composite;
}
private Shell getShell() {
if (fSWTControl != null) {
return fSWTControl.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
private class SourceContainerAdapter implements ITreeListAdapter, IDialogFieldListener {
private final Object[] EMPTY_ARR= new Object[0];
// -------- IListAdapter --------
public void customButtonPressed(TreeListDialogField field, int index) {
sourcePageCustomButtonPressed(field, index);
}
public void selectionChanged(TreeListDialogField field) {
sourcePageSelectionChanged(field);
}
public void doubleClicked(TreeListDialogField field) {
sourcePageDoubleClicked(field);
}
public void keyPressed(TreeListDialogField field, KeyEvent event) {
sourcePageKeyPressed(field, event);
}
public Object[] getChildren(TreeListDialogField field, Object element) {
if (element instanceof CPListElement) {
return ((CPListElement) element).getChildren(!fUseFolderOutputs.isSelected());
}
return EMPTY_ARR;
}
public Object getParent(TreeListDialogField field, Object element) {
if (element instanceof CPListElementAttribute) {
return ((CPListElementAttribute) element).getParent();
}
return null;
}
public boolean hasChildren(TreeListDialogField field, Object element) {
return (element instanceof CPListElement);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
sourcePageDialogFieldChanged(field);
}
}
protected void sourcePageKeyPressed(TreeListDialogField field, KeyEvent event) {
if (field == fFoldersList) {
if (event.character == SWT.DEL && event.stateMask == 0) {
List selection= field.getSelectedElements();
if (canRemove(selection)) {
removeEntry();
}
}
}
}
protected void sourcePageDoubleClicked(TreeListDialogField field) {
if (field == fFoldersList) {
List selection= field.getSelectedElements();
if (canEdit(selection)) {
editEntry();
}
}
}
protected void sourcePageCustomButtonPressed(DialogField field, int index) {
if (field == fFoldersList) {
if (index == IDX_ADD) {
List elementsToAdd= new ArrayList(10);
if (fCurrJProject.getProject().exists()) {
CPListElement[] srcentries= openSourceContainerDialog(null);
if (srcentries != null) {
for (int i= 0; i < srcentries.length; i++) {
elementsToAdd.add(srcentries[i]);
}
}
} else {
CPListElement entry= openNewSourceContainerDialog(null);
if (entry != null) {
elementsToAdd.add(entry);
}
}
if (!elementsToAdd.isEmpty()) {
if (fFoldersList.getSize() == 1) {
CPListElement existing= (CPListElement) fFoldersList.getElement(0);
if (existing.getResource() instanceof IProject) {
askForChangingBuildPathDialog(existing);
}
}
HashSet modifiedElements= new HashSet();
askForAddingExclusionPatternsDialog(elementsToAdd, modifiedElements);
fFoldersList.addElements(elementsToAdd);
fFoldersList.postSetSelection(new StructuredSelection(elementsToAdd));
if (!modifiedElements.isEmpty()) {
for (Iterator iter= modifiedElements.iterator(); iter.hasNext();) {
Object elem= iter.next();
fFoldersList.refresh(elem);
fFoldersList.expandElement(elem, 3);
}
}
}
} else if (index == IDX_EDIT) {
editEntry();
} else if (index == IDX_REMOVE) {
removeEntry();
}
}
}
private void editEntry() {
List selElements= fFoldersList.getSelectedElements();
if (selElements.size() != 1) {
return;
}
Object elem= selElements.get(0);
if (fFoldersList.getIndexOfElement(elem) != -1) {
editElementEntry((CPListElement) elem);
} else if (elem instanceof CPListElementAttribute) {
editAttributeEntry((CPListElementAttribute) elem);
}
}
private void editElementEntry(CPListElement elem) {
CPListElement res= null;
IResource resource= elem.getResource();
if (resource.exists()) {
CPListElement[] arr= openSourceContainerDialog(elem);
if (arr != null) {
res= arr[0];
}
} else {
res= openNewSourceContainerDialog(elem);
}
if (res != null) {
fFoldersList.replaceElement(elem, res);
}
}
private void editAttributeEntry(CPListElementAttribute elem) {
String key= elem.getKey();
if (key.equals(CPListElement.OUTPUT)) {
CPListElement selElement= elem.getParent();
OutputLocationDialog dialog= new OutputLocationDialog(getShell(), selElement);
if (dialog.open() == Window.OK) {
selElement.setAttribute(CPListElement.OUTPUT, dialog.getOutputLocation());
fFoldersList.refresh();
fClassPathList.dialogFieldChanged(); // validate
}
} else if (key.equals(CPListElement.EXCLUSION)) {
CPListElement selElement= elem.getParent();
ExclusionPatternDialog dialog= new ExclusionPatternDialog(getShell(), selElement);
if (dialog.open() == Window.OK) {
selElement.setAttribute(CPListElement.EXCLUSION, dialog.getExclusionPattern());
fFoldersList.refresh();
fClassPathList.dialogFieldChanged(); // validate
}
}
}
protected void sourcePageSelectionChanged(DialogField field) {
List selected= fFoldersList.getSelectedElements();
fFoldersList.enableButton(IDX_EDIT, canEdit(selected));
fFoldersList.enableButton(IDX_REMOVE, canRemove(selected));
}
private void removeEntry() {
List selElements= fFoldersList.getSelectedElements();
for (int i= selElements.size() - 1; i >= 0 ; i--) {
Object elem= selElements.get(i);
if (elem instanceof CPListElementAttribute) {
CPListElementAttribute attrib= (CPListElementAttribute) elem;
String key= attrib.getKey();
Object value= key.equals(CPListElement.EXCLUSION) ? new Path[0] : null;
attrib.getParent().setAttribute(key, value);
selElements.remove(i);
}
}
if (selElements.isEmpty()) {
fFoldersList.refresh();
fClassPathList.dialogFieldChanged(); // validate
} else {
fFoldersList.removeElements(selElements);
}
}
private boolean canRemove(List selElements) {
if (selElements.size() == 0) {
return false;
}
for (int i= 0; i < selElements.size(); i++) {
Object elem= selElements.get(i);
if (elem instanceof CPListElementAttribute) {
CPListElementAttribute attrib= (CPListElementAttribute) elem;
if (attrib.getKey().equals(CPListElement.EXCLUSION)) {
if (((IPath[]) attrib.getValue()).length == 0) {
return false;
}
} else if (attrib.getValue() == null) {
return false;
}
} else if (elem instanceof CPListElement) {
CPListElement curr= (CPListElement) elem;
if (curr.getParentContainer() != null) {
return false;
}
}
}
return true;
}
private boolean canEdit(List selElements) {
if (selElements.size() != 1) {
return false;
}
Object elem= selElements.get(0);
if (fFoldersList.getIndexOfElement(elem) != -1) {
return true;
}
if (elem instanceof CPListElementAttribute) {
return true;
}
return false;
}
private void sourcePageDialogFieldChanged(DialogField field) {
if (fCurrJProject == null) {
// not initialized
return;
}
if (field == fUseFolderOutputs) {
if (!fUseFolderOutputs.isSelected()) {
int nFolders= fFoldersList.getSize();
for (int i= 0; i < nFolders; i++) {
CPListElement cpe= (CPListElement) fFoldersList.getElement(i);
cpe.setAttribute(CPListElement.OUTPUT, null);
}
}
fFoldersList.refresh();
} else if (field == fFoldersList) {
updateClasspathList();
}
}
private void updateClasspathList() {
List cpelements= fClassPathList.getElements();
List srcelements= fFoldersList.getElements();
boolean changeDone= false;
CPListElement lastSourceFolder= null;
// backwards, as entries will be deleted
for (int i= cpelements.size() - 1; i >= 0 ; i--) {
CPListElement cpe= (CPListElement)cpelements.get(i);
if (isEntryKind(cpe.getEntryKind())) {
// if it is a source folder, but not one of the accepted entries, remove it
// at the same time, for the entries seen, remove them from the accepted list
if (!srcelements.remove(cpe)) {
cpelements.remove(i);
changeDone= true;
} else if (lastSourceFolder == null) {
lastSourceFolder= cpe;
}
}
}
if (!srcelements.isEmpty()) {
int insertIndex= (lastSourceFolder == null) ? 0 : cpelements.indexOf(lastSourceFolder) + 1;
cpelements.addAll(insertIndex, srcelements);
changeDone= true;
}
if (changeDone) {
fClassPathList.setElements(cpelements);
}
}
private CPListElement openNewSourceContainerDialog(CPListElement existing) {
String title= (existing == null) ? NewWizardMessages.getString("SourceContainerWorkbookPage.NewSourceFolderDialog.new.title") : NewWizardMessages.getString("SourceContainerWorkbookPage.NewSourceFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
IProject proj= fCurrJProject.getProject();
NewSourceFolderDialog dialog= new NewSourceFolderDialog(getShell(), title, proj, getExistingContainers(existing), existing);
dialog.setMessage(NewWizardMessages.getFormattedString("SourceContainerWorkbookPage.NewSourceFolderDialog.description", fProjPath.toString())); //$NON-NLS-1$
if (dialog.open() == Window.OK) {
IResource folder= dialog.getSourceFolder();
return newCPSourceElement(folder);
}
return null;
}
/**
* Asks to change the output folder to 'proj/bin' when no source folders were existing
*/
private void askForChangingBuildPathDialog(CPListElement existing) {
IPath outputFolder= new Path(fOutputLocationField.getText());
IPath newOutputFolder= null;
String message;
if (outputFolder.segmentCount() == 1) {
String outputFolderName= PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME);
newOutputFolder= outputFolder.append(outputFolderName);
message= NewWizardMessages.getFormattedString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.project_and_output.message", newOutputFolder); //$NON-NLS-1$
} else {
message= NewWizardMessages.getString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.project.message"); //$NON-NLS-1$
}
String title= NewWizardMessages.getString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.title"); //$NON-NLS-1$
if (MessageDialog.openQuestion(getShell(), title, message)) {
fFoldersList.removeElement(existing);
if (newOutputFolder != null) {
fOutputLocationField.setText(newOutputFolder.toString());
}
}
}
private void askForAddingExclusionPatternsDialog(List newEntries, Set modifiedEntries) {
for (int i= 0; i < newEntries.size(); i++) {
CPListElement curr= (CPListElement) newEntries.get(i);
addExclusionPatterns(curr, modifiedEntries);
}
if (!modifiedEntries.isEmpty()) {
String title= NewWizardMessages.getString("SourceContainerWorkbookPage.exclusion_added.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("SourceContainerWorkbookPage.exclusion_added.message"); //$NON-NLS-1$
MessageDialog.openInformation(getShell(), title, message);
}
}
private void addExclusionPatterns(CPListElement newEntry, Set modifiedEntries) {
IPath entryPath= newEntry.getPath();
List existing= fFoldersList.getElements();
for (int i= 0; i < existing.size(); i++) {
CPListElement curr= (CPListElement) existing.get(i);
IPath currPath= curr.getPath();
if (currPath.isPrefixOf(entryPath)) {
IPath[] exclusionFilters= (IPath[]) curr.getAttribute(CPListElement.EXCLUSION);
if (!JavaModelUtil.isExcludedPath(entryPath, exclusionFilters)) {
IPath pathToExclude= entryPath.removeFirstSegments(currPath.segmentCount()).addTrailingSeparator();
IPath[] newExclusionFilters= new IPath[exclusionFilters.length + 1];
System.arraycopy(exclusionFilters, 0, newExclusionFilters, 0, exclusionFilters.length);
newExclusionFilters[exclusionFilters.length]= pathToExclude;
curr.setAttribute(CPListElement.EXCLUSION, newExclusionFilters);
modifiedEntries.add(curr);
}
}
}
}
private CPListElement[] openSourceContainerDialog(CPListElement existing) {
Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class };
TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, existing == null, getExistingContainers(null));
IProject[] allProjects= fWorkspaceRoot.getProjects();
ArrayList rejectedElements= new ArrayList(allProjects.length);
IProject currProject= fCurrJProject.getProject();
for (int i= 0; i < allProjects.length; i++) {
if (!allProjects[i].equals(currProject)) {
rejectedElements.add(allProjects[i]);
}
}
ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray());
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
String title= (existing == null) ? NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.new.title") : NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
String message= (existing == null) ? NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.new.description") : NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.edit.description"); //$NON-NLS-1$ //$NON-NLS-2$
FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp);
dialog.setValidator(validator);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.addFilter(filter);
dialog.setInput(fCurrJProject.getProject().getParent());
dialog.setSorter(new ResourceSorter(ResourceSorter.NAME));
if (existing == null) {
dialog.setInitialSelection(fCurrJProject.getProject());
} else {
dialog.setInitialSelection(existing.getResource());
}
if (dialog.open() == Window.OK) {
Object[] elements= dialog.getResult();
CPListElement[] res= new CPListElement[elements.length];
for (int i= 0; i < res.length; i++) {
IResource elem= (IResource)elements[i];
res[i]= newCPSourceElement(elem);
}
return res;
}
return null;
}
private List getExistingContainers(CPListElement existing) {
List res= new ArrayList();
List cplist= fFoldersList.getElements();
for (int i= 0; i < cplist.size(); i++) {
CPListElement elem= (CPListElement)cplist.get(i);
if (elem != existing) {
IResource resource= elem.getResource();
if (resource instanceof IContainer) { // defensive code
res.add(resource);
}
}
}
return res;
}
private CPListElement newCPSourceElement(IResource res) {
Assert.isNotNull(res);
return new CPListElement(fCurrJProject, IClasspathEntry.CPE_SOURCE, res.getFullPath(), res);
}
/*
* @see BuildPathBasePage#getSelection
*/
public List getSelection() {
return fFoldersList.getSelectedElements();
}
/*
* @see BuildPathBasePage#setSelection
*/
public void setSelection(List selElements) {
fFoldersList.selectElements(new StructuredSelection(selElements));
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathBasePage#isEntryKind(int)
*/
public boolean isEntryKind(int kind) {
return kind == IClasspathEntry.CPE_SOURCE;
}
}
|
35,762 |
Bug 35762 JUnit View wasting a lot of screen space [JUnit]
| null |
resolved fixed
|
2bfc8d4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-30T23:37:13Z | 2003-03-27T15:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/CounterPanel.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.junit.ui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
* A panel with counters for the number of Runs, Errors and Failures.
*/
public class CounterPanel extends Composite {
private Text fNumberOfErrors;
private Text fNumberOfFailures;
private Text fNumberOfRuns;
private int fTotal;
private final Image fErrorIcon= TestRunnerViewPart.createImage("ovr16/error_ovr.gif"); //$NON-NLS-1$
private final Image fFailureIcon= TestRunnerViewPart.createImage("ovr16/failed_ovr.gif"); //$NON-NLS-1$
public CounterPanel(Composite parent) {
super(parent, SWT.WRAP);
GridLayout gridLayout= new GridLayout();
gridLayout.numColumns= 9;
gridLayout.makeColumnsEqualWidth= false;
gridLayout.marginWidth= 0;
setLayout(gridLayout);
fNumberOfRuns= createLabel(JUnitMessages.getString("CounterPanel.label.runs"), null, " 0/0 "); //$NON-NLS-1$ //$NON-NLS-2$
fNumberOfErrors= createLabel(JUnitMessages.getString("CounterPanel.label.errors"), fErrorIcon, " 0 "); //$NON-NLS-1$ //$NON-NLS-2$
fNumberOfFailures= createLabel(JUnitMessages.getString("CounterPanel.label.failures"), fFailureIcon, " 0 "); //$NON-NLS-1$ //$NON-NLS-2$
addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
disposeIcons();
}
});
}
private void disposeIcons() {
fErrorIcon.dispose();
fFailureIcon.dispose();
}
private Text createLabel(String name, Image image, String init) {
Label label= new Label(this, SWT.NONE);
if (image != null) {
image.setBackground(label.getBackground());
label.setImage(image);
}
label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
label= new Label(this, SWT.NONE);
label.setText(name);
label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
Text value= new Text(this, SWT.READ_ONLY);
value.setText(init);
// bug: 39661 Junit test counters do not repaint correctly [JUnit]
value.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
value.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_BEGINNING));
return value;
}
public void reset() {
setErrorValue(0);
setFailureValue(0);
setRunValue(0);
fTotal= 0;
}
public void setTotal(int value) {
fTotal= value;
}
public int getTotal(){
return fTotal;
}
public void setRunValue(int value) {
String runString= JUnitMessages.getFormattedString("CounterPanel.runcount", new String[] { Integer.toString(value), Integer.toString(fTotal) }); //$NON-NLS-1$
fNumberOfRuns.setText(runString);
fNumberOfRuns.redraw();
redraw();
}
public void setErrorValue(int value) {
fNumberOfErrors.setText(Integer.toString(value));
redraw();
}
public void setFailureValue(int value) {
fNumberOfFailures.setText(Integer.toString(value));
redraw();
}
}
|
35,762 |
Bug 35762 JUnit View wasting a lot of screen space [JUnit]
| null |
resolved fixed
|
2bfc8d4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-30T23:37:13Z | 2003-03-27T15:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/IJUnitHelpContextIds.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.junit.ui;
/**
* Help context ids for the JUnit UI.
*/
public interface IJUnitHelpContextIds {
public static final String PREFIX= JUnitPlugin.PLUGIN_ID + '.';
// Actions
public static final String COPYTRACE_ACTION= PREFIX + "copy_trace_action_context"; //$NON-NLS-1$
public static final String COPYFAILURELIST_ACTION= PREFIX + "copy_failure_list_action_context"; //$NON-NLS-1$
public static final String ENABLEFILTER_ACTION= PREFIX + "enable_filter_action_context"; //$NON-NLS-1$
public static final String OPENEDITORATLINE_ACTION= PREFIX + "open_editor_atline_action_context"; //$NON-NLS-1$
public static final String OPENTEST_ACTION= PREFIX + "open_test_action_context"; //$NON-NLS-1$
public static final String RERUN_ACTION= PREFIX + "rerun_test_action_context"; //$NON-NLS-1$
public static final String GOTO_REFERENCED_TEST_ACTION_CONTEXT= PREFIX + "goto_referenced_test_action_context"; //$NON-NLS-1$
public static final String OUTPUT_SCROLL_LOCK_ACTION= PREFIX + "scroll_lock"; //$NON-NLS-1$
// view parts
public static final String RESULTS_VIEW= PREFIX + "results_view_context"; //$NON-NLS-1$
// Preference/Property pages
public static final String JUNIT_PREFERENCE_PAGE= PREFIX + "junit_preference_page_context"; //$NON-NLS-1$
// Wizard pages
public static final String NEW_TESTCASE_WIZARD_PAGE= PREFIX + "new_testcase_wizard_page_context"; //$NON-NLS-1$
public static final String NEW_TESTCASE_WIZARD_PAGE2= PREFIX + "new_testcase_wizard_page2_context"; //$NON-NLS-1$
public static final String NEW_TESTSUITE_WIZARD_PAGE= PREFIX + "new_testsuite_wizard_page2_context"; //$NON-NLS-1$
// Dialogs
public static final String TEST_SELECTION_DIALOG= PREFIX + "test_selection_context"; //$NON-NLS-1$
}
|
35,762 |
Bug 35762 JUnit View wasting a lot of screen space [JUnit]
| null |
resolved fixed
|
2bfc8d4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-30T23:37:13Z | 2003-03-27T15:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestRunnerViewPart.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
* Julien Ruaux: [email protected] see bug 25324 Ability to know when tests are finished [junit]
* Vincent Massol: [email protected] 25324 Ability to know when tests are finished [junit]
******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import java.net.MalformedURLException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.junit.launcher.JUnitBaseLaunchConfiguration;
import org.eclipse.jdt.junit.ITestRunListener;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.ViewPart;
/**
* A ViewPart that shows the results of a test run.
*/
public class TestRunnerViewPart extends ViewPart implements ITestRunListener3, IPropertyChangeListener {
public static final String NAME= "org.eclipse.jdt.junit.ResultView"; //$NON-NLS-1$
/**
* Number of executed tests during a test run
*/
protected int fExecutedTests;
/**
* Number of errors during this test run
*/
protected int fErrorCount;
/**
* Number of failures during this test run
*/
protected int fFailureCount;
/**
* Number of tests run
*/
private int fTestCount;
/**
* Whether the output scrolls and reveals tests as they are executed.
*/
private boolean fAutoScroll = true;
/**
* Map storing TestInfos for each executed test keyed by
* the test name.
*/
private Map fTestInfos= new HashMap();
/**
* The first failure of a test run. Used to reveal the
* first failed tests at the end of a run.
*/
private List fFailures= new ArrayList();
private JUnitProgressBar fProgressBar;
private ProgressImages fProgressImages;
private Image fViewImage;
private CounterPanel fCounterPanel;
private boolean fShowOnErrorOnly= false;
private Clipboard fClipboard;
/**
* The view that shows the stack trace of a failure
*/
private FailureTraceView fFailureView;
/**
* The collection of ITestRunViews
*/
private Vector fTestRunViews = new Vector();
/**
* The currently active run view
*/
private ITestRunView fActiveRunView;
/**
* Is the UI disposed
*/
private boolean fIsDisposed= false;
/**
* The launched project
*/
private IJavaProject fTestProject;
/**
* The launcher that has started the test
*/
private String fLaunchMode;
private ILaunch fLastLaunch;
/**
* Actions
*/
private Action fRerunLastTestAction;
private ScrollLockAction fScrollLockAction;
/**
* The client side of the remote test runner
*/
private RemoteTestRunnerClient fTestRunnerClient;
final Image fStackViewIcon= TestRunnerViewPart.createImage("cview16/stackframe.gif");//$NON-NLS-1$
final Image fTestRunOKIcon= TestRunnerViewPart.createImage("cview16/junitsucc.gif"); //$NON-NLS-1$
final Image fTestRunFailIcon= TestRunnerViewPart.createImage("cview16/juniterr.gif"); //$NON-NLS-1$
final Image fTestRunOKDirtyIcon= TestRunnerViewPart.createImage("cview16/junitsuccq.gif"); //$NON-NLS-1$
final Image fTestRunFailDirtyIcon= TestRunnerViewPart.createImage("cview16/juniterrq.gif"); //$NON-NLS-1$
// Persistance tags.
static final String TAG_PAGE= "page"; //$NON-NLS-1$
static final String TAG_RATIO= "ratio"; //$NON-NLS-1$
static final String TAG_TRACEFILTER= "tracefilter"; //$NON-NLS-1$
private IMemento fMemento;
Image fOriginalViewImage;
IElementChangedListener fDirtyListener;
private CTabFolder fTabFolder;
private SashForm fSashForm;
private Action fNextAction;
private Action fPreviousAction;
private class StopAction extends Action {
public StopAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.stopaction.text"));//$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.stopaction.tooltip"));//$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/stop.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/stop.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/stop.gif")); //$NON-NLS-1$
}
public void run() {
stopTest();
}
}
private class RerunLastAction extends Action {
public RerunLastAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.label")); //$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.tooltip")); //$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/relaunch.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/relaunch.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/relaunch.gif")); //$NON-NLS-1$
}
public void run(){
rerunTestRun();
}
}
/**
* Listen for for modifications to Java elements
*/
private class DirtyListener implements IElementChangedListener {
public void elementChanged(ElementChangedEvent event) {
processDelta(event.getDelta());
}
private boolean processDelta(IJavaElementDelta delta) {
int kind= delta.getKind();
int details= delta.getFlags();
int type= delta.getElement().getElementType();
switch (type) {
// Consider containers for class files.
case IJavaElement.JAVA_MODEL:
case IJavaElement.JAVA_PROJECT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
case IJavaElement.PACKAGE_FRAGMENT:
// If we did some different than changing a child we flush the the undo / redo stack.
if (kind != IJavaElementDelta.CHANGED || details != IJavaElementDelta.F_CHILDREN) {
codeHasChanged();
return false;
}
break;
case IJavaElement.COMPILATION_UNIT:
ICompilationUnit unit= (ICompilationUnit)delta.getElement();
// If we change a working copy we do nothing
if (unit.isWorkingCopy()) {
// Don't examine children of a working copy but keep processing siblings.
return true;
} else {
codeHasChanged();
return false;
}
case IJavaElement.CLASS_FILE:
// Don't examine children of a class file but keep on examining siblings.
return true;
default:
codeHasChanged();
return false;
}
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
if (affectedChildren == null)
return true;
for (int i= 0; i < affectedChildren.length; i++) {
if (!processDelta(affectedChildren[i]))
return false;
}
return true;
}
}
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
private void restoreLayoutState(IMemento memento) {
Integer page= memento.getInteger(TAG_PAGE);
if (page != null) {
int p= page.intValue();
fTabFolder.setSelection(p);
fActiveRunView= (ITestRunView)fTestRunViews.get(p);
}
Integer ratio= memento.getInteger(TAG_RATIO);
if (ratio != null)
fSashForm.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue()} );
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void stopTest() {
if (fTestRunnerClient != null)
fTestRunnerClient.stopTest();
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void rerunTestRun() {
if (fLastLaunch != null && fLastLaunch.getLaunchConfiguration() != null) {
try {
DebugUITools.saveAndBuildBeforeLaunch();
fLastLaunch.getLaunchConfiguration().launch(fLastLaunch.getLaunchMode(), null);
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
}
public void setAutoScroll(boolean scroll) {
fAutoScroll = scroll;
}
public boolean isAutoScroll() {
return fAutoScroll;
}
/*
* @see ITestRunListener#testRunStarted(testCount)
*/
public void testRunStarted(final int testCount){
reset(testCount);
fShowOnErrorOnly= JUnitPreferencePage.getShowOnErrorOnly();
fExecutedTests++;
}
public void selectNextFailure() {
fActiveRunView.selectNext();
}
public void selectPreviousFailure() {
fActiveRunView.selectPrevious();
}
public void showTest(TestRunInfo test) {
fActiveRunView.setSelectedTest(test.getTestId());
handleTestSelected(test.getTestId());
new OpenTestAction(this, test.getClassName(), test.getTestMethodName()).run();
}
public void reset(){
reset(0);
setViewPartTitle(null);
clearStatus();
resetViewIcon();
}
/*
* @see ITestRunListener#testRunEnded
*/
public void testRunEnded(long elapsedTime){
fExecutedTests--;
String[] keys= {elapsedTimeAsString(elapsedTime), String.valueOf(fErrorCount), String.valueOf(fFailureCount)};
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.finish", keys); //$NON-NLS-1$
if (hasErrorsOrFailures())
postError(msg);
else
postInfo(msg);
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
if (fFailures.size() > 0) {
selectFirstFailure();
}
updateViewIcon();
if (fDirtyListener == null) {
fDirtyListener= new DirtyListener();
JavaCore.addElementChangedListener(fDirtyListener);
}
}
});
}
protected void selectFirstFailure() {
TestRunInfo firstFailure= (TestRunInfo)fFailures.get(0);
if (firstFailure != null && fAutoScroll) {
fActiveRunView.setSelectedTest(firstFailure.getTestId());
handleTestSelected(firstFailure.getTestId());
}
}
private void updateViewIcon() {
if (hasErrorsOrFailures())
fViewImage= fTestRunFailIcon;
else
fViewImage= fTestRunOKIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
private boolean hasErrorsOrFailures() {
return fErrorCount+fFailureCount > 0;
}
private String elapsedTimeAsString(long runTime) {
return NumberFormat.getInstance().format((double)runTime/1000);
}
/*
* @see ITestRunListener#testRunStopped
*/
public void testRunStopped(final long elapsedTime) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.stopped", elapsedTimeAsString(elapsedTime)); //$NON-NLS-1$
postInfo(msg);
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
resetViewIcon();
}
});
}
private void resetViewIcon() {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
/*
* @see ITestRunListener#testRunTerminated
*/
public void testRunTerminated() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.terminated"); //$NON-NLS-1$
showMessage(msg);
}
private void showMessage(String msg) {
showInformation(msg);
postError(msg);
}
/*
* @see ITestRunListener#testStarted
*/
public void testStarted(String testId, String testName) {
postStartTest(testId, testName);
// reveal the part when the first test starts
if (!fShowOnErrorOnly && fExecutedTests == 1)
postShowTestResultsView();
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
testInfo= new TestRunInfo(testId, testName);
fTestInfos.put(testId, testInfo);
}
String className= testInfo.getClassName();
String method= testInfo.getTestMethodName();
String status= JUnitMessages.getFormattedString("TestRunnerViewPart.message.started", new String[] { className, method }); //$NON-NLS-1$
postInfo(status);
}
/*
* @see ITestRunListener#testEnded
*/
public void testEnded(String testId, String testName){
postEndTest(testId, testName);
fExecutedTests++;
}
/*
* @see ITestRunListener#testFailed
*/
public void testFailed(int status, String testId, String testName, String trace){
testFailed(status, testId, testName, trace, null, null);
}
/*
* @see ITestRunListener#testFailed
*/
public void testFailed(int status, String testId, String testName, String trace, String expected, String actual){
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
testInfo= new TestRunInfo(testId, testName);
fTestInfos.put(testName, testInfo);
}
testInfo.setTrace(trace);
testInfo.setStatus(status);
if (expected != null)
testInfo.setExpected(expected.substring(0, expected.length()-1));
if (actual != null)
testInfo.setActual(actual.substring(0, actual.length()-1));
if (status == ITestRunListener.STATUS_ERROR)
fErrorCount++;
else
fFailureCount++;
fFailures.add(testInfo);
// show the view on the first error only
if (fShowOnErrorOnly && (fErrorCount + fFailureCount == 1))
postShowTestResultsView();
}
/*
* @see ITestRunListener#testReran
*/
public void testReran(String testId, String className, String testName, int status, String trace) {
if (status == ITestRunListener.STATUS_ERROR) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.error", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else if (status == ITestRunListener.STATUS_FAILURE) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.failure", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.success", new String[]{testName, className}); //$NON-NLS-1$
postInfo(msg);
}
TestRunInfo info= getTestInfo(testId);
updateTest(info, status);
if (info.getTrace() == null || !info.getTrace().equals(trace)) {
info.setTrace(trace);
showFailure(info);
}
}
private void updateTest(TestRunInfo info, final int status) {
if (status == info.getStatus())
return;
if (info.getStatus() == ITestRunListener.STATUS_OK) {
if (status == ITestRunListener.STATUS_FAILURE)
fFailureCount++;
else if (status == ITestRunListener.STATUS_ERROR)
fErrorCount++;
} else if (info.getStatus() == ITestRunListener.STATUS_ERROR) {
if (status == ITestRunListener.STATUS_OK)
fErrorCount--;
else if (status == ITestRunListener.STATUS_FAILURE) {
fErrorCount--;
fFailureCount++;
}
} else if (info.getStatus() == ITestRunListener.STATUS_FAILURE) {
if (status == ITestRunListener.STATUS_OK)
fFailureCount--;
else if (status == ITestRunListener.STATUS_ERROR) {
fFailureCount--;
fErrorCount++;
}
}
info.setStatus(status);
final TestRunInfo finalInfo= info;
postSyncRunnable(new Runnable() {
public void run() {
refreshCounters();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.testStatusChanged(finalInfo);
}
}
});
}
/*
* @see ITestRunListener#testTreeEntry
*/
public void testTreeEntry(final String treeEntry){
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.newTreeEntry(treeEntry);
}
}
});
}
public void startTestRunListening(IJavaElement type, int port, ILaunch launch) {
fTestProject= type.getJavaProject();
fLaunchMode= launch.getLaunchMode();
aboutToLaunch();
if (fTestRunnerClient != null) {
stopTest();
}
fTestRunnerClient= new RemoteTestRunnerClient();
// add the TestRunnerViewPart to the list of registered listeners
List listeners= JUnitPlugin.getDefault().getTestRunListeners();
ITestRunListener[] listenerArray= new ITestRunListener[listeners.size()+1];
listeners.toArray(listenerArray);
System.arraycopy(listenerArray, 0, listenerArray, 1, listenerArray.length-1);
listenerArray[0]= this;
fTestRunnerClient.startListening(listenerArray, port);
fLastLaunch= launch;
setViewPartTitle(type);
if (type instanceof IType)
setTitleToolTip(((IType)type).getFullyQualifiedName());
else
setTitleToolTip(type.getElementName());
}
private void setViewPartTitle(IJavaElement type) {
String title;
if (type == null)
title= JUnitMessages.getString("TestRunnerViewPart.title_no_type"); //$NON-NLS-1$
else
title= JUnitMessages.getFormattedString("TestRunnerViewPart.title", type.getElementName()); //$NON-NLS-1$
setTitle(title);
}
private void aboutToLaunch() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.launching"); //$NON-NLS-1$
showInformation(msg);
postInfo(msg);
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
public synchronized void dispose(){
fIsDisposed= true;
stopTest();
if (fProgressImages != null)
fProgressImages.dispose();
JUnitPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
fTestRunOKIcon.dispose();
fTestRunFailIcon.dispose();
fStackViewIcon.dispose();
fTestRunOKDirtyIcon.dispose();
fTestRunFailDirtyIcon.dispose();
if (fClipboard != null)
fClipboard.dispose();
}
private void start(final int total) {
resetProgressBar(total);
fCounterPanel.setTotal(total);
fCounterPanel.setRunValue(0);
}
private void resetProgressBar(final int total) {
fProgressBar.reset();
fProgressBar.setMaximum(total);
}
private void postSyncRunnable(Runnable r) {
if (!isDisposed())
getDisplay().syncExec(r);
}
private void aboutToStart() {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed()) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.aboutToStart();
}
fNextAction.setEnabled(false);
fPreviousAction.setEnabled(false);
}
}
});
}
private void postEndTest(final String testId, final String testName) {
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
handleEndTest();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.endTest(testId);
}
if (fFailureCount + fErrorCount > 0) {
fNextAction.setEnabled(true);
fPreviousAction.setEnabled(true);
}
}
});
}
private void postStartTest(final String testId, final String testName) {
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.startTest(testId);
}
}
});
}
private void handleEndTest() {
refreshCounters();
fProgressBar.step(fFailureCount+fErrorCount);
if (fShowOnErrorOnly) {
Image progress= fProgressImages.getImage(fExecutedTests, fTestCount, fErrorCount, fFailureCount);
if (progress != fViewImage) {
fViewImage= progress;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
private void refreshCounters() {
fCounterPanel.setErrorValue(fErrorCount);
fCounterPanel.setFailureValue(fFailureCount);
fCounterPanel.setRunValue(fExecutedTests);
fProgressBar.refresh(fErrorCount+fFailureCount> 0);
}
protected void postShowTestResultsView() {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
showTestResultsView();
}
});
}
public void showTestResultsView() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IWorkbenchPage page= window.getActivePage();
TestRunnerViewPart testRunner= null;
if (page != null) {
try { // show the result view
testRunner= (TestRunnerViewPart)page.findView(TestRunnerViewPart.NAME);
if(testRunner == null) {
IWorkbenchPart activePart= page.getActivePart();
testRunner= (TestRunnerViewPart)page.showView(TestRunnerViewPart.NAME);
//restore focus stolen by the creation of the console
page.activate(activePart);
} else {
page.bringToTop(testRunner);
}
} catch (PartInitException pie) {
JUnitPlugin.log(pie);
}
}
}
protected void postInfo(final String message) {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setErrorMessage(null);
getStatusLine().setMessage(message);
}
});
}
protected void postError(final String message) {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(message);
}
});
}
protected void showInformation(final String info){
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.setInformation(info);
}
});
}
private CTabFolder createTestRunViews(Composite parent) {
CTabFolder tabFolder= new CTabFolder(parent, SWT.TOP);
tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_VERTICAL));
ITestRunView failureRunView= new FailureRunView(tabFolder, fClipboard, this);
ITestRunView testHierarchyRunView= new HierarchyRunView(tabFolder, this);
fTestRunViews.addElement(failureRunView);
fTestRunViews.addElement(testHierarchyRunView);
tabFolder.setSelection(0);
fActiveRunView= (ITestRunView)fTestRunViews.firstElement();
tabFolder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
testViewChanged(event);
}
});
return tabFolder;
}
private void testViewChanged(SelectionEvent event) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
if (((CTabFolder) event.widget).getSelection().getText() == v.getName()){
v.setSelectedTest(fActiveRunView.getSelectedTestId());
fActiveRunView= v;
fActiveRunView.activate();
}
}
}
private SashForm createSashForm(Composite parent) {
fSashForm= new SashForm(parent, SWT.VERTICAL);
ViewForm top= new ViewForm(fSashForm, SWT.NONE);
fTabFolder= createTestRunViews(top);
fTabFolder.setLayoutData(new TabFolderLayout());
top.setContent(fTabFolder);
ViewForm bottom= new ViewForm(fSashForm, SWT.NONE);
CLabel label= new CLabel(bottom, SWT.NONE);
label.setText(JUnitMessages.getString("TestRunnerViewPart.label.failure")); //$NON-NLS-1$
label.setImage(fStackViewIcon);
bottom.setTopLeft(label);
ToolBar failureToolBar= new ToolBar(bottom, SWT.FLAT | SWT.WRAP);
bottom.setTopCenter(failureToolBar);
fFailureView= new FailureTraceView(bottom, fClipboard, this, failureToolBar);
bottom.setContent(fFailureView.getComposite());
fSashForm.setWeights(new int[]{50, 50});
return fSashForm;
}
private void reset(final int testCount) {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
fCounterPanel.reset();
fFailureView.clear();
fProgressBar.reset();
clearStatus();
start(testCount);
}
});
fExecutedTests= 0;
fFailureCount= 0;
fErrorCount= 0;
fTestCount= testCount;
aboutToStart();
fTestInfos.clear();
fFailures= new ArrayList();
}
private void clearStatus() {
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(null);
}
public void setFocus() {
if (fActiveRunView != null)
fActiveRunView.setFocus();
}
public void createPartControl(Composite parent) {
fClipboard= new Clipboard(parent.getDisplay());
GridLayout gridLayout= new GridLayout();
gridLayout.marginWidth= 0;
gridLayout.marginHeight= 0;
parent.setLayout(gridLayout);
configureToolBar();
Composite counterPanel= createProgressCountPanel(parent);
counterPanel.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
SashForm sashForm= createSashForm(parent);
sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
IActionBars actionBars= getViewSite().getActionBars();
actionBars.setGlobalActionHandler(
ActionFactory.COPY.getId(),
new CopyTraceAction(fFailureView, fClipboard));
JUnitPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
fOriginalViewImage= getTitleImage();
fProgressImages= new ProgressImages();
WorkbenchHelp.setHelp(parent, IJUnitHelpContextIds.RESULTS_VIEW);
if (fMemento != null)
restoreLayoutState(fMemento);
fMemento= null;
}
public void saveState(IMemento memento) {
if (fSashForm == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
int activePage= fTabFolder.getSelectionIndex();
memento.putInteger(TAG_PAGE, activePage);
int weigths[]= fSashForm.getWeights();
int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]);
memento.putInteger(TAG_RATIO, ratio);
}
private void configureToolBar() {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager toolBar= actionBars.getToolBarManager();
fRerunLastTestAction= new RerunLastAction();
fScrollLockAction= new ScrollLockAction(this);
fNextAction= new ShowNextFailureAction(this);
fPreviousAction= new ShowPreviousFailureAction(this);
fNextAction.setEnabled(false);
fPreviousAction.setEnabled(false);
actionBars.setGlobalActionHandler(ActionFactory.NEXT.getId(), fNextAction);
actionBars.setGlobalActionHandler(ActionFactory.PREVIOUS.getId(), fPreviousAction);
toolBar.add(fNextAction);
toolBar.add(fPreviousAction);
toolBar.add(new StopAction());
toolBar.add(new Separator());
toolBar.add(fRerunLastTestAction);
toolBar.add(fScrollLockAction);
fScrollLockAction.setChecked(!fAutoScroll);
actionBars.updateActionBars();
}
private IStatusLineManager getStatusLine() {
// we want to show messages globally hence we
// have to go throgh the active part
IViewSite site= getViewSite();
IWorkbenchPage page= site.getPage();
IWorkbenchPart activePart= page.getActivePart();
if (activePart instanceof IViewPart) {
IViewPart activeViewPart= (IViewPart)activePart;
IViewSite activeViewSite= activeViewPart.getViewSite();
return activeViewSite.getActionBars().getStatusLineManager();
}
if (activePart instanceof IEditorPart) {
IEditorPart activeEditorPart= (IEditorPart)activePart;
IEditorActionBarContributor contributor= activeEditorPart.getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor)
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
// no active part
return getViewSite().getActionBars().getStatusLineManager();
}
private Composite createProgressCountPanel(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout());
fProgressBar = new JUnitProgressBar(composite);
fProgressBar.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
fCounterPanel = new CounterPanel(composite);
fCounterPanel.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
return composite;
}
public TestRunInfo getTestInfo(String testId) {
if (testId == null)
return null;
return (TestRunInfo) fTestInfos.get(testId);
}
public void handleTestSelected(String testId) {
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
showFailure(null); //$NON-NLS-1$
} else {
showFailure(testInfo);
}
}
private void showFailure(final TestRunInfo failure) {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.showFailure(failure);
}
});
}
public IJavaProject getLaunchedProject() {
return fTestProject;
}
public ILaunch getLastLaunch() {
return fLastLaunch;
}
protected static Image createImage(String path) {
try {
ImageDescriptor id= ImageDescriptor.createFromURL(JUnitPlugin.makeIconFileURL(path));
return id.createImage();
} catch (MalformedURLException e) {
// fall through
}
return null;
}
private boolean isDisposed() {
return fIsDisposed || fCounterPanel.isDisposed();
}
private Display getDisplay() {
return getViewSite().getShell().getDisplay();
}
/**
* @see IWorkbenchPart#getTitleImage()
*/
public Image getTitleImage() {
if (fOriginalViewImage == null)
fOriginalViewImage= super.getTitleImage();
if (fViewImage == null)
return super.getTitleImage();
return fViewImage;
}
public void propertyChange(PropertyChangeEvent event) {
if (isDisposed())
return;
if (IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY.equals(event.getProperty())) {
if (!JUnitPreferencePage.getShowOnErrorOnly()) {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
void codeHasChanged() {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
if (fDirtyListener != null) {
JavaCore.removeElementChangedListener(fDirtyListener);
fDirtyListener= null;
}
if (fViewImage == fTestRunOKIcon)
fViewImage= fTestRunOKDirtyIcon;
else if (fViewImage == fTestRunFailIcon)
fViewImage= fTestRunFailDirtyIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
});
}
boolean isCreated() {
return fCounterPanel != null;
}
public void rerunTest(String testId, String className, String testName) {
DebugUITools.saveAndBuildBeforeLaunch();
if (fTestRunnerClient != null && fTestRunnerClient.isRunning() && ILaunchManager.DEBUG_MODE.equals(fLaunchMode))
fTestRunnerClient.rerunTest(testId, className, testName);
else if (fLastLaunch != null) {
// run the selected test using the previous launch configuration
ILaunchConfiguration launchConfiguration= fLastLaunch.getLaunchConfiguration();
if (launchConfiguration != null) {
try {
ILaunchConfigurationWorkingCopy tmp= launchConfiguration.copy("Rerun "+testName); //$NON-NLS-1$
tmp.setAttribute(JUnitBaseLaunchConfiguration.TESTNAME_ATTR, testName);
tmp.launch(fLastLaunch.getLaunchMode(), null);
return;
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
MessageDialog.openInformation(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.cannotrerun.title"), //$NON-NLS-1$
JUnitMessages.getString("TestRunnerViewPart.cannotrerurn.message") //$NON-NLS-1$
);
}
}
}
|
45,531 |
Bug 45531 [JUnit] Open failed test failed when test name is "1.3 - test346"
|
Using org.eclipse.jdt.junit version 20031021, I got a failure when I tried to open a failed test that is named "1.3 - test346". This can happen with the compiler tests when they run in 1.3 mode. We add "1.3", "1.4" or "1.5" to distinguish the different compiler compliance mode. I attach a patch for the opening action that fixes the issue.
|
resolved fixed
|
cc8cf61
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-30T23:55:20Z | 2003-10-24T18:26:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/OpenEditorAction.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.junit.ui;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.texteditor.ITextEditor;
/**
* Abstract Action for opening a Java editor.
*/
public abstract class OpenEditorAction extends Action {
protected String fClassName;
protected TestRunnerViewPart fTestRunner;
/**
* Constructor for OpenEditorAction.
*/
protected OpenEditorAction(TestRunnerViewPart testRunner, String testClassName) {
super(JUnitMessages.getString("OpenEditorAction.action.label")); //$NON-NLS-1$
fClassName= testClassName;
fTestRunner= testRunner;
}
/*
* @see IAction#run()
*/
public void run() {
ITextEditor textEditor= null;
try {
IJavaElement element= findElement(getLaunchedProject(), fClassName);
if (element == null) {
MessageDialog.openError(fTestRunner.getSite().getShell(),
JUnitMessages.getString("OpenEditorAction.error.cannotopen.title"), JUnitMessages.getString("OpenEditorAction.error.cannotopen.message")); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
textEditor= (ITextEditor)EditorUtility.openInEditor(element, false);
} catch (CoreException e) {
ErrorDialog.openError(fTestRunner.getSite().getShell(), JUnitMessages.getString("OpenEditorAction.error.dialog.title"), JUnitMessages.getString("OpenEditorAction.error.dialog.message"), e.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
if (textEditor == null) {
fTestRunner.postInfo(JUnitMessages.getString("OpenEditorAction.message.cannotopen")); //$NON-NLS-1$
return;
}
reveal(textEditor);
}
protected IJavaProject getLaunchedProject() {
return fTestRunner.getLaunchedProject();
}
protected String getClassName() {
return fClassName;
}
protected abstract IJavaElement findElement(IJavaProject project, String className) throws JavaModelException;
protected abstract void reveal(ITextEditor editor);
}
|
45,531 |
Bug 45531 [JUnit] Open failed test failed when test name is "1.3 - test346"
|
Using org.eclipse.jdt.junit version 20031021, I got a failure when I tried to open a failed test that is named "1.3 - test346". This can happen with the compiler tests when they run in 1.3 mode. We add "1.3", "1.4" or "1.5" to distinguish the different compiler compliance mode. I attach a patch for the opening action that fixes the issue.
|
resolved fixed
|
cc8cf61
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-30T23:55:20Z | 2003-10-24T18:26:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/OpenEditorAtLineAction.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: [email protected] bug 37333 Failure Trace cannot
* navigate to non-public class in CU throwing Exception
*******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
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.IJavaSearchResultCollector;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.ISearchPattern;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Open a test in the Java editor and reveal a given line
*/
public class OpenEditorAtLineAction extends OpenEditorAction {
//fix for bug 37333
private class NonPublicClassInCUCollector implements IJavaSearchResultCollector {
private IJavaElement fFound;
public void accept(IResource resource, int start, int end, IJavaElement enclosingElement, int accuracy)
throws JavaModelException {
if ((enclosingElement instanceof IType) && (resource.getName().equals(fCUName)))
fFound= enclosingElement;
}
public IProgressMonitor getProgressMonitor() {
return new NullProgressMonitor();
}
public void aboutToStart() {}
public void done() {}
}
private int fLineNumber;
private String fCUName;
/**
* Constructor for OpenEditorAtLineAction.
*/
public OpenEditorAtLineAction(TestRunnerViewPart testRunner, String cuName, String className, int line) {
super(testRunner, className);
WorkbenchHelp.setHelp(this, IJUnitHelpContextIds.OPENEDITORATLINE_ACTION);
fLineNumber= line;
fCUName= cuName;
}
protected void reveal(ITextEditor textEditor) {
if (fLineNumber >= 0) {
try {
IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
textEditor.selectAndReveal(document.getLineOffset(fLineNumber-1), document.getLineLength(fLineNumber-1));
} catch (BadLocationException x) {
// marker refers to invalid text position -> do nothing
}
}
}
protected IJavaElement findElement(IJavaProject project, String className) throws JavaModelException {
IJavaElement element= project.findType(className);
//fix for bug 37333
if (element == null) {
ISearchPattern pattern= SearchEngine.createSearchPattern(className, IJavaSearchConstants.TYPE, IJavaSearchConstants.DECLARATIONS, true);
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { project }, false);
NonPublicClassInCUCollector collector= new NonPublicClassInCUCollector();
SearchEngine searchEngine= new SearchEngine();
searchEngine.search(JavaPlugin.getWorkspace(), pattern, scope, collector);
element= collector.fFound;
}
return element;
}
public boolean isEnabled() {
try {
return getLaunchedProject().findType(getClassName()) != null;
} catch (JavaModelException e) {
}
return false;
}
}
|
45,531 |
Bug 45531 [JUnit] Open failed test failed when test name is "1.3 - test346"
|
Using org.eclipse.jdt.junit version 20031021, I got a failure when I tried to open a failed test that is named "1.3 - test346". This can happen with the compiler tests when they run in 1.3 mode. We add "1.3", "1.4" or "1.5" to distinguish the different compiler compliance mode. I attach a patch for the opening action that fixes the issue.
|
resolved fixed
|
cc8cf61
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-12-30T23:55:20Z | 2003-10-24T18:26:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/OpenTestAction.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.junit.ui;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
/**
* Open a class on a Test method.
*/
public class OpenTestAction extends OpenEditorAction {
private String fMethodName;
private ISourceRange fRange;
/**
* Constructor for OpenTestAction.
*/
public OpenTestAction(TestRunnerViewPart testRunner, String className, String method) {
super(testRunner, className);
WorkbenchHelp.setHelp(this, IJUnitHelpContextIds.OPENTEST_ACTION);
fMethodName= method;
}
public OpenTestAction(TestRunnerViewPart testRunner, String className) {
this(testRunner, className, null);
}
protected IJavaElement findElement(IJavaProject project, String className) throws JavaModelException {
IType type= project.findType(className);
if (type == null)
return null;
if (fMethodName == null)
return type;
IMethod method= findMethod(type);
if (method == null) {
ITypeHierarchy typeHierarchy= type.newSupertypeHierarchy(null);
IType[] types= typeHierarchy.getAllSuperclasses(type);
for (int i= 0; i < types.length; i++) {
method= findMethod(types[i]);
if (method != null)
break;
}
}
if (method != null)
fRange= method.getNameRange();
return method;
}
IMethod findMethod(IType type) throws JavaModelException {
IMethod method= type.getMethod(fMethodName, new String[0]);
if (method != null && method.exists())
return method;
return null;
}
protected void reveal(ITextEditor textEditor) {
if (fRange != null)
textEditor.selectAndReveal(fRange.getOffset(), fRange.getLength());
}
public boolean isEnabled() {
try {
return getLaunchedProject().findType(getClassName()) != null;
} catch (JavaModelException e) {
}
return false;
}
}
|
49,010 |
Bug 49010 Move Static Method Refactoring: Focus problems
|
I20031216 On Mac OS you can open the menu of a combo box with the up or down cursor keys. If you use code assist in the same field and try to use the up and down arrow keys to scroll through the code assist proposals, they don't work as expected because the underlying combo box uses the keys to open its own menu. As a result you get the combo menu on top of the code assist window (see attached screenshot).
|
resolved fixed
|
2a643d0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-05T18:21:04Z | 2003-12-17T14:06:40Z |
org.eclipse.jdt.ui/ui
| |
49,010 |
Bug 49010 Move Static Method Refactoring: Focus problems
|
I20031216 On Mac OS you can open the menu of a combo box with the up or down cursor keys. If you use code assist in the same field and try to use the up and down arrow keys to scroll through the code assist proposals, they don't work as expected because the underlying combo box uses the keys to open its own menu. As a result you get the combo menu on top of the code assist window (see attached screenshot).
|
resolved fixed
|
2a643d0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-05T18:21:04Z | 2003-12-17T14:06:40Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/ComboContentAssistSubjectAdapter.java
| |
49,232 |
Bug 49232 Refactoring: Move static method content assist key binding is CTRL-SPACE [general issue]
|
On OS X the content assist key-binding is OPTION-Space, but in the refactoring you can only use CTRL-SPACE.
|
resolved fixed
|
ea3dbfd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-05T18:21:55Z | 2003-12-20T14:20:00Z |
org.eclipse.jdt.ui/ui
| |
49,232 |
Bug 49232 Refactoring: Move static method content assist key binding is CTRL-SPACE [general issue]
|
On OS X the content assist key-binding is OPTION-Space, but in the refactoring you can only use CTRL-SPACE.
|
resolved fixed
|
ea3dbfd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-05T18:21:55Z | 2003-12-20T14:20:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/MoveMembersWizard.java
| |
46,951 |
Bug 46951 enhancements for "Introduce Factory" [refactoring]
|
I20031119 It would be useful if the new "Introduce Factory" refactory would allow to specify on which class the "createXxx" method is created. The current behavior always creates the method on the least likely class.
|
resolved fixed
|
a246216
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-05T18:41:50Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui/core
| |
46,951 |
Bug 46951 enhancements for "Introduce Factory" [refactoring]
|
I20031119 It would be useful if the new "Introduce Factory" refactory would allow to specify on which class the "createXxx" method is created. The current behavior always creates the method on the least likely class.
|
resolved fixed
|
a246216
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-05T18:41:50Z | 2003-11-19T11:06:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/IntroduceFactoryRefactoring.java
| |
46,951 |
Bug 46951 enhancements for "Introduce Factory" [refactoring]
|
I20031119 It would be useful if the new "Introduce Factory" refactory would allow to specify on which class the "createXxx" method is created. The current behavior always creates the method on the least likely class.
|
resolved fixed
|
a246216
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-05T18:41:50Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui/ui
| |
46,951 |
Bug 46951 enhancements for "Introduce Factory" [refactoring]
|
I20031119 It would be useful if the new "Introduce Factory" refactory would allow to specify on which class the "createXxx" method is created. The current behavior always creates the method on the least likely class.
|
resolved fixed
|
a246216
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-05T18:41:50Z | 2003-11-19T11:06:40Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/IntroduceFactoryInputPage.java
| |
49,230 |
Bug 49230 Editable Table: can have empty rows [refactoring]
| null |
resolved fixed
|
67dfaa6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-05T18:56:48Z | 2003-12-20T14:20:00Z |
org.eclipse.jdt.ui/core
| |
49,230 |
Bug 49230 Editable Table: can have empty rows [refactoring]
| null |
resolved fixed
|
67dfaa6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-05T18:56:48Z | 2003-12-20T14:20:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/ParameterInfo.java
| |
49,002 |
Bug 49002 Move static members: Labels [refactoring]
|
20031217 - The window title says 'Move static member(s)' the brackets look really ugly. Why not just write 'Move static members'? It's the name of the refactoring. Or be precice and write either 'member' or 'members' - When moving a single method that returns something it says 'Destination type for 'IJavaElement create(File)': This looks like my method is in IJavaElement, but that's the return type. -> Put the return type behind the method name (or leave ir away!) like it is done in the outline (use JavaElementLabels to render this) or put the declaring type 'JavaCore.create(IFile)'
|
resolved fixed
|
bd86a78
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-06T08:44:11Z | 2003-12-17T14:06:40Z |
org.eclipse.jdt.ui/ui
| |
49,002 |
Bug 49002 Move static members: Labels [refactoring]
|
20031217 - The window title says 'Move static member(s)' the brackets look really ugly. Why not just write 'Move static members'? It's the name of the refactoring. Or be precice and write either 'member' or 'members' - When moving a single method that returns something it says 'Destination type for 'IJavaElement create(File)': This looks like my method is in IJavaElement, but that's the return type. -> Put the return type behind the method name (or leave ir away!) like it is done in the outline (use JavaElementLabels to render this) or put the declaring type 'JavaCore.create(IFile)'
|
resolved fixed
|
bd86a78
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-06T08:44:11Z | 2003-12-17T14:06:40Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/MoveMembersWizard.java
| |
49,485 |
Bug 49485 Extra carriage return required after auto-completion of brackets
|
When typing in a statement such as for(), when completion is enabled (so that the closing bracket is added automatically), an extra carriage return keystroke is sometimes required. For example, type the following: for( Eclipse adds the closing bracket to complete the statement, and leaves the caret between the two brackets. If you then cursor-right, to place the caret at the end of the statement and press Enter (carriage return), nothing happens. The caret does not move, and no new line is created. If, instead of cursor-right, you type the closing bracket youself (overwriting the one Eclipse added) and press Enter (carriage-return), then a new line is created and the caret moves to it as you would expect. When typing in a hurry, this is a real nuisance! I don't know which Java preferences are relevant to help to reproduce this, but for reference, the Java|Editor|Typing preferences are all checked. Please ask if you need more info. This occurs in Eclipse M6
|
resolved fixed
|
5046357
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-06T10:27:15Z | 2004-01-03T17:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/LinkedUIControl.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.link;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.events.ShellListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.viewers.IPostSelectionProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DefaultPositionUpdater;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IPositionUpdater;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.IRewriteTarget;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.ITextViewerExtension3;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.link.contentassist.ContentAssistant2;
/**
* The UI for linked mode. Detects events that influence behaviour of the
* linked position UI and acts upon them.
*
* @since 3.0
*/
public class LinkedUIControl {
/* cycle constants */
/**
* Constant indicating that this UI should never cycle from the last
* position to the first and vice versa.
*/
public static final int CYCLE_NEVER= 0;
/**
* Constant indicating that this UI should always cycle from the last
* position to the first and vice versa.
*/
public static final int CYCLE_ALWAYS= 1;
/**
* Constant indicating that this UI should cycle from the last position to
* the first and vice versa if its environment is not nested.
*/
public static final int CYCLE_WHEN_NO_PARENT= 2;
/**
* Listens on a styled text for events before (Verify) and after (Modify)
* modifications. Used to update the caret after linked changes.
*/
private final class CaretListener implements ModifyListener, VerifyListener {
/*
* @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
*/
public void modifyText(ModifyEvent e) {
updateSelection(e);
}
/*
* @see org.eclipse.swt.events.VerifyListener#verifyText(org.eclipse.swt.events.VerifyEvent)
*/
public void verifyText(VerifyEvent e) {
rememberSelection(e);
}
}
/**
* A link target consists of a viewer and gets notified if the linked UI on
* it is being shown.
*
* @since 3.0
*/
public static abstract class LinkedUITarget {
/**
* Returns the viewer represented by this target, never <code>null</code>.
*
* @return the viewer associated with this target.
*/
abstract ITextViewer getViewer();
/**
* Called by the linked UI when this target is being shown. An
* implementation could for example ensure that the corresponding
* editor is showing.
*/
abstract void enter();
/**
* The viewer's text widget is initialized when the UI first connects
* to the viewer and never changed thereafter. This is to keep the
* reference of the widget that we have registered our listeners with,
* as the viewer, when it gets disposed, does not remember it, resulting
* in a situation where we cannot uninstall the listeners and a memory leak.
*/
StyledText fWidget;
/** The cached shell - same reason as fWidget. */
Shell fShell;
/** The registered listener, or <code>null</code>. */
LinkedUIKeyListener fKeyListener;
}
private static final class EmptyTarget extends LinkedUITarget {
private ITextViewer fTextViewer;
public EmptyTarget(ITextViewer viewer) {
Assert.isNotNull(viewer);
fTextViewer= viewer;
}
/*
* @see org.eclipse.jdt.internal.ui.text.link2.LinkedUIControl.ILinkedUITarget#getViewer()
*/
public ITextViewer getViewer() {
return fTextViewer;
}
/*
* @see org.eclipse.jdt.internal.ui.text.link2.LinkedUIControl.ILinkedUITarget#enter()
*/
public void enter() {
}
}
/**
* An <code>ILinkedUITarget</code> with an associated editor, which is
* brought to the top when a linked position in its viewer is jumped to.
*
* @since 3.0
*/
public static class EditorTarget extends LinkedUITarget {
/** The text viewer. */
protected final ITextViewer fTextViewer;
/** The editor displaying the viewer. */
protected final ITextEditor fTextEditor;
/**
* Creates a new instance.
*
* @param viewer the viewer
* @param editor the editor displaying <code>viewer</code>, or <code>null</code>
*/
public EditorTarget(ITextViewer viewer, ITextEditor editor) {
Assert.isNotNull(viewer);
fTextViewer= viewer;
fTextEditor= editor;
}
/*
* @see org.eclipse.jdt.internal.ui.text.link2.LinkedUIControl.ILinkedUITarget#getViewer()
*/
public ITextViewer getViewer() {
return fTextViewer;
}
/*
* @see org.eclipse.jdt.internal.ui.text.link2.LinkedUIControl.ILinkedUITarget#enter()
*/
public void enter() {
if (fTextEditor != null)
return;
IWorkbenchPage page= fTextEditor.getEditorSite().getPage();
if (page != null) {
page.bringToTop(fTextEditor);
}
fTextEditor.setFocus();
}
}
/**
* Listens for state changes in the model.
*/
private final class ExitListener implements ILinkedListener {
/*
* @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#left(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment, int)
*/
public void left(LinkedEnvironment environment, int flags) {
leave(ILinkedListener.EXIT_ALL | flags);
}
/*
* @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#suspend(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment)
*/
public void suspend(LinkedEnvironment environment) {
disconnect();
redraw();
}
/*
* @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#resume(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment)
*/
public void resume(LinkedEnvironment environment, int flags) {
if ((flags & ILinkedListener.EXIT_ALL) != 0) {
leave(flags);
} else {
connect();
if ((flags & ILinkedListener.SELECT) != 0)
select();
redraw();
}
}
}
/**
* Exit flags returned if a custom exit policy wants to exit linked mode.
*/
public static class ExitFlags {
/** The flags to return in the <code>leave</code> method. */
public int flags;
/** The doit flag of the checked <code>VerifyKeyEvent</code>. */
public boolean doit;
/**
* Creates a new instance.
*
* @param flags the exit flags
* @param doit the doit flag for the verify event
*/
public ExitFlags(int flags, boolean doit) {
this.flags= flags;
this.doit= doit;
}
}
/**
* An exit policy can be registered by a caller to get custom exit
* behaviour.
*/
public interface IExitPolicy {
/**
* Checks whether the linked mode should be left after receiving the
* given <code>VerifyEvent</code> and selection.
*
* @param environment the linked environment
* @param event the verify event
* @param offset the offset of the current selection
* @param length the length of the current selection
* @return valid exit flags or <code>null</code> if no special action
* should be taken
*/
ExitFlags doExit(LinkedEnvironment environment, VerifyEvent event, int offset, int length);
}
/**
* A NullObject implementation of <code>IExitPolicy</code>.
*/
private static class NullExitPolicy implements IExitPolicy {
/*
* @see org.eclipse.jdt.internal.ui.text.link2.LinkedUIControl.IExitPolicy#doExit(org.eclipse.swt.events.VerifyEvent, int, int)
*/
public ExitFlags doExit(LinkedEnvironment environment, VerifyEvent event, int offset, int length) {
return null;
}
}
/**
* Listens for shell events and acts upon them.
*/
private class LinkedUICloser implements ShellListener {
public void shellActivated(ShellEvent e) {
}
public void shellClosed(ShellEvent e) {
leave(ILinkedListener.EXIT_ALL);
}
public void shellDeactivated(ShellEvent e) {
// T ODO reenable after debugging
// if (true) return;
// from LinkedPositionUI:
// don't deactivate on focus lost, since the proposal popups may take focus
// plus: it doesn't hurt if you can check with another window without losing linked mode
// since there is no intrusive popup sticking out.
// need to check first what happens on reentering based on an open action
// Seems to be no problem
// Better:
// Check with content assistant and only leave if its not the proposal shell that took the
// focus away.
StyledText text;
Display display;
if (fAssistant == null || fCurrentTarget == null || (text= fCurrentTarget.fWidget) == null
|| text.isDisposed() || (display= text.getDisplay()) == null || display.isDisposed()) {
leave(ILinkedListener.EXIT_ALL);
} else {
// Post in UI thread since the assistant popup will only get the focus after we lose it.
display.asyncExec(new Runnable() {
public void run() {
if (fIsActive && (fAssistant == null || !fAssistant.hasFocus())) {
leave(ILinkedListener.EXIT_ALL);
}
}
});
}
}
public void shellDeiconified(ShellEvent e) {
}
public void shellIconified(ShellEvent e) {
leave(ILinkedListener.EXIT_ALL);
}
}
/**
* Listens for key events, checks the exit policy for custom exit
* strategies but defaults to handling Tab, Enter, and Escape.
*/
private class LinkedUIKeyListener implements VerifyKeyListener {
private boolean fIsEnabled= true;
public void verifyKey(VerifyEvent event) {
if (!event.doit || !fIsEnabled)
return;
Point selection= fCurrentTarget.getViewer().getSelectedRange();
int offset= selection.x;
int length= selection.y;
// if the custom exit policy returns anything, use that
ExitFlags exitFlags= fExitPolicy.doExit(fEnvironment, event, offset, length);
if (exitFlags != null) {
leave(exitFlags.flags);
event.doit= exitFlags.doit;
return;
}
// standard behaviour:
// (Shift+)Tab: jumps from position to position, depending on cycle mode
// Enter: accepts all entries and leaves all (possibly stacked) environments, the last sets the caret
// Esc: accepts all entries and leaves all (possibly stacked) environments, the caret stays
// ? what do we do to leave one level of a cycling environment that is stacked?
// -> This is only the case if the level was set up with forced cycling (CYCLE_ALWAYS), in which case
// the caller is sure that one does not need by-level exiting.
switch (event.character) {
// [SHIFT-]TAB = hop between edit boxes
case 0x09:
if (!(fExitPosition != null && fExitPosition.includes(offset)) && !fEnvironment.anyPositionContains(offset)) {
// outside any edit box -> leave (all? TODO should only leave the affected, level and forward to the next upper)
leave(ILinkedListener.EXIT_ALL);
break;
} else {
if (event.stateMask == SWT.SHIFT)
previous();
else
next();
}
event.doit= false;
break;
// ENTER
case 0x0A:
// Ctrl+Enter on WinXP
case 0x0D:
if (fAssistant != null && fAssistant.wasProposalChosen()) {
// don't exit as it was really just the proposal that was chosen
next();
event.doit= false;
break;
} else if (!(fExitPosition != null && fExitPosition.includes(offset)) && !fEnvironment.anyPositionContains(offset)) {
// outside any edit box -> leave (all? TODO should only leave the affected, level and forward to the next upper)
leave(ILinkedListener.EXIT_ALL);
break;
} else {
// normal case: exit entire stack and put caret to final position
leave(ILinkedListener.EXIT_ALL | ILinkedListener.UPDATE_CARET);
event.doit= false;
break;
}
// ESC
case 0x1B:
// exit entire stack and leave caret
leave(ILinkedListener.EXIT_ALL);
event.doit= false;
break;
default:
if (event.character != 0) {
if (!controlUndoBehavior(offset, length)) {
leave(ILinkedListener.EXIT_ALL);
break;
}
}
}
}
private boolean controlUndoBehavior(int offset, int length) {
LinkedPosition position= fEnvironment.findPosition(new LinkedPosition(fCurrentTarget.getViewer().getDocument(), offset, length, LinkedPositionGroup.NO_STOP));
if (position != null) {
ITextViewerExtension extension= (ITextViewerExtension) fCurrentTarget.getViewer();
IRewriteTarget target= extension.getRewriteTarget();
if (fPreviousPosition != null && !fPreviousPosition.equals(position))
target.endCompoundChange();
target.beginCompoundChange();
}
fPreviousPosition= position;
return fPreviousPosition != null;
}
/**
* @param b
*/
public void setEnabled(boolean enabled) {
fIsEnabled= enabled;
}
}
/**
* Installed as post selection listener on the watched viewer. Updates the
* linked position after cursor movement, even to positions not in the
* iteration list.
*/
private class MySelectionListener implements ISelectionChangedListener {
/*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection= event.getSelection();
if (selection instanceof ITextSelection) {
ITextSelection textsel= (ITextSelection) selection;
if (event.getSelectionProvider() instanceof ITextViewer) {
IDocument doc= ((ITextViewer) event.getSelectionProvider()).getDocument();
if (doc != null) {
int offset= textsel.getOffset();
int length= textsel.getLength();
if (offset >= 0 && length >= 0) {
LinkedPosition find= new LinkedPosition(doc, offset, length, LinkedPositionGroup.NO_STOP);
LinkedPosition pos= fEnvironment.findPosition(find);
if (pos != null)
switchPosition(pos, false, false);
}
}
}
}
}
}
/** The current viewer. */
private LinkedUITarget fCurrentTarget;
/** The manager of the linked positions we provide a UI for. */
private LinkedEnvironment fEnvironment;
/** The set of viewers we manage. */
private LinkedUITarget[] fTargets;
/** The iterator over the tab stop positions. */
private TabStopIterator fIterator;
/* Our team of event listeners */
/** The shell listener. */
private LinkedUICloser fCloser= new LinkedUICloser();
/** The linked listener. */
private ILinkedListener fLinkedListener= new ExitListener();
/** The selection listener. */
private MySelectionListener fSelectionListener= new MySelectionListener();
/** The styled text listener. */
private CaretListener fCaretListener= new CaretListener();
/** The last caret position, used by fCaretListener. */
private final Position fCaretPosition= new Position(0, 0);
/** The painter for the underline of the current position. */
private LinkedUIPainter fPainter;
/** The exit policy to control custom exit behaviour */
private IExitPolicy fExitPolicy= new NullExitPolicy();
/** The current frame position shown in the UI, or <code>null</code>. */
private LinkedPosition fFramePosition;
/** The last visisted position, used for undo / redo. */
private LinkedPosition fPreviousPosition;
/** The content assistant used to show proposals. */
private ContentAssistant2 fAssistant;
/** The exit position. */
private LinkedPosition fExitPosition;
/** State indicator to prevent multiple invocation of leave. */
private boolean fIsActive= false;
private IPositionUpdater fPositionUpdater= new DefaultPositionUpdater(getCategory());
private boolean fDoContextInfo= false;
/**
* Creates a new UI on the given model (environment) and the set of
* viewers. The environment must provide a tab stop sequence with a
* non-empty list of tab stops.
*
* @param environment the linked position model
* @param targets the non-empty list of targets upon which the linked ui
* should act
*/
public LinkedUIControl(LinkedEnvironment environment, LinkedUITarget[] targets) {
constructor(environment, targets);
}
/**
* Conveniance ctor for just one viewer.
*
* @param environment the linked position model
* @param viewer the viewer upon which the linked ui
* should act
*/
public LinkedUIControl(LinkedEnvironment environment, ITextViewer viewer) {
constructor(environment, new LinkedUITarget[]{new EmptyTarget(viewer)});
}
/**
* Conveniance ctor for multiple viewers.
*
* @param environment the linked position model
* @param viewers the non-empty list of viewers upon which the linked ui
* should act
*/
public LinkedUIControl(LinkedEnvironment environment, ITextViewer[] viewers) {
LinkedUITarget[] array= new LinkedUITarget[viewers.length];
for (int i= 0; i < array.length; i++) {
array[i]= new EmptyTarget(viewers[i]);
}
constructor(environment, array);
}
/**
* Conveniance ctor for one target.
*
* @param environment the linked position model
* @param target the target upon which the linked ui
* should act
*/
public LinkedUIControl(LinkedEnvironment environment, LinkedUITarget target) {
constructor(environment, new LinkedUITarget[]{target});
}
/**
* This does the actual constructor work.
*
* @param environment the linked position model
* @param targets the non-empty array of targets upon which the linked ui
* should act
*/
private void constructor(LinkedEnvironment environment, LinkedUITarget[] targets) {
Assert.isNotNull(environment);
Assert.isNotNull(targets);
Assert.isTrue(targets.length > 0);
Assert.isTrue(environment.getTabStopSequence().size() > 0);
fEnvironment= environment;
fTargets= targets;
fCurrentTarget= targets[0];
fIterator= new TabStopIterator(fEnvironment.getTabStopSequence());
fIterator.setCycling(!fEnvironment.isNested());
fEnvironment.addLinkedListener(fLinkedListener);
fPainter= new LinkedUIPainter(fCurrentTarget.getViewer());
fPainter.setColor(getFrameColor());
fAssistant= new ContentAssistant2();
fAssistant.setDocumentPartitioning(IJavaPartitions.JAVA_PARTITIONING);
fCaretPosition.delete();
}
/**
* Starts this UI on the first position.
*/
public void enter() {
fIsActive= true;
connect();
next();
}
/**
* Sets an <code>IExitPolicy</code> to customize the exit behaviour of
* this linked UI.
*
* @param policy the exit policy to use.
*/
public void setExitPolicy(IExitPolicy policy) {
fExitPolicy= policy;
}
/**
* Sets the exit position to move the caret to when linked mode is exited.
*
* @param target the target where the exit position is located
* @param offset the offset of the exit position
* @param length the length of the exit position (in case there should be a
* selection)
* @param sequence set to the tab stop position of the exit position, or
* <code>LinkedPositionGroup.NO_STOP</code> if there should be no tab stop.
* @throws BadLocationException if the position is not valid in the
* viewer's document
*/
public void setExitPosition(LinkedUITarget target, int offset, int length, int sequence) throws BadLocationException {
// remove any existing exit position
if (fExitPosition != null) {
fExitPosition.getDocument().removePosition(fExitPosition);
fIterator.removePosition(fExitPosition);
fExitPosition= null;
}
IDocument doc= target.getViewer().getDocument();
if (doc == null)
return;
// if we are a tabstop, we are the last one -> MAX_VALUE
fExitPosition= new LinkedPosition(doc, offset, length, sequence);
doc.addPosition(fExitPosition); // gets removed in leave()
if (sequence != LinkedPositionGroup.NO_STOP)
fIterator.addPosition(fExitPosition);
}
/**
* Sets the exit position to move the caret to when linked mode is exited.
*
* @param viewer the viewer where the exit position is located
* @param offset the offset of the exit position
* @param length the length of the exit position (in case there should be a
* selection)
* @param sequence set to the tab stop position of the exit position, or
* <code>LinkedPositionGroup.NO_STOP</code> if there should be no tab stop.
* @throws BadLocationException if the position is not valid in the
* viewer's document
*/
public void setExitPosition(ITextViewer viewer, int offset, int length, int sequence) throws BadLocationException {
setExitPosition(new EditorTarget(viewer, null), offset, length, sequence);
}
/**
* Sets the cycling mode to either of <code>CYCLING_ALWAYS</code>,
* <code>CYCLING_NEVER</code>, or <code>CYCLING_WHEN_NO_PARENT</code>,
* which is the default.
*
* @param mode the new cycling mode.
*/
public void setCyclingMode(int mode) {
if (mode == CYCLE_ALWAYS || mode == CYCLE_WHEN_NO_PARENT && !fEnvironment.isNested())
fIterator.setCycling(true);
else
fIterator.setCycling(false);
}
void next() {
if (fIterator.hasNext(fFramePosition)) {
switchPosition(fIterator.next(fFramePosition), true, true);
return;
} else
leave(ILinkedListener.UPDATE_CARET);
}
void previous() {
if (fIterator.hasPrevious(fFramePosition)) {
switchPosition(fIterator.previous(fFramePosition), true, true);
} else
// dont't update caret, but rather select the current frame
leave(ILinkedListener.SELECT);
}
private void triggerContextInfo() {
ITextOperationTarget target= fCurrentTarget.getViewer().getTextOperationTarget();
if (target != null) {
if (target.canDoOperation(ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION))
target.doOperation(ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION);
}
}
/** Trigger content assist on choice positions */
private void triggerContentAssist() {
if (fFramePosition instanceof ProposalPosition) {
ProposalPosition pp= (ProposalPosition) fFramePosition;
fAssistant.setCompletions(pp.getChoices());
fAssistant.showPossibleCompletions();
} else {
fAssistant.setCompletions(new ICompletionProposal[0]);
fAssistant.hidePossibleCompletions();
}
}
private void switchPosition(LinkedPosition pos, boolean select, boolean showProposals) {
Assert.isNotNull(pos);
if (pos.equals(fFramePosition))
return;
// mark navigation history
JavaPlugin.getActivePage().getNavigationHistory().markLocation(JavaPlugin.getActivePage().getActiveEditor());
// undo
ITextViewerExtension extension= (ITextViewerExtension) fCurrentTarget.getViewer();
IRewriteTarget target= extension.getRewriteTarget();
if (fFramePosition != null)
target.endCompoundChange();
redraw();
IDocument oldDoc= fFramePosition == null ? null : fFramePosition.getDocument();
IDocument newDoc= pos.getDocument();
switchViewer(oldDoc, newDoc);
fFramePosition= pos;
if (fFramePosition != null)
target.beginCompoundChange();
fPainter.setPosition(fFramePosition);
if (select)
select();
if (fFramePosition == fExitPosition && !fIterator.isCycling())
leave(ILinkedListener.NONE);
else {
redraw();
}
if (showProposals)
triggerContentAssist();
if (fFramePosition != fExitPosition && fDoContextInfo)
triggerContextInfo();
}
private void switchViewer(IDocument oldDoc, IDocument newDoc) {
if (oldDoc != newDoc) {
LinkedUITarget target= null;
for (int i= 0; i < fTargets.length; i++) {
if (fTargets[i].getViewer().getDocument() == newDoc) {
target= fTargets[i];
break;
}
}
if (target != fCurrentTarget) {
disconnect();
fCurrentTarget= target;
target.enter();
connect();
}
}
}
private void select() {
ITextViewer viewer= fCurrentTarget.getViewer();
if (!viewer.overlapsWithVisibleRegion(fFramePosition.offset, fFramePosition.length))
viewer.resetVisibleRegion();
viewer.revealRange(fFramePosition.offset, fFramePosition.length);
viewer.setSelectedRange(fFramePosition.offset, fFramePosition.length);
}
private void redraw() {
if (fFramePosition == null)
return;
IRegion widgetRange= asWidgetRange(fFramePosition);
if (widgetRange == null) {
leave(ILinkedListener.EXIT_ALL);
return;
}
StyledText text= fCurrentTarget.fWidget;
if (text != null && !text.isDisposed())
text.redrawRange(widgetRange.getOffset(), widgetRange.getLength(), true);
}
private void connect() {
Assert.isNotNull(fCurrentTarget);
ITextViewer viewer= fCurrentTarget.getViewer();
Assert.isNotNull(viewer);
fCurrentTarget.fWidget= viewer.getTextWidget();
if (fCurrentTarget.fWidget == null)
leave(ILinkedListener.EXIT_ALL);
if (fCurrentTarget.fKeyListener == null) {
fCurrentTarget.fKeyListener= new LinkedUIKeyListener();
((ITextViewerExtension) viewer).prependVerifyKeyListener(fCurrentTarget.fKeyListener);
} else
fCurrentTarget.fKeyListener.setEnabled(true);
((IPostSelectionProvider) viewer).addPostSelectionChangedListener(fSelectionListener);
fPainter.setViewer(viewer);
fCurrentTarget.fWidget.addPaintListener(fPainter);
fCurrentTarget.fWidget.showSelection();
fCurrentTarget.fWidget.addVerifyListener(fCaretListener);
fCurrentTarget.fWidget.addModifyListener(fCaretListener);
fCurrentTarget.fShell= fCurrentTarget.fWidget.getShell();
if (fCurrentTarget.fShell == null)
leave(ILinkedListener.EXIT_ALL);
fCurrentTarget.fShell.addShellListener(fCloser);
fAssistant.install(viewer);
}
private void disconnect() {
Assert.isNotNull(fCurrentTarget);
ITextViewer viewer= fCurrentTarget.getViewer();
Assert.isNotNull(viewer);
fAssistant.uninstall();
StyledText text= fCurrentTarget.fWidget;
fCurrentTarget.fWidget= null;
Shell shell= fCurrentTarget.fShell;
fCurrentTarget.fShell= null;
if (shell != null && !shell.isDisposed())
shell.removeShellListener(fCloser);
if (text != null && !text.isDisposed()) {
text.removeModifyListener(fCaretListener);
text.removeVerifyListener(fCaretListener);
text.removePaintListener(fPainter);
}
// don't remove the verify key listener to let it keep its position
// in the listener queue
fCurrentTarget.fKeyListener.setEnabled(false);
((IPostSelectionProvider) viewer).removePostSelectionChangedListener(fSelectionListener);
redraw();
}
void leave(int flags) {
if (!fIsActive)
return;
fIsActive= false;
ITextViewerExtension extension= (ITextViewerExtension) fCurrentTarget.getViewer();
IRewriteTarget target= extension.getRewriteTarget();
target.endCompoundChange();
// // debug trace
// JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), IStatus.OK, "leaving linked mode", null));
fPainter.dispose();
disconnect();
redraw();
for (int i= 0; i < fTargets.length; i++) {
if (fCurrentTarget.fKeyListener != null) {
((ITextViewerExtension) fTargets[i].getViewer()).removeVerifyKeyListener(fCurrentTarget.fKeyListener);
fCurrentTarget.fKeyListener= null;
}
}
if (fExitPosition != null)
fExitPosition.getDocument().removePosition(fExitPosition);
if ((flags & ILinkedListener.UPDATE_CARET) != 0 && fExitPosition != null && fFramePosition != fExitPosition)
switchPosition(fExitPosition, true, false);
for (int i= 0; i < fTargets.length; i++) {
IDocument doc= fTargets[i].getViewer().getDocument();
if (doc != null) {
doc.removePositionUpdater(fPositionUpdater);
boolean uninstallCat= false;
String[] cats= doc.getPositionCategories();
for (int j= 0; j < cats.length; j++) {
if (getCategory().equals(cats[j])) {
uninstallCat= true;
break;
}
}
if (uninstallCat)
try {
doc.removePositionCategory(getCategory());
} catch (BadPositionCategoryException e) {
// ignore
}
}
}
fEnvironment.exit(flags);
}
private IRegion asWidgetRange(Position position) {
ITextViewer viewer= fCurrentTarget.getViewer();
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
return extension.modelRange2WidgetRange(new Region(position.getOffset(), position.getLength()));
} else {
IRegion region= viewer.getVisibleRegion();
if (includes(region, position))
return new Region(position.getOffset() - region.getOffset(), position.getLength());
}
return null;
}
private static boolean includes(IRegion region, Position position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
private Color getFrameColor() {
StyledText text= fCurrentTarget.getViewer().getTextWidget();
if (text != null) {
Display display= text.getDisplay();
return createColor(JavaPlugin.getDefault().getPreferenceStore(), PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, display);
}
return null;
}
/**
* Creates a color from the information stored in the given preference
* store. Returns <code>null</code> if there is no such information
* available.
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store != null && store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return new Color(display, new RGB(100, 255, 100));
}
/**
* Returns the currently selected region or <code>null</code>.
*
* @return the currently selected region or <code>null</code>
*/
public IRegion getSelectedRegion() {
if (fFramePosition == null)
if (fExitPosition != null)
return new Region(fExitPosition.getOffset(), fExitPosition.getLength());
else
return null;
else
return new Region(fFramePosition.getOffset(), fFramePosition.getLength());
}
private void rememberSelection(VerifyEvent event) {
// don't update other editor's carets
if (event.getSource() != fCurrentTarget.fWidget)
return;
Point selection= fCurrentTarget.getViewer().getSelectedRange();
fCaretPosition.offset= selection.x + selection.y;
fCaretPosition.length= 0;
fCaretPosition.isDeleted= false;
try {
IDocument document= fCurrentTarget.getViewer().getDocument();
boolean installCat= true;
String[] cats= document.getPositionCategories();
for (int i= 0; i < cats.length; i++) {
if (getCategory().equals(cats[i]))
installCat= false;
}
if (installCat) {
document.addPositionCategory(getCategory());
document.addPositionUpdater(fPositionUpdater);
}
if (document.getPositions(getCategory()).length != 0)
document.removePosition(getCategory(), fCaretPosition);
document.addPosition(getCategory(), fCaretPosition);
} catch (BadLocationException e) {
// will not happen
Assert.isTrue(false);
} catch (BadPositionCategoryException e) {
// will not happen
Assert.isTrue(false);
}
}
private void updateSelection(ModifyEvent event) {
// don't set the caret if we've left already (we're still called as the listener
// has just been removed) or the event does not happen on our current viewer
if (!fIsActive || event.getSource() != fCurrentTarget.fWidget)
return;
if (!fCaretPosition.isDeleted())
fCurrentTarget.getViewer().setSelectedRange(fCaretPosition.getOffset(), 0);
fCaretPosition.isDeleted= true;
}
private String getCategory() {
return toString();
}
/**
* Sets the context info property. If set to <code>true</code>, context
* info will be invoked on the current target's viewer whenever a position
* is switched.
*
* @param doContextInfo The doContextInfo to set.
*/
public void setDoContextInfo(boolean doContextInfo) {
fDoContextInfo= doContextInfo;
}
}
|
48,722 |
Bug 48722 Extract Constant refactoring: proposed name
|
I20031211 When extracting the constant "win32" the proposed name for the constant is: WIN__ I don't see a reason why WIN32 isn't used.
|
resolved fixed
|
29e9cb0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-06T17:22:18Z | 2003-12-15T09:20:00Z |
org.eclipse.jdt.ui/core
| |
48,722 |
Bug 48722 Extract Constant refactoring: proposed name
|
I20031211 When extracting the constant "win32" the proposed name for the constant is: WIN__ I don't see a reason why WIN32 isn't used.
|
resolved fixed
|
29e9cb0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-06T17:22:18Z | 2003-12-15T09:20:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractConstantRefactoring.java
| |
48,393 |
Bug 48393 inline final static field [refactoring]
|
Please provide a refactoring to inline a constant (final static field).
|
resolved fixed
|
60ca83c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-07T10:17:10Z | 2003-12-10T09:53:20Z |
org.eclipse.jdt.ui/core
| |
48,393 |
Bug 48393 inline final static field [refactoring]
|
Please provide a refactoring to inline a constant (final static field).
|
resolved fixed
|
60ca83c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-07T10:17:10Z | 2003-12-10T09:53:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InlineMethodRefactoring.java
| |
48,393 |
Bug 48393 inline final static field [refactoring]
|
Please provide a refactoring to inline a constant (final static field).
|
resolved fixed
|
60ca83c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-07T10:17:10Z | 2003-12-10T09:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/InlineAction.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.dialogs.MessageDialog;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages;
import org.eclipse.jdt.internal.ui.refactoring.actions.InlineConstantAction;
import org.eclipse.jdt.internal.ui.refactoring.actions.InlineMethodAction;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.refactoring.code.InlineConstantRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.code.InlineTempRefactoring;
/**
* Inlines a method, local variable or a static final field.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.1
*/
public class InlineAction extends SelectionDispatchAction {
private CompilationUnitEditor fEditor;
private final InlineTempAction fInlineTemp;
private final InlineMethodAction fInlineMethod;
private final InlineConstantAction fInlineConstant;
/**
* Creates a new <code>InlineAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public InlineAction(IWorkbenchSite site) {
super(site);
setText(RefactoringMessages.getString("InlineAction.Inline")); //$NON-NLS-1$
fInlineTemp = new InlineTempAction(site);
fInlineMethod = new InlineMethodAction(site);
fInlineConstant = new InlineConstantAction(site);
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.INLINE_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public InlineAction(CompilationUnitEditor editor) {
//don't want to call 'this' here - it'd create useless action objects
super(editor.getEditorSite());
setText(RefactoringMessages.getString("InlineAction.Inline")); //$NON-NLS-1$
fEditor= editor;
fInlineTemp = new InlineTempAction(editor);
fInlineMethod = new InlineMethodAction(editor);
fInlineConstant = new InlineConstantAction(editor);
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.INLINE_ACTION);
setEnabled(getCompilationUnit() != null);
}
/*
* @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#selectionChanged(org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(ISelection selection) {
fInlineConstant.update(selection);
fInlineMethod.update(selection);
fInlineTemp.update(selection);
setEnabled(computeEnablementState());
}
private boolean computeEnablementState() {
return fInlineTemp.isEnabled() || fInlineConstant.isEnabled() || fInlineMethod.isEnabled();
}
/*
* @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.text.ITextSelection)
*/
public void run(ITextSelection selection) {
ICompilationUnit cu= getCompilationUnit();
if (cu == null || !ActionUtil.isProcessable(getShell(), cu))
return;
if (fInlineTemp.isEnabled() && tryInlineTemp(cu, selection))
return;
if (fInlineMethod.isEnabled() && tryInlineMethod(cu, selection))
return;
if (fInlineConstant.isEnabled() && tryInlineConstant(cu, selection))
return;
MessageDialog.openInformation(getShell(), RefactoringMessages.getString("InlineAction.dialog_title"), RefactoringMessages.getString("InlineAction.select")); //$NON-NLS-1$ //$NON-NLS-2$
}
private boolean tryInlineTemp(ICompilationUnit cu, ITextSelection selection){
InlineTempRefactoring inlineTemp= InlineTempRefactoring.create(cu, selection.getOffset(), selection.getLength());
if (inlineTemp == null)
return false;
fInlineTemp.run(selection);
return true;
}
private boolean tryInlineMethod(ICompilationUnit cu, ITextSelection selection){
InlineMethodRefactoring inlineMethodRef= InlineMethodRefactoring.create(
cu, selection.getOffset(), selection.getLength(),
JavaPreferencesSettings.getCodeGenerationSettings());
if (inlineMethodRef == null)
return false;
fInlineMethod.run(selection);
return true;
}
private boolean tryInlineConstant(ICompilationUnit cu, ITextSelection selection){
InlineConstantRefactoring inlineConstantRef= InlineConstantRefactoring.create(
cu, selection.getOffset(), selection.getLength(),
JavaPreferencesSettings.getCodeGenerationSettings());
if (inlineConstantRef == null)
return false;
fInlineConstant.run(selection);
return true;
}
private ICompilationUnit getCompilationUnit() {
return SelectionConverter.getInputAsCompilationUnit(fEditor);
}
/*
* @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.viewers.IStructuredSelection)
*/
public void run(IStructuredSelection selection) {
if (fInlineConstant.isEnabled())
fInlineConstant.run(selection);
else if (fInlineMethod.isEnabled())
fInlineMethod.run(selection);
else
//inline temp will never be enabled on IStructuredSelection
//don't bother running it
Assert.isTrue(! fInlineTemp.isEnabled());
}
}
|
49,599 |
Bug 49599 Occurrences finder should use a job
|
Build: 3.0 M6 I noticed that the background task to find occurrences in the file creates a new thread every time, rather than using jobs. This is exactly the situation that jobs were created for (in fact Erich used this as a demo of the job infrastructure at a code camp). Some advantages of changing to jobs: - less overhead (currently a new thread is created per key press, jobs use a thread pool) - better handling of priority (currently running in a thread with same priority as the UI, and thus is competing with UI thread for CPU more than it should) - smarter scheduling. Jobs with "DECORATE" priority are run based on a check of how busy the system is. Thus they do not run immediately if there are other things going on (they will run eventually, just not as quickly). This smooths over bottlenecks when the system is busy. Note that you can prevent this job from showing in the progress view or making the progress animation (cigarette) move by making it a system job (Job.setSystem(true)). Generally jobs that the user didn't explicitly start can be marked as system jobs. If there was a reason why jobs were considered and rejected, I'd be curious to know. If the infrastructure isn't useful to you then I want to fix it.
|
resolved fixed
|
c0a3666
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-07T17:16:59Z | 2004-01-06T20:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.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.javaeditor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.CollationElementIterator;
import java.text.Collator;
import java.text.RuleBasedCollator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
import org.eclipse.swt.custom.ST;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.IPostSelectionProvider;
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.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextPresentationListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension3;
import org.eclipse.jface.text.ITextViewerExtension4;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextPresentation;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.IInformationProviderExtension2;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelExtension;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.LineChangeHover;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.ExtendedTextEditor;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextNavigationAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportContainer;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.ILocalVariable;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
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.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
import org.eclipse.jdt.internal.ui.search.FindOccurrencesEngine;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.JavaChangeHover;
import org.eclipse.jdt.internal.ui.text.JavaPairMatcher;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
/**
* Java specific text editor.
*/
public abstract class JavaEditor extends ExtendedTextEditor implements IViewPartInputProvider {
/**
* Internal implementation class for a change listener.
* @since 3.0
*/
protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener {
/**
* Installs this selection changed listener with the given selection provider. If
* the selection provider is a post selection provider, post selection changed
* events are the preferred choice, otherwise normal selection changed events
* are requested.
*
* @param selectionProvider
*/
public void install(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.addPostSelectionChangedListener(this);
} else {
selectionProvider.addSelectionChangedListener(this);
}
}
/**
* Removes this selection changed listener from the given selection provider.
*
* @param selectionProviderstyle
*/
public void uninstall(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.removePostSelectionChangedListener(this);
} else {
selectionProvider.removeSelectionChangedListener(this);
}
}
}
/**
* Updates the Java outline page selection and this editor's range indicator.
*
* @since 3.0
*/
private class EditorSelectionChangedListener extends AbstractSelectionChangedListener {
/*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
selectionChanged();
}
public void selectionChanged() {
ISourceReference element= computeHighlightRangeSourceReference();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
synchronizeOutlinePage(element);
setSelection(element, false);
updateStatusLine();
updateOccurrenceAnnotations();
}
}
/**
* Updates the selection in the editor's widget with the selection of the outline page.
*/
class OutlineSelectionChangedListener extends AbstractSelectionChangedListener {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
}
/*
* Link mode.
*/
class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener,
FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener, ITextPresentationListener {
/** The session is active. */
private boolean fActive;
/** The currently active style range. */
private IRegion fActiveRegion;
/** The currently active style range as position. */
private Position fRememberedPosition;
/** The hand cursor. */
private Cursor fCursor;
/** The link color. */
private Color fColor;
/** The key modifier mask. */
private int fKeyModifierMask;
public void deactivate() {
deactivate(false);
}
public void deactivate(boolean redrawAll) {
if (!fActive)
return;
repairRepresentation(redrawAll);
fActive= false;
}
public void install() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
updateColor(sourceViewer);
sourceViewer.addTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.addDocumentListener(this);
text.addKeyListener(this);
text.addMouseListener(this);
text.addMouseMoveListener(this);
text.addFocusListener(this);
text.addPaintListener(this);
((ITextViewerExtension4)sourceViewer).addTextPresentationListener(this);
updateKeyModifierMask();
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
private void updateKeyModifierMask() {
String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
fKeyModifierMask= computeStateMask(modifiers);
if (fKeyModifierMask == -1) {
// Fallback to stored state mask
fKeyModifierMask= getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
}
}
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;
}
public void uninstall() {
if (fColor != null) {
fColor.dispose();
fColor= null;
}
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
sourceViewer.removeTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.removeDocumentListener(this);
IPreferenceStore preferenceStore= getPreferenceStore();
if (preferenceStore != null)
preferenceStore.removePropertyChangeListener(this);
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
text.removeKeyListener(this);
text.removeMouseListener(this);
text.removeMouseMoveListener(this);
text.removeFocusListener(this);
text.removePaintListener(this);
((ITextViewerExtension4)sourceViewer).removeTextPresentationListener(this);
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(JavaEditor.LINK_COLOR)) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null)
updateColor(viewer);
} else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
updateKeyModifierMask();
}
}
private void updateColor(ISourceViewer viewer) {
if (fColor != null)
fColor.dispose();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display);
}
/**
* Creates a color from the information stored in the given preference store.
* Returns <code>null</code> if there is no such information available.
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
private void repairRepresentation() {
repairRepresentation(false);
}
private void repairRepresentation(boolean redrawAll) {
if (fActiveRegion == null)
return;
int offset= fActiveRegion.getOffset();
int length= fActiveRegion.getLength();
fActiveRegion= null;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
resetCursor(viewer);
// Invalidate ==> remove applied text presentation
if (!redrawAll && viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
else
viewer.invalidateTextPresentation();
// Remove underline
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
offset= extension.modelOffset2WidgetOffset(offset);
} else {
offset -= viewer.getVisibleRegion().getOffset();
}
try {
StyledText text= viewer.getTextWidget();
text.redrawRange(offset, length, false);
} catch (IllegalArgumentException x) {
JavaPlugin.log(x);
}
}
}
// will eventually be replaced by a method provided by jdt.core
private IRegion selectWord(IDocument document, int anchor) {
try {
int offset= anchor;
char c;
while (offset >= 0) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
--offset;
}
int start= offset;
offset= anchor;
int length= document.getLength();
while (offset < length) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
++offset;
}
int end= offset;
if (start == end)
return new Region(start, 0);
else
return new Region(start + 1, end - start - 1);
} catch (BadLocationException x) {
return null;
}
}
IRegion getCurrentTextRegion(ISourceViewer viewer) {
int offset= getCurrentTextOffset(viewer);
if (offset == -1)
return null;
IJavaElement input= SelectionConverter.getInput(JavaEditor.this);
if (input == null)
return null;
try {
IJavaElement[] elements= null;
synchronized (input) {
elements= ((ICodeAssist) input).codeSelect(offset, 0);
}
if (elements == null || elements.length == 0)
return null;
return selectWord(viewer.getDocument(), offset);
} catch (JavaModelException e) {
return null;
}
}
private int getCurrentTextOffset(ISourceViewer viewer) {
try {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return -1;
Display display= text.getDisplay();
Point absolutePosition= display.getCursorLocation();
Point relativePosition= text.toControl(absolutePosition);
int widgetOffset= text.getOffsetAtLocation(relativePosition);
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
return extension.widgetOffset2ModelOffset(widgetOffset);
} else {
return widgetOffset + viewer.getVisibleRegion().getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
public void applyTextPresentation(TextPresentation textPresentation) {
if (fActiveRegion == null)
return;
IRegion region= textPresentation.getExtent();
if (fActiveRegion.getOffset() + fActiveRegion.getLength() >= region.getOffset() && region.getOffset() + region.getLength() > fActiveRegion.getOffset())
textPresentation.mergeStyleRange(new StyleRange(fActiveRegion.getOffset(), fActiveRegion.getLength(), fColor, null));
}
private void highlightRegion(ISourceViewer viewer, IRegion region) {
if (region.equals(fActiveRegion))
return;
repairRepresentation();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
// Underline
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(region);
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
offset= region.getOffset() - viewer.getVisibleRegion().getOffset();
length= region.getLength();
}
text.redrawRange(offset, length, false);
// Invalidate region ==> apply text presentation
fActiveRegion= region;
if (viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(region.getOffset(), region.getLength());
else
viewer.invalidateTextPresentation();
}
private void activateCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
if (fCursor == null)
fCursor= new Cursor(display, SWT.CURSOR_HAND);
text.setCursor(fCursor);
}
private void resetCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed())
text.setCursor(null);
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
}
/*
* @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
*/
public void keyPressed(KeyEvent event) {
if (fActive) {
deactivate();
return;
}
if (event.keyCode != fKeyModifierMask) {
deactivate();
return;
}
fActive= true;
// removed for #25871
//
// ISourceViewer viewer= getSourceViewer();
// if (viewer == null)
// return;
//
// IRegion region= getCurrentTextRegion(viewer);
// if (region == null)
// return;
//
// highlightRegion(viewer, region);
// activateCursor(viewer);
}
/*
* @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
*/
public void keyReleased(KeyEvent event) {
if (!fActive)
return;
deactivate();
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDoubleClick(MouseEvent e) {}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDown(MouseEvent event) {
if (!fActive)
return;
if (event.stateMask != fKeyModifierMask) {
deactivate();
return;
}
if (event.button != 1) {
deactivate();
return;
}
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
*/
public void mouseUp(MouseEvent e) {
if (!fActive)
return;
if (e.button != 1) {
deactivate();
return;
}
boolean wasActive= fCursor != null;
deactivate();
if (wasActive) {
IAction action= getAction("OpenEditor"); //$NON-NLS-1$
if (action != null)
action.run();
}
}
/*
* @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
*/
public void mouseMove(MouseEvent event) {
if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) {
deactivate();
return;
}
if (!fActive) {
if (event.stateMask != fKeyModifierMask)
return;
// modifier was already pressed
fActive= true;
}
ISourceViewer viewer= getSourceViewer();
if (viewer == null) {
deactivate();
return;
}
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed()) {
deactivate();
return;
}
if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) {
deactivate();
return;
}
IRegion region= getCurrentTextRegion(viewer);
if (region == null || region.getLength() == 0) {
repairRepresentation();
return;
}
highlightRegion(viewer, region);
activateCursor(viewer);
}
/*
* @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
*/
public void focusGained(FocusEvent e) {}
/*
* @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
*/
public void focusLost(FocusEvent event) {
deactivate();
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentAboutToBeChanged(DocumentEvent event) {
if (fActive && fActiveRegion != null) {
fRememberedPosition= new Position(fActiveRegion.getOffset(), fActiveRegion.getLength());
try {
event.getDocument().addPosition(fRememberedPosition);
} catch (BadLocationException x) {
fRememberedPosition= null;
}
}
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
if (fRememberedPosition != null) {
if (!fRememberedPosition.isDeleted()) {
event.getDocument().removePosition(fRememberedPosition);
fActiveRegion= new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength());
fRememberedPosition= null;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
StyledText widget= viewer.getTextWidget();
if (widget != null && !widget.isDisposed()) {
widget.getDisplay().asyncExec(new Runnable() {
public void run() {
deactivate();
}
});
}
}
} else {
fActiveRegion= null;
fRememberedPosition= null;
deactivate();
}
}
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
if (oldInput == null)
return;
deactivate();
oldInput.removeDocumentListener(this);
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
if (newInput == null)
return;
newInput.addDocumentListener(this);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(new Region(offset, length));
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
IRegion region= viewer.getVisibleRegion();
if (!includes(region, fActiveRegion))
return;
offset= fActiveRegion.getOffset() - region.getOffset();
length= fActiveRegion.getLength();
}
// support for bidi
Point minLocation= getMinimumLocation(text, offset, length);
Point maxLocation= getMaximumLocation(text, offset, length);
int x1= minLocation.x;
int x2= minLocation.x + maxLocation.x - minLocation.x - 1;
int y= minLocation.y + text.getLineHeight() - 1;
GC gc= event.gc;
if (fColor != null && !fColor.isDisposed())
gc.setForeground(fColor);
gc.drawLine(x1, y, x2, y);
}
private boolean includes(IRegion region, IRegion position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
private Point getMinimumLocation(StyledText text, int offset, int length) {
Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x < minLocation.x)
minLocation.x= location.x;
if (location.y < minLocation.y)
minLocation.y= location.y;
}
return minLocation;
}
private Point getMaximumLocation(StyledText text, int offset, int length) {
Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x > maxLocation.x)
maxLocation.x= location.x;
if (location.y > maxLocation.y)
maxLocation.y= location.y;
}
return maxLocation;
}
}
/**
* This action dispatches into two behaviours: If there is no current text
* hover, the javadoc is displayed using information presenter. If there is
* a current text hover, it is converted into a information presenter in
* order to make it sticky.
*/
class InformationDispatchAction extends TextEditorAction {
/** The wrapped text operation action. */
private final TextOperationAction fTextOperationAction;
/**
* Creates a dispatch action.
*/
public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
super(resourceBundle, prefix, JavaEditor.this);
if (textOperationAction == null)
throw new IllegalArgumentException();
fTextOperationAction= textOperationAction;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
/**
* Information provider used to present the information.
*
* @since 3.0
*/
class InformationProvider implements IInformationProvider, IInformationProviderExtension2 {
private IRegion fHoverRegion;
private String fHoverInfo;
private IInformationControlCreator fControlCreator;
InformationProvider(IRegion hoverRegion, String hoverInfo, IInformationControlCreator controlCreator) {
fHoverRegion= hoverRegion;
fHoverInfo= hoverInfo;
fControlCreator= controlCreator;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getSubject(ITextViewer textViewer, int invocationOffset) {
return fHoverRegion;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getInformation(ITextViewer textViewer, IRegion subject) {
return fHoverInfo;
}
/*
* @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator()
* @since 3.0
*/
public IInformationControlCreator getInformationPresenterControlCreator() {
return fControlCreator;
}
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null) {
fTextOperationAction.run();
return;
}
if (sourceViewer instanceof ITextViewerExtension4) {
ITextViewerExtension4 extension4= (ITextViewerExtension4) sourceViewer;
if (extension4.moveFocusToWidgetToken())
return;
}
if (! (sourceViewer instanceof ITextViewerExtension2)) {
fTextOperationAction.run();
return;
}
ITextViewerExtension2 textViewerExtension2= (ITextViewerExtension2) sourceViewer;
// does a text hover exist?
ITextHover textHover= textViewerExtension2.getCurrentTextHover();
if (textHover == null) {
fTextOperationAction.run();
return;
}
Point hoverEventLocation= textViewerExtension2.getHoverEventLocation();
int offset= computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
if (offset == -1) {
fTextOperationAction.run();
return;
}
try {
// get the text hover content
String contentType= TextUtilities.getContentType(sourceViewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, offset);
IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset);
if (hoverRegion == null)
return;
String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion);
IInformationControlCreator controlCreator= null;
if (textHover instanceof IInformationProviderExtension2)
controlCreator= ((IInformationProviderExtension2)textHover).getInformationPresenterControlCreator();
IInformationProvider informationProvider= new InformationProvider(hoverRegion, hoverInfo, controlCreator);
fInformationPresenter.setOffset(offset);
fInformationPresenter.setInformationProvider(informationProvider, contentType);
fInformationPresenter.showInformation();
} catch (BadLocationException e) {
}
}
// modified version from TextViewer
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
StyledText styledText= textViewer.getTextWidget();
IDocument document= textViewer.getDocument();
if (document == null)
return -1;
try {
int widgetLocation= styledText.getOffsetAtLocation(new Point(x, y));
if (textViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) textViewer;
return extension.widgetOffset2ModelOffset(widgetLocation);
} else {
IRegion visibleRegion= textViewer.getVisibleRegion();
return widgetLocation + visibleRegion.getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
}
private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener {
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
handlePreferencePropertyChanged(event);
}
}
/**
* This action implements smart home.
*
* Instead of going to the start of a line it does the following:
*
* - if smart home/end is enabled and the caret is after the line's first non-whitespace then the caret is moved directly before it, taking JavaDoc and multi-line comments into account.
* - if the caret is before the line's first non-whitespace the caret is moved to the beginning of the line
* - if the caret is at the beginning of the line see first case.
*
* @since 3.0
*/
protected class SmartLineStartAction extends LineStartAction {
/**
* Creates a new smart line start action
*
* @param textWidget the styled text widget
* @param doSelect a boolean flag which tells if the text up to the beginning of the line should be selected
*/
public SmartLineStartAction(final StyledText textWidget, final boolean doSelect) {
super(textWidget, doSelect);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, int, java.lang.String)
*/
protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) {
String type= IDocument.DEFAULT_CONTENT_TYPE;
try {
type= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, offset).getType();
} catch (BadLocationException exception) {
// Should not happen
}
int index= super.getLineStartPosition(document, line, length, offset);
if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) {
if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') {
do {
++index;
} while (index < length && Character.isWhitespace(line.charAt(index)));
}
} else {
if (index < length - 1 && line.charAt(index) == '/' && line.charAt(++index) == '/') {
do {
++index;
} while (index < length && Character.isWhitespace(line.charAt(index)));
}
}
return index;
}
}
/**
* Text navigation action to navigate to the next sub-word.
*
* @since 3.0
*/
protected abstract class NextSubWordAction extends TextNavigationAction {
/** Collator to determine the sub-word boundaries */
private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance();
/**
* Creates a new next sub-word action.
*
* @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST.
*/
protected NextSubWordAction(int code) {
super(getSourceViewer().getTextWidget(), code);
// Only compare upper-/lower case
fCollator.setStrength(Collator.TERTIARY);
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
try {
final ISourceViewer viewer= getSourceViewer();
final IDocument document= viewer.getDocument();
int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
// Check whether we are in a java code partititon and the preference is enabled
final IPreferenceStore store= getPreferenceStore();
final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position);
if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
super.run();
return;
}
// Check whether right hand character of caret is valid identifier start
if (Character.isJavaIdentifierStart(document.getChar(position))) {
int offset= 0;
int order= CollationElementIterator.NULLORDER;
short previous= Short.MAX_VALUE;
short next= Short.MAX_VALUE;
// Acquire collator for partition around caret
final String buffer= document.get(position, region.getOffset() + region.getLength() - position);
final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer);
// Iterate to first upper-case character
do {
// Check whether we reached end of word
offset= iterator.getOffset();
if (!Character.isJavaIdentifierPart(document.getChar(position + offset)))
throw new BadLocationException();
// Test next characters
order= iterator.next();
next= CollationElementIterator.tertiaryOrder(order);
if (next <= previous)
previous= next;
else
break;
} while (order != CollationElementIterator.NULLORDER);
// Check for leading underscores
position += offset;
if (Character.getType(document.getChar(position - 1)) != Character.CONNECTOR_PUNCTUATION) {
setCaretPosition(position);
getTextWidget().showSelection();
fireSelectionChanged();
return;
}
}
} catch (BadLocationException exception) {
// Use default behavior
}
super.run();
}
/**
* Sets the caret position to the sub-word boundary given with <code>position</code>.
*
* @param position Position where the action should move the caret
*/
protected abstract void setCaretPosition(int position);
}
/**
* Text navigation action to navigate to the next sub-word.
*
* @since 3.0
*/
protected class NavigateNextSubWordAction extends NextSubWordAction {
/**
* Creates a new navigate next sub-word action.
*/
public NavigateNextSubWordAction() {
super(ST.WORD_NEXT);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position));
}
}
/**
* Text operation action to delete the next sub-word.
*
* @since 3.0
*/
protected class DeleteNextSubWordAction extends NextSubWordAction {
/**
* Creates a new delete next sub-word action.
*/
public DeleteNextSubWordAction() {
super(ST.DELETE_WORD_NEXT);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
try {
viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$
} catch (BadLocationException exception) {
// Should not happen
}
}
}
/**
* Text operation action to select the next sub-word.
*
* @since 3.0
*/
protected class SelectNextSubWordAction extends NextSubWordAction {
/**
* Creates a new select next sub-word action.
*/
public SelectNextSubWordAction() {
super(ST.SELECT_WORD_NEXT);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed()) {
final Point selection= text.getSelection();
final int caret= text.getCaretOffset();
final int offset= modelOffset2WidgetOffset(viewer, position);
if (caret == selection.x)
text.setSelectionRange(selection.y, offset - selection.y);
else
text.setSelectionRange(selection.x, offset - selection.x);
}
}
}
/**
* Text navigation action to navigate to the previous sub-word.
*
* @since 3.0
*/
protected abstract class PreviousSubWordAction extends TextNavigationAction {
/** Collator to determine the sub-word boundaries */
private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance();
/**
* Creates a new previous sub-word action.
*
* @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST.
*/
protected PreviousSubWordAction(final int code) {
super(getSourceViewer().getTextWidget(), code);
// Only compare upper-/lower case
fCollator.setStrength(Collator.TERTIARY);
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
try {
final ISourceViewer viewer= getSourceViewer();
final IDocument document= viewer.getDocument();
int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()) - 1;
// Check whether we are in a java code partititon and the preference is enabled
final IPreferenceStore store= getPreferenceStore();
if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
super.run();
return;
}
// Ignore trailing white spaces
char character= document.getChar(position);
while (position > 0 && Character.isWhitespace(character)) {
--position;
character= document.getChar(position);
}
// Check whether left hand character of caret is valid identifier part
if (Character.isJavaIdentifierPart(character)) {
int offset= 0;
int order= CollationElementIterator.NULLORDER;
short previous= Short.MAX_VALUE;
short next= Short.MAX_VALUE;
// Acquire collator for partition around caret
final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position);
final String buffer= document.get(region.getOffset(), position - region.getOffset() + 1);
final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer);
// Iterate to first upper-case character
iterator.setOffset(buffer.length() - 1);
do {
// Check whether we reached begin of word or single upper-case start
offset= iterator.getOffset();
character= document.getChar(region.getOffset() + offset);
if (!Character.isJavaIdentifierPart(character))
throw new BadLocationException();
else if (Character.isUpperCase(character)) {
++offset;
break;
}
// Test next characters
order= iterator.previous();
next= CollationElementIterator.tertiaryOrder(order);
if (next <= previous)
previous= next;
else
break;
} while (order != CollationElementIterator.NULLORDER);
// Check left character for multiple upper-case characters
position= position - buffer.length() + offset - 1;
character= document.getChar(position);
while (position >= 0 && Character.isUpperCase(character))
character= document.getChar(--position);
setCaretPosition(position + 1);
getTextWidget().showSelection();
fireSelectionChanged();
return;
}
} catch (BadLocationException exception) {
// Use default behavior
}
super.run();
}
/**
* Sets the caret position to the sub-word boundary given with <code>position</code>.
*
* @param position Position where the action should move the caret
*/
protected abstract void setCaretPosition(int position);
}
/**
* Text navigation action to navigate to the previous sub-word.
*
* @since 3.0
*/
protected class NavigatePreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new navigate previous sub-word action.
*/
public NavigatePreviousSubWordAction() {
super(ST.WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position));
}
}
/**
* Text operation action to delete the previous sub-word.
*
* @since 3.0
*/
protected class DeletePreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new delete previous sub-word action.
*/
public DeletePreviousSubWordAction() {
super(ST.DELETE_WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
try {
viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$
} catch (BadLocationException exception) {
// Should not happen
}
}
}
/**
* Text operation action to select the previous sub-word.
*
* @since 3.0
*/
protected class SelectPreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new select previous sub-word action.
*/
public SelectPreviousSubWordAction() {
super(ST.SELECT_WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed()) {
final Point selection= text.getSelection();
final int caret= text.getCaretOffset();
final int offset= modelOffset2WidgetOffset(viewer, position);
if (caret == selection.x)
text.setSelectionRange(selection.y, offset - selection.y);
else
text.setSelectionRange(selection.x, offset - selection.x);
}
}
}
/**
* Quick format action to format the enclosing java element.
* <p>
* The quick format action works as follows:
* <ul>
* <li>If there is no selection and the caret is positioned on a Java element,
* only this element is formatted. If the element has some accompanying comment,
* then the comment is formatted as well.</li>
* <li>If the selection spans one or more partitions of the document, then all
* partitions covered by the selection are entirely formatted.</li>
* <p>
* Partitions at the end of the selection are not completed, except for comments.
*
* @since 3.0
*/
protected class QuickFormatAction extends Action {
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
final JavaSourceViewer viewer= (JavaSourceViewer) getSourceViewer();
if (viewer.isEditable()) {
final Point selection= viewer.rememberSelection();
try {
viewer.setRedraw(false);
final String type= TextUtilities.getContentType(viewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, selection.x);
if (type.equals(IDocument.DEFAULT_CONTENT_TYPE) && selection.y == 0) {
try {
final IJavaElement element= getElementAt(selection.x, true);
if (element != null && element.exists()) {
final int kind= element.getElementType();
if (kind == IJavaElement.TYPE || kind == IJavaElement.METHOD || kind == IJavaElement.INITIALIZER) {
final ISourceReference reference= (ISourceReference)element;
final ISourceRange range= reference.getSourceRange();
if (range != null) {
viewer.setSelectedRange(range.getOffset(), range.getLength());
viewer.doOperation(ISourceViewer.FORMAT);
}
}
}
} catch (JavaModelException exception) {
// Should not happen
}
} else {
viewer.setSelectedRange(selection.x, 1);
viewer.doOperation(ISourceViewer.FORMAT);
}
} catch (BadLocationException exception) {
// Can not happen
} finally {
viewer.setRedraw(true);
viewer.restoreSelection();
}
}
}
}
/**
* Internal activation listener.
* @since 3.0
*/
private class ActivationListener extends ShellAdapter {
/*
* @see org.eclipse.swt.events.ShellAdapter#shellActivated(org.eclipse.swt.events.ShellEvent)
*/
public void shellActivated(ShellEvent e) {
updateOccurrenceAnnotations();
}
/*
* @see org.eclipse.swt.events.ShellAdapter#shellDeactivated(org.eclipse.swt.events.ShellEvent)
*/
public void shellDeactivated(ShellEvent e) {
removeOccurrenceAnnotations();
}
}
/** Preference key for the link color */
protected final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR;
/** Preference key for matching brackets */
protected final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS;
/** Preference key for matching brackets color */
protected final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
/** Preference key for compiler task tags */
private final static String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS;
/** Preference key for browser like links */
private final static String BROWSER_LIKE_LINKS= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
/** Preference key for key modifier of browser like links */
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
/**
* Preference key for key modifier mask of 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.
*
* @since 2.1.1
*/
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' };
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/**
* The editor selection changed listener.
*
* @since 3.0
*/
private EditorSelectionChangedListener fEditorSelectionChangedListener;
/** The selection changed listener */
protected AbstractSelectionChangedListener fOutlineSelectionChangedListener= new OutlineSelectionChangedListener();
/** The editor's bracket matcher */
protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS);
/** This editor's encoding support */
private DefaultEncodingSupport fEncodingSupport;
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/** The preference property change listener for java core. */
private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener();
/**
* Indicates whether this editor is about to update any annotation views.
* @since 3.0
*/
private boolean fIsUpdatingAnnotationViews= false;
/**
* The marker that served as last target for a goto marker request.
* @since 3.0
*/
private IMarker fLastMarkerTarget= null;
protected CompositeActionGroup fActionGroups;
private CompositeActionGroup fContextMenuGroup;
/**
* Holds the current occurrence annotations.
* @since 3.0
*/
private Annotation[] fOccurrenceAnnotations= null;
/**
* Counts the number of background computation requests.
* @since 3.0
*/
private volatile int fComputeCount;
/**
* Tells whether all occurrences of the element at the
* current caret location are automatically marked in
* this editor.
* @since 3.0
*/
private boolean fMarkOccurrenceAnnotations;
/**
* The last element used to highlight its occurrences
* in this editor.
* @since 3.0
*/
private IBinding fOccurrenceAnnotationsTarget;
/**
* The internal shell activation listener for updating occurrences.
* @since 3.0
*/
private ActivationListener fActivationListener= new ActivationListener();
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @return the most narrow java element
*/
abstract protected IJavaElement getElementAt(int offset);
/**
* Returns the java element of this editor's input corresponding to the given IJavaElement
*/
abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
/**
* Sets the input of the editor's outline page.
*/
abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
/**
* Default constructor.
*/
public JavaEditor() {
super();
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools, this, IJavaPartitions.JAVA_PARTITIONING));
setRangeIndicator(new DefaultRangeIndicator());
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
setPreferenceStore(store);
setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" }); //$NON-NLS-1$
fMarkOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES);
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles);
StyledText text= viewer.getTextWidget();
text.addBidiSegmentListener(new BidiSegmentListener() {
public void lineGetSegments(BidiSegmentEvent event) {
event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
}
});
JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
// ensure source viewer decoration support has been created and configured
getSourceViewerDecorationSupport(viewer);
return viewer;
}
public final ISourceViewer getViewer() {
return getSourceViewer();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) {
return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.affectsBehavior(event);
}
/**
* Sets the outliner's context menu ID.
*/
protected void setOutlinerContextMenuId(String menuId) {
fOutlinerContextMenuId= menuId;
}
/**
* Returns the standard action group of this editor.
*/
protected ActionGroup getActionGroup() {
return fActionGroups;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/**
* Creates the outline page used with this editor.
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
fOutlineSelectionChangedListener.install(page);
setOutlinePageInput(page, getEditorInput());
return page;
}
/**
* Informs the editor that its outliner has been closed.
*/
public void outlinePageClosed() {
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage= null;
resetHighlightRange();
}
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
*/
protected void synchronizeOutlinePage(ISourceReference element) {
synchronizeOutlinePage(element, true);
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
* @param checkIfOutlinePageActive <code>true</code> if check for active outline page needs to be done
*/
protected void synchronizeOutlinePage(ISourceReference element, boolean checkIfOutlinePageActive) {
if (fOutlinePage != null && element != null && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
/**
* Synchronizes the outliner selection with the actual cursor
* position in the editor.
*/
public void synchronizeOutlinePageSelection() {
synchronizeOutlinePage(computeHighlightRangeSourceReference());
}
/*
* Get the desktop's StatusLineManager
*/
protected IStatusLineManager getStatusLineManager() {
IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
return null;
}
/*
* @see AbstractTextEditor#getAdapter(Class)
*/
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
if (fOutlinePage == null)
fOutlinePage= createOutlinePage();
return fOutlinePage;
}
if (IEncodingSupport.class.equals(required))
return fEncodingSupport;
if (required == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
}
};
}
return super.getAdapter(required);
}
protected void setSelection(ISourceReference reference, boolean moveCursor) {
ISelection selection= getSelectionProvider().getSelection();
if (selection instanceof TextSelection) {
TextSelection textSelection= (TextSelection) selection;
// PR 39995: [navigation] Forward history cleared after going back in navigation history:
// mark only in navigation history if the cursor is being moved (which it isn't if
// this is called from a PostSelectionEvent that should only update the magnet)
if (moveCursor && (textSelection.getOffset() != 0 || textSelection.getLength() != 0))
markInNavigationHistory();
}
if (reference != null) {
StyledText textWidget= null;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
textWidget= sourceViewer.getTextWidget();
if (textWidget == null)
return;
try {
ISourceRange range= null;
if (reference instanceof ILocalVariable) {
IJavaElement je= ((ILocalVariable)reference).getParent();
if (je instanceof ISourceReference)
range= ((ISourceReference)je).getSourceRange();
} else
range= reference.getSourceRange();
if (range == null)
return;
int offset= range.getOffset();
int length= range.getLength();
if (offset < 0 || length < 0)
return;
setHighlightRange(offset, length, moveCursor);
if (!moveCursor)
return;
offset= -1;
length= -1;
if (reference instanceof IMember) {
range= ((IMember) reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof ILocalVariable) {
range= ((ILocalVariable)reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof IImportDeclaration) {
String name= ((IImportDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
} else if (reference instanceof IPackageDeclaration) {
String name= ((IPackageDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
}
if (offset > -1 && length > 0) {
try {
textWidget.setRedraw(false);
sourceViewer.revealRange(offset, length);
sourceViewer.setSelectedRange(offset, length);
} finally {
textWidget.setRedraw(true);
}
markInNavigationHistory();
}
} catch (JavaModelException x) {
} catch (IllegalArgumentException x) {
}
} else if (moveCursor) {
resetHighlightRange();
markInNavigationHistory();
}
}
public void setSelection(IJavaElement element) {
if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) {
/*
* If the element is an ICompilationUnit this unit is either the input
* of this editor or not being displayed. In both cases, nothing should
* happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
*/
return;
}
IJavaElement corresponding= getCorrespondingElement(element);
if (corresponding instanceof ISourceReference) {
ISourceReference reference= (ISourceReference) corresponding;
// set hightlight range
setSelection(reference, true);
// set outliner selection
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(reference);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
}
protected void doSelectionChanged(SelectionChangedEvent event) {
ISourceReference reference= null;
ISelection selection= event.getSelection();
Iterator iter= ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (o instanceof ISourceReference) {
reference= (ISourceReference) o;
break;
}
}
if (!isActivePart() && JavaPlugin.getActivePage() != null)
JavaPlugin.getActivePage().bringToTop(this);
setSelection(reference, !isActivePart());
}
/*
* @see AbstractTextEditor#adjustHighlightRange(int, int)
*/
protected void adjustHighlightRange(int offset, int length) {
try {
IJavaElement element= getElementAt(offset);
while (element instanceof ISourceReference) {
ISourceRange range= ((ISourceReference) element).getSourceRange();
if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
setHighlightRange(range.getOffset(), range.getLength(), true);
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select((ISourceReference) element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
return;
}
element= element.getParent();
}
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
resetHighlightRange();
}
protected boolean isActivePart() {
IWorkbenchPart part= getActivePart();
return part != null && part.equals(this);
}
private boolean isJavaOutlinePageActive() {
IWorkbenchPart part= getActivePart();
return part instanceof ContentOutline && ((ContentOutline)part).getCurrentPage() == fOutlinePage;
}
private IWorkbenchPart getActivePart() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IPartService service= window.getPartService();
IWorkbenchPart part= service.getActivePart();
return part;
}
/*
* @see StatusTextEditor#getStatusHeader(IStatus)
*/
protected String getStatusHeader(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusHeader(status);
if (message != null)
return message;
}
return super.getStatusHeader(status);
}
/*
* @see StatusTextEditor#getStatusBanner(IStatus)
*/
protected String getStatusBanner(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusBanner(status);
if (message != null)
return message;
}
return super.getStatusBanner(status);
}
/*
* @see StatusTextEditor#getStatusMessage(IStatus)
*/
protected String getStatusMessage(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusMessage(status);
if (message != null)
return message;
}
return super.getStatusMessage(status);
}
/*
* @see AbstractTextEditor#doSetInput
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
if (fEncodingSupport != null)
fEncodingSupport.reset();
setOutlinePageInput(fOutlinePage, input);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
// cancel possible running computation
fMarkOccurrenceAnnotations= false;
fComputeCount++;
if (fActivationListener != null) {
Shell shell= getEditorSite().getShell();
if (shell != null && !shell.isDisposed())
shell.removeShellListener(fActivationListener);
fActivationListener= null;
}
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
if (fEncodingSupport != null) {
fEncodingSupport.dispose();
fEncodingSupport= null;
}
if (fPropertyChangeListener != null) {
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fBracketMatcher != null) {
fBracketMatcher.dispose();
fBracketMatcher= null;
}
if (fSelectionHistory != null) {
fSelectionHistory.dispose();
fSelectionHistory= null;
}
if (fEditorSelectionChangedListener != null) {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
super.dispose();
}
protected void createActions() {
super.createActions();
ActionGroup oeg, ovg, jsg, sg;
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
oeg= new OpenEditorActionGroup(this),
sg= new ShowActionGroup(this),
ovg= new OpenViewActionGroup(this),
jsg= new JavaSearchActionGroup(this)
});
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg});
ResourceAction resAction= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
resAction= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
resAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC);
setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
WorkbenchHelp.setHelp(resAction, IJavaHelpContextIds.SHOW_JAVADOC_ACTION);
Action action= new GotoMatchingBracketAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
fEncodingSupport= new DefaultEncodingSupport();
fEncodingSupport.initialize(this);
fSelectionHistory= new SelectionHistory(this);
action= new StructureSelectEnclosingAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING);
setAction(StructureSelectionAction.ENCLOSING, action);
action= new StructureSelectNextAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT);
setAction(StructureSelectionAction.NEXT, action);
action= new StructureSelectPreviousAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS);
setAction(StructureSelectionAction.PREVIOUS, action);
StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory);
historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST);
setAction(StructureSelectionAction.HISTORY, historyAction);
fSelectionHistory.setHistoryAction(historyAction);
action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
action= new QuickFormatAction();
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.QUICK_FORMAT);
setAction(IJavaEditorActionDefinitionIds.QUICK_FORMAT, action);
action= new RemoveOccurrenceAnnotations(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS);
setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$
}
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
String property= event.getProperty();
if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
Object value= event.getNewValue();
if (value instanceof Integer) {
sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
} else if (value instanceof String) {
sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
}
return;
}
if (isJavaEditorHoverProperty(property))
updateHoverBehavior();
if (BROWSER_LIKE_LINKS.equals(property)) {
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
else
disableBrowserLikeLinks();
return;
}
if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
if ((event.getNewValue() instanceof Boolean) && ((Boolean)event.getNewValue()).booleanValue())
fEditorSelectionChangedListener.selectionChanged();
return;
}
if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
Boolean disable= (Boolean) event.getNewValue();
configureInsertMode(OVERWRITE, !disable.booleanValue());
}
}
if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
fMarkOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue();
if (!fMarkOccurrenceAnnotations) {
fComputeCount++;
removeOccurrenceAnnotations();
}
}
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
/**
* Initializes the given viewer's colors.
*
* @param viewer the viewer to be initialized
* @since 3.0
*/
protected void initializeViewerColors(ISourceViewer viewer) {
// is handled by JavaSourceViewer
}
private boolean isJavaEditorHoverProperty(String property) {
return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
}
/**
* Return whether the browser like links should be enabled
* according to the preference store settings.
* @return <code>true</code> if the browser like links should be enabled
*/
private boolean isBrowserLikeLinks() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(BROWSER_LIKE_LINKS);
}
/**
* Enables browser like links.
*/
private void enableBrowserLikeLinks() {
if (fMouseListener == null) {
fMouseListener= new MouseClickListener();
fMouseListener.install();
}
}
/**
* Disables browser like links.
*/
private void disableBrowserLikeLinks() {
if (fMouseListener != null) {
fMouseListener.uninstall();
fMouseListener= null;
}
}
/**
* Handles a property change event describing a change
* of the java core's preferences and updates the preference
* related editor properties.
*
* @param event the property change event
*/
protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
if (COMPILER_TASK_TAGS.equals(event.getProperty())) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event.getNewValue())))
sourceViewer.invalidateTextPresentation();
}
}
/**
* Returns a segmentation of the line of the given viewer's input document appropriate for
* bidi rendering. The default implementation returns only the string literals of a java code
* line as segments.
*
* @param viewer the text viewer
* @param lineOffset the offset of the line
* @return the line's bidi segmentation
* @throws BadLocationException in case lineOffset is not valid in document
*/
public static int[] getBidiLineSegments(ITextViewer viewer, int lineOffset) throws BadLocationException {
IDocument document= viewer.getDocument();
if (document == null)
return null;
IRegion line= document.getLineInformationOfOffset(lineOffset);
ITypedRegion[] linePartitioning= TextUtilities.computePartitioning(document, IJavaPartitions.JAVA_PARTITIONING, lineOffset, line.getLength());
List segmentation= new ArrayList();
for (int i= 0; i < linePartitioning.length; i++) {
if (IJavaPartitions.JAVA_STRING.equals(linePartitioning[i].getType()))
segmentation.add(linePartitioning[i]);
}
if (segmentation.size() == 0)
return null;
int size= segmentation.size();
int[] segments= new int[size * 2 + 1];
int j= 0;
for (int i= 0; i < size; i++) {
ITypedRegion segment= (ITypedRegion) segmentation.get(i);
if (i == 0)
segments[j++]= 0;
int offset= segment.getOffset() - lineOffset;
if (offset > segments[j - 1])
segments[j++]= offset;
if (offset + segment.getLength() >= line.getLength())
break;
segments[j++]= offset + segment.getLength();
}
if (j < segments.length) {
int[] result= new int[j];
System.arraycopy(segments, 0, result, 0, j);
segments= result;
}
return segments;
}
/**
* Returns a segmentation of the given line appropriate for bidi rendering. The default
* implementation returns only the string literals of a java code line as segments.
*
* @param lineOffset the offset of the line
* @param line the content of the line
* @return the line's bidi segmentation
*/
protected int[] getBidiLineSegments(int widgetLineOffset, String line) {
if (line != null && line.length() > 0) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null) {
int lineOffset;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
lineOffset= extension.widgetOffset2ModelOffset(widgetLineOffset);
} else {
IRegion visible= sourceViewer.getVisibleRegion();
lineOffset= visible.getOffset() + widgetLineOffset;
}
try {
return getBidiLineSegments(sourceViewer, lineOffset);
} catch (BadLocationException x) {
// don't segment line in this case
}
}
}
return null;
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
*/
protected void updatePropertyDependentActions() {
super.updatePropertyDependentActions();
if (fEncodingSupport != null)
fEncodingSupport.reset();
}
/*
* Update the hovering behavior depending on the preferences.
*/
private void updateHoverBehavior() {
SourceViewerConfiguration configuration= getSourceViewerConfiguration();
String[] types= configuration.getConfiguredContentTypes(getSourceViewer());
for (int i= 0; i < types.length; i++) {
String t= types[i];
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension2) {
// Remove existing hovers
((ITextViewerExtension2)sourceViewer).removeTextHovers(t);
int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
if (stateMasks != null) {
for (int j= 0; j < stateMasks.length; j++) {
int stateMask= stateMasks[j];
ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask);
}
} else {
ITextHover textHover= configuration.getTextHover(sourceViewer, t);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
} else
sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
}
}
/*
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return getEditorInput().getAdapter(IJavaElement.class);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
*/
protected void doSetSelection(ISelection selection) {
super.doSetSelection(selection);
synchronizeOutlinePageSelection();
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.addPropertyChangeListener(fPropertyChangeListener);
IInformationControlCreator informationControlCreator= new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell shell) {
boolean cutDown= false;
int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
return new DefaultInformationControl(shell, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
}
};
fInformationPresenter= new InformationPresenter(informationControlCreator);
fInformationPresenter.setSizeConstraints(60, 10, true, true);
fInformationPresenter.install(getSourceViewer());
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
configureInsertMode(OVERWRITE, false);
getEditorSite().getShell().addShellListener(fActivationListener);
}
protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
support.setCharacterPairMatcher(fBracketMatcher);
support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
super.configureSourceViewerDecorationSupport(support);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#gotoMarker(org.eclipse.core.resources.IMarker)
*/
public void gotoMarker(IMarker marker) {
fLastMarkerTarget= marker;
if (!fIsUpdatingAnnotationViews)
super.gotoMarker(marker);
}
/**
* Jumps to the next enabled annotation according to the given direction.
* An annotation type is enabled if it is configured to be in the
* Next/Previous tool bar drop down menu and if it is checked.
*
* @param forward <code>true</code> if search direction is forward, <code>false</code> if backward
*/
public void gotoAnnotation(boolean forward) {
ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection();
Position position= new Position(0, 0);
if (false /* delayed - see bug 18316 */) {
getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
selectAndReveal(position.getOffset(), position.getLength());
} else /* no delay - see bug 18316 */ {
Annotation annotation= getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
setStatusLineErrorMessage(null);
setStatusLineMessage(null);
if (annotation != null) {
updateAnnotationViews(annotation);
selectAndReveal(position.getOffset(), position.getLength());
setStatusLineMessage(annotation.getText());
}
}
}
/**
* Updates the annotation views that show the given annotation.
*
* @param annotation the annotation
*/
private void updateAnnotationViews(Annotation annotation) {
IMarker marker= null;
if (annotation instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) annotation).getMarker();
else if (annotation instanceof IJavaAnnotation) {
Iterator e= ((IJavaAnnotation) annotation).getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null && !marker.equals(fLastMarkerTarget)) {
try {
boolean isProblem= marker.isSubtypeOf(IMarker.PROBLEM);
IWorkbenchPage page= getSite().getPage();
IViewPart view= page.findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW: IPageLayout.ID_TASK_LIST); //$NON-NLS-1$ //$NON-NLS-2$
if (view != null) {
Method method= view.getClass().getMethod("setSelection", new Class[] { IStructuredSelection.class, boolean.class}); //$NON-NLS-1$
method.invoke(view, new Object[] {new StructuredSelection(marker), Boolean.TRUE });
}
} catch (CoreException x) {
} catch (NoSuchMethodException x) {
} catch (IllegalAccessException x) {
} catch (InvocationTargetException x) {
}
// ignore exceptions, don't update any of the lists, just set statusline
}
}
/**
* Finds and marks occurrence annotations.
*
* @since 3.0
*/
class OccurrencesFinder implements Runnable, IDocumentListener {
private int fCount;
private IDocument fDocument;
private ITextSelection fSelection;
private boolean fCancelled= false;
public OccurrencesFinder(int count, IDocument document, ITextSelection selection) {
fCount= count;
fDocument= document;
fSelection= selection;
fDocument.addDocumentListener(this);
}
private boolean isCancelled() {
return fCount != fComputeCount || fCancelled;
}
/*
* @see java.lang.Runnable#run()
*/
public void run() {
try {
if (isCancelled())
return;
FindOccurrencesEngine engine= FindOccurrencesEngine.create(getInputJavaElement());
if (engine == null)
return;
List matches= new ArrayList();
try {
IBinding newTarget= engine.resolveTarget(fSelection.getOffset(), fSelection.getLength());
if (isCancelled())
return;
if (newTarget == null)
// Use previous element as target
newTarget= fOccurrenceAnnotationsTarget;
// We no longer execute the code below because we want the
// occurrence annotations be in sync with the code.
// Should flickering be a problem we could compare the new
// matchers with the occurrence annotations and only apply
// the changes.
// if (newTarget == null || fOccurrenceAnnotationsTarget != null && Bindings.equals(fOccurrenceAnnotationsTarget, newTarget)) {
// engine.clearTarget();
// return;
// }
fOccurrenceAnnotationsTarget= newTarget;
// Find occurrences
matches= engine.findOccurrences(fOccurrenceAnnotationsTarget);
} catch (JavaModelException e) {
JavaPlugin.log(e);
return;
}
if (matches == null || matches.isEmpty())
return;
if (isCancelled())
return;
if (isCancelled())
return;
ITextViewer textViewer= getViewer();
if (textViewer == null)
return;
IDocument document= textViewer.getDocument();
if (document == null)
return;
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider == null)
return;
IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
if (annotationModel == null)
return;
// Add occurrence annotations
Map annotationMap= new HashMap(matches.size());
for (Iterator each= matches.iterator(); each.hasNext();) {
if (isCancelled())
return;
ASTNode node= (ASTNode) each.next();
if (node == null)
continue;
String message;
// Create & add annotation
try {
message= document.get(node.getStartPosition(), node.getLength());
} catch (BadLocationException ex) {
// Skip this match
continue;
}
annotationMap.put(
new Annotation("org.eclipse.search.results", false, message),
new Position(node.getStartPosition(), node.getLength()));
}
if (isCancelled())
return;
synchronized (annotationModel) {
if (annotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap);
} else {
removeOccurrenceAnnotations();
Iterator iter= annotationMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mapEntry= (Map.Entry)iter.next();
annotationModel.addAnnotation((Annotation)mapEntry.getKey(), (Position)mapEntry.getValue());
}
}
fOccurrenceAnnotations= (Annotation[])annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
}
} finally {
fDocument.removeDocumentListener(this);
}
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentAboutToBeChanged(DocumentEvent event) {
fCancelled= true;
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
}
}
/**
* Updates the occurrences annotations based
* on the current selection.
*
* @since 3.0
*/
protected void updateOccurrenceAnnotations() {
if (!fMarkOccurrenceAnnotations)
return;
IDocument document= getSourceViewer().getDocument();
if (document == null)
return;
OccurrencesFinder finder= new OccurrencesFinder(++fComputeCount, document, (ITextSelection) getSelectionProvider().getSelection());
Thread thread= new Thread(finder, "Occurrences Marker"); //$NON-NLS-1$
thread.setDaemon(true);
thread.start();
}
void removeOccurrenceAnnotations() {
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider == null)
return;
IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
if (annotationModel == null || fOccurrenceAnnotations == null)
return;
synchronized (annotationModel) {
if (annotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
} else {
for (int i= 0, length= fOccurrenceAnnotations.length; i < length; i++)
annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
}
fOccurrenceAnnotations= null;
}
}
/**
* Returns the Java element wrapped by this editors input.
*
* @return the Java element wrapped by this editors input.
* @since 3.0
*/
abstract protected IJavaElement getInputJavaElement();
protected void updateStatusLine() {
ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection();
Annotation annotation= getAnnotation(selection.getOffset(), selection.getLength());
setStatusLineErrorMessage(null);
setStatusLineMessage(null);
if (annotation != null) {
try {
fIsUpdatingAnnotationViews= true;
updateAnnotationViews(annotation);
} finally {
fIsUpdatingAnnotationViews= false;
}
if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation) annotation).isProblem())
setStatusLineMessage(annotation.getText());
}
}
/**
* Jumps to the matching bracket.
*/
public void gotoMatchingBracket() {
ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
if (document == null)
return;
IRegion selection= getSignedSelection(sourceViewer);
int selectionLength= Math.abs(selection.getLength());
if (selectionLength > 1) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
// #26314
int sourceCaretOffset= selection.getOffset() + selection.getLength();
if (isSurroundedByBrackets(document, sourceCaretOffset))
sourceCaretOffset -= selection.getLength();
IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
if (region == null) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
int offset= region.getOffset();
int length= region.getLength();
if (length < 1)
return;
int anchor= fBracketMatcher.getAnchor();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset + 1: offset + length;
boolean visible= false;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion= sourceViewer.getVisibleRegion();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
}
if (!visible) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
if (selection.getLength() < 0)
targetOffset -= selection.getLength();
sourceViewer.setSelectedRange(targetOffset, selection.getLength());
sourceViewer.revealRange(targetOffset, selection.getLength());
}
/**
* Sets the given message as error message to this editor's status line.
*
* @param msg message to be set
*/
protected void setStatusLineErrorMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
}
/**
* Sets the given message as message to this editor's status line.
*
* @param msg message to be set
* @since 3.0
*/
protected void setStatusLineMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(false, msg, null);
}
private static IRegion getSignedSelection(ITextViewer viewer) {
StyledText text= viewer.getTextWidget();
int caretOffset= text.getCaretOffset();
Point selection= text.getSelection();
// caret left
int offset, length;
if (caretOffset == selection.x) {
offset= selection.y;
length= selection.x - selection.y;
// caret right
} else {
offset= selection.x;
length= selection.y - selection.x;
}
return new Region(offset, length);
}
private static boolean isBracket(char character) {
for (int i= 0; i != BRACKETS.length; ++i)
if (character == BRACKETS[i])
return true;
return false;
}
private static boolean isSurroundedByBrackets(IDocument document, int offset) {
if (offset == 0 || offset == document.getLength())
return false;
try {
return
isBracket(document.getChar(offset - 1)) &&
isBracket(document.getChar(offset));
} catch (BadLocationException e) {
return false;
}
}
/**
* Returns the annotation closest to the given range respecting the given
* direction. If an annotation is found, the annotations current position
* is copied into the provided annotation position.
*
* @param offset the region offset
* @param length the region length
* @param forward <code>true</code> for forwards, <code>false</code> for backward
* @param annotationPosition the position of the found annotation
* @return the found annotation
*/
private Annotation getNextAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) {
Annotation nextAnnotation= null;
Position nextAnnotationPosition= null;
Annotation containingAnnotation= null;
Position containingAnnotationPosition= null;
boolean currentAnnotation= false;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= Integer.MAX_VALUE;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true, true);
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation)a).hasOverlay() || !isNavigationTarget(a))
continue;
Position p= model.getPosition(a);
if (p == null)
continue;
if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || p.includes(offset)) {
if (containingAnnotation == null || (forward && p.length >= containingAnnotationPosition.length || !forward && p.length >= containingAnnotationPosition.length)) {
containingAnnotation= a;
containingAnnotationPosition= p;
currentAnnotation= p.length == length;
}
} else {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument + currentDistance;
if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
} else {
currentDistance= offset + length - (p.getOffset() + p.length);
if (currentDistance < 0)
currentDistance= endOfDocument + currentDistance;
if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
}
}
}
if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) {
annotationPosition.setOffset(containingAnnotationPosition.getOffset());
annotationPosition.setLength(containingAnnotationPosition.getLength());
return containingAnnotation;
}
if (nextAnnotationPosition != null) {
annotationPosition.setOffset(nextAnnotationPosition.getOffset());
annotationPosition.setLength(nextAnnotationPosition.getLength());
}
return nextAnnotation;
}
/**
* Returns the annotation overlapping with the given range or <code>null</code>.
*
* @param offset the region offset
* @param length the region length
* @return the found annotation or <code>null</code>
* @since 3.0
*/
private Annotation getAnnotation(int offset, int length) {
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true, true);
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if (!isNavigationTarget(a))
continue;
Position p= model.getPosition(a);
if (p != null && p.overlapsWith(offset, length))
return a;
}
return null;
}
/**
* Returns whether the given annotation is configured as a target for the
* "Go to Next/Previous Annotation" actions
*
* @param annotation the annotation
* @return <code>true</code> if this is a target, <code>false</code>
* otherwise
* @since 3.0
*/
private boolean isNavigationTarget(Annotation annotation) {
Preferences preferences= Platform.getPlugin("org.eclipse.ui.editors").getPluginPreferences(); //$NON-NLS-1$
AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(annotation);
// See bug 41689
// String key= forward ? preference.getIsGoToNextNavigationTargetKey() : preference.getIsGoToPreviousNavigationTargetKey();
String key= preference == null ? null : preference.getIsGoToNextNavigationTargetKey();
return (key != null && preferences.getBoolean(key));
}
/**
* Computes and returns the source reference that includes the caret and
* serves as provider for the outline page selection and the editor range
* indication.
*
* @return the computed source reference
* @since 3.0
*/
protected ISourceReference computeHighlightRangeSourceReference() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return null;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return null;
int caret= 0;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3)sourceViewer;
caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} else {
int offset= sourceViewer.getVisibleRegion().getOffset();
caret= offset + styledText.getCaretOffset();
}
IJavaElement element= getElementAt(caret, false);
if ( !(element instanceof ISourceReference))
return null;
if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
IImportDeclaration declaration= (IImportDeclaration) element;
IImportContainer container= (IImportContainer) declaration.getParent();
ISourceRange srcRange= null;
try {
srcRange= container.getSourceRange();
} catch (JavaModelException e) {
}
if (srcRange != null && srcRange.getOffset() == caret)
return container;
}
return (ISourceReference) element;
}
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @param reconcile <code>true</code> if editor input should be reconciled in advance
* @return the most narrow java element
* @since 3.0
*/
protected IJavaElement getElementAt(int offset, boolean reconcile) {
return getElementAt(offset);
}
/*
* @see org.eclipse.ui.texteditor.ExtendedTextEditor#createChangeHover()
*/
protected LineChangeHover createChangeHover() {
return new JavaChangeHover(IJavaPartitions.JAVA_PARTITIONING);
}
protected boolean isPrefQuickDiffAlwaysOn() {
return false; // never show change ruler for the non-editable java editor. Overridden in subclasses like CompilationUnitEditor
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions()
*/
protected void createNavigationActions() {
super.createNavigationActions();
final StyledText textWidget= getSourceViewer().getTextWidget();
IAction action= new SmartLineStartAction(textWidget, false);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START);
setAction(ITextEditorActionDefinitionIds.LINE_START, action);
action= new SmartLineStartAction(textWidget, true);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START);
setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action);
action= new NavigatePreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS);
setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL);
action= new NavigateNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT);
setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL);
action= new DeletePreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD);
setAction(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.BS, SWT.NULL);
action= new DeleteNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD);
setAction(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.DEL, SWT.NULL);
action= new SelectPreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS);
setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL);
action= new SelectNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT);
setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.