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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
46,329 |
Bug 46329 PasteActionTest#test2 failts
|
N20031109 After converting to RCP the above test started to fail
|
resolved fixed
|
997ac85
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-13T15:25:41Z | 2003-11-09T20:33:20Z |
extension/org/eclipse/jdt/internal/corext/dom/ASTRewrite.java
| |
46,329 |
Bug 46329 PasteActionTest#test2 failts
|
N20031109 After converting to RCP the above test started to fail
|
resolved fixed
|
997ac85
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-13T15:25:41Z | 2003-11-09T20:33:20Z |
org.eclipse.jdt.ui/core
| |
46,329 |
Bug 46329 PasteActionTest#test2 failts
|
N20031109 After converting to RCP the above test started to fail
|
resolved fixed
|
997ac85
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-13T15:25:41Z | 2003-11-09T20:33:20Z |
extension/org/eclipse/jdt/internal/corext/dom/ListRewriteEvent.java
| |
46,329 |
Bug 46329 PasteActionTest#test2 failts
|
N20031109 After converting to RCP the above test started to fail
|
resolved fixed
|
997ac85
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-13T15:25:41Z | 2003-11-09T20:33:20Z |
org.eclipse.jdt.ui/core
| |
46,329 |
Bug 46329 PasteActionTest#test2 failts
|
N20031109 After converting to RCP the above test started to fail
|
resolved fixed
|
997ac85
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-13T15:25:41Z | 2003-11-09T20:33:20Z |
extension/org/eclipse/jdt/internal/corext/dom/TokenScanner.java
| |
46,377 |
Bug 46377 [misc] Save not working for linked resources in Java editor
|
Trying to open a java file stored in a linked folder, results in error message "Java editor could not initialize" and no editor is opened. Other functions like compiling or comparing work fine with files in a linked folder. In previous build of Eclipse the Java editor used to work fine on files in linked folder. The build I have found this bug in is the M4.
|
verified fixed
|
0c7fcb5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-13T19:01:51Z | 2003-11-10T21:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/filebuffers/DocumentAdapter2.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.filebuffers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.filebuffers.FileBuffers;
import org.eclipse.core.filebuffers.ITextFileBuffer;
import org.eclipse.core.filebuffers.ITextFileBufferManager;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultLineTracker;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jdt.core.BufferChangedEvent;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.IBufferChangedListener;
import org.eclipse.jdt.core.IOpenable;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Adapts <code>IDocument</code> to <code>IBuffer</code>. Uses the
* same algorithm as the text widget to determine the buffer's line delimiter.
* All text inserted into the buffer is converted to this line delimiter.
* This class is <code>public</code> for test purposes only.
*/
public class DocumentAdapter2 implements IBuffer, IDocumentListener {
/**
* Internal implementation of a NULL instanceof IBuffer.
*/
static private class NullBuffer implements IBuffer {
public void addBufferChangedListener(IBufferChangedListener listener) {}
public void append(char[] text) {}
public void append(String text) {}
public void close() {}
public char getChar(int position) { return 0; }
public char[] getCharacters() { return null; }
public String getContents() { return null; }
public int getLength() { return 0; }
public IOpenable getOwner() { return null; }
public String getText(int offset, int length) { return null; }
public IResource getUnderlyingResource() { return null; }
public boolean hasUnsavedChanges() { return false; }
public boolean isClosed() { return false; }
public boolean isReadOnly() { return true; }
public void removeBufferChangedListener(IBufferChangedListener listener) {}
public void replace(int position, int length, char[] text) {}
public void replace(int position, int length, String text) {}
public void save(IProgressMonitor progress, boolean force) throws JavaModelException {}
public void setContents(char[] contents) {}
public void setContents(String contents) {}
}
/** NULL implementing <code>IBuffer</code> */
public final static IBuffer NULL= new NullBuffer();
/**
* Executes a document set content call in the ui thread.
*/
protected class DocumentSetCommand implements Runnable {
private String fContents;
public void run() {
fDocument.set(fContents);
}
public void set(String contents) {
fContents= contents;
Display.getDefault().syncExec(this);
}
}
/**
* Executes a document replace call in the ui thread.
*/
protected class DocumentReplaceCommand implements Runnable {
private int fOffset;
private int fLength;
private String fText;
public void run() {
try {
fDocument.replace(fOffset, fLength, fText);
} catch (BadLocationException x) {
// ignore
}
}
public void replace(int offset, int length, String text) {
fOffset= offset;
fLength= length;
fText= text;
Display.getDefault().syncExec(this);
}
}
private static final boolean DEBUG_LINE_DELIMITERS= true;
private IOpenable fOwner;
private IFile fFile;
private ITextFileBuffer fTextFileBuffer;
private IDocument fDocument;
private DocumentSetCommand fSetCmd= new DocumentSetCommand();
private DocumentReplaceCommand fReplaceCmd= new DocumentReplaceCommand();
private Set fLegalLineDelimiters;
private List fBufferListeners= new ArrayList(3);
private IStatus fStatus;
/**
* This method is <code>public</code> for test purposes only.
*/
public DocumentAdapter2(IOpenable owner, IFile file) {
fOwner= owner;
fFile= file;
initialize();
}
private void initialize() {
ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
IPath location= fFile.getLocation();
try {
manager.connect(location, new NullProgressMonitor());
fTextFileBuffer= manager.getTextFileBuffer(location);
fDocument= fTextFileBuffer.getDocument();
} catch (CoreException x) {
fStatus= x.getStatus();
fDocument= manager.createEmptyDocument(location);
}
fDocument.addPrenotifiedDocumentListener(this);
}
/**
* Returns the status of this document adapter.
*/
public IStatus getStatus() {
if (fStatus != null)
return fStatus;
if (fTextFileBuffer != null)
return fTextFileBuffer.getStatus();
return null;
}
/**
* Returns the adapted document.
*
* @return the adapted document
*/
public IDocument getDocument() {
return fDocument;
}
/*
* @see IBuffer#addBufferChangedListener(IBufferChangedListener)
*/
public void addBufferChangedListener(IBufferChangedListener listener) {
Assert.isNotNull(listener);
if (!fBufferListeners.contains(listener))
fBufferListeners.add(listener);
}
/*
* @see IBuffer#removeBufferChangedListener(IBufferChangedListener)
*/
public void removeBufferChangedListener(IBufferChangedListener listener) {
Assert.isNotNull(listener);
fBufferListeners.remove(listener);
}
/*
* @see IBuffer#append(char[])
*/
public void append(char[] text) {
append(new String(text));
}
/*
* @see IBuffer#append(String)
*/
public void append(String text) {
if (DEBUG_LINE_DELIMITERS) {
validateLineDelimiters(text);
}
fReplaceCmd.replace(fDocument.getLength(), 0, text);
}
/*
* @see IBuffer#close()
*/
public void close() {
if (isClosed())
return;
IDocument d= fDocument;
fDocument= null;
d.removePrenotifiedDocumentListener(this);
if (fTextFileBuffer != null) {
ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
try {
manager.disconnect(fTextFileBuffer.getLocation(), new NullProgressMonitor());
} catch (CoreException x) {
// ignore
}
fTextFileBuffer= null;
}
fireBufferChanged(new BufferChangedEvent(this, 0, 0, null));
fBufferListeners.clear();
}
/*
* @see IBuffer#getChar(int)
*/
public char getChar(int position) {
try {
return fDocument.getChar(position);
} catch (BadLocationException x) {
throw new ArrayIndexOutOfBoundsException();
}
}
/*
* @see IBuffer#getCharacters()
*/
public char[] getCharacters() {
String content= getContents();
return content == null ? null : content.toCharArray();
}
/*
* @see IBuffer#getContents()
*/
public String getContents() {
return fDocument.get();
}
/*
* @see IBuffer#getLength()
*/
public int getLength() {
return fDocument.getLength();
}
/*
* @see IBuffer#getOwner()
*/
public IOpenable getOwner() {
return fOwner;
}
/*
* @see IBuffer#getText(int, int)
*/
public String getText(int offset, int length) {
try {
return fDocument.get(offset, length);
} catch (BadLocationException x) {
throw new ArrayIndexOutOfBoundsException();
}
}
/*
* @see IBuffer#getUnderlyingResource()
*/
public IResource getUnderlyingResource() {
return fFile;
}
/*
* @see IBuffer#hasUnsavedChanges()
*/
public boolean hasUnsavedChanges() {
return fTextFileBuffer != null ? fTextFileBuffer.isDirty() : false;
}
/*
* @see IBuffer#isClosed()
*/
public boolean isClosed() {
return fDocument == null;
}
/*
* @see IBuffer#isReadOnly()
*/
public boolean isReadOnly() {
IResource resource= getUnderlyingResource();
return resource == null ? true : resource.isReadOnly();
}
/*
* @see IBuffer#replace(int, int, char[])
*/
public void replace(int position, int length, char[] text) {
replace(position, length, new String(text));
}
/*
* @see IBuffer#replace(int, int, String)
*/
public void replace(int position, int length, String text) {
if (DEBUG_LINE_DELIMITERS) {
validateLineDelimiters(text);
}
fReplaceCmd.replace(position, length, text);
}
/*
* @see IBuffer#save(IProgressMonitor, boolean)
*/
public void save(IProgressMonitor progress, boolean force) throws JavaModelException {
try {
if (fTextFileBuffer != null)
fTextFileBuffer.commit(progress, force);
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
/*
* @see IBuffer#setContents(char[])
*/
public void setContents(char[] contents) {
setContents(new String(contents));
}
/*
* @see IBuffer#setContents(String)
*/
public void setContents(String contents) {
int oldLength= fDocument.getLength();
if (contents == null) {
if (oldLength != 0)
fSetCmd.set(""); //$NON-NLS-1$
} else {
// set only if different
if (DEBUG_LINE_DELIMITERS) {
validateLineDelimiters(contents);
}
if (!contents.equals(fDocument.get()))
fSetCmd.set(contents);
}
}
private void validateLineDelimiters(String contents) {
if (fLegalLineDelimiters == null) {
// collect all line delimiters in the document
HashSet existingDelimiters= new HashSet();
for (int i= fDocument.getNumberOfLines() - 1; i >= 0; i-- ) {
try {
String curr= fDocument.getLineDelimiter(i);
if (curr != null) {
existingDelimiters.add(curr);
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
if (existingDelimiters.isEmpty()) {
return; // first insertion of a line delimiter: no test
}
fLegalLineDelimiters= existingDelimiters;
}
DefaultLineTracker tracker= new DefaultLineTracker();
tracker.set(contents);
int lines= tracker.getNumberOfLines();
if (lines <= 1)
return;
for (int i= 0; i < lines; i++) {
try {
String curr= tracker.getLineDelimiter(i);
if (curr != null && !fLegalLineDelimiters.contains(curr)) {
StringBuffer buf= new StringBuffer("New line delimiter added to new code: "); //$NON-NLS-1$
for (int k= 0; k < curr.length(); k++) {
buf.append(String.valueOf((int) curr.charAt(k)));
}
JavaPlugin.log(new Exception(buf.toString()));
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
}
/*
* @see IDocumentListener#documentAboutToBeChanged(DocumentEvent)
*/
public void documentAboutToBeChanged(DocumentEvent event) {
// there is nothing to do here
}
/*
* @see IDocumentListener#documentChanged(DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
fireBufferChanged(new BufferChangedEvent(this, event.getOffset(), event.getLength(), event.getText()));
}
private void fireBufferChanged(BufferChangedEvent event) {
if (fBufferListeners != null && fBufferListeners.size() > 0) {
Iterator e= new ArrayList(fBufferListeners).iterator();
while (e.hasNext())
((IBufferChangedListener) e.next()).bufferChanged(event);
}
}
}
|
46,088 |
Bug 46088 Create method quick fix declares Object as return type [quick fix]
|
When you write the following code Bla var = getMyBla(); and press Ctrl-1, you can have the method "getMyBla" created. However, if the type Bla is not (yet) known, the method gets declared as private Object getMyBla() { ... } If you press Ctrl-1 again, the import for Bla is added. If the order of the two quickfixes was reversed, you'd get the correct method declaration.
|
resolved fixed
|
d5ef949
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-13T23:16:12Z | 2003-11-05T11:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NewMethodCompletionProposal.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.NamingConventions;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.ui.CodeGeneration;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class NewMethodCompletionProposal extends LinkedCorrectionProposal {
private static final String KEY_NAME= "name"; //$NON-NLS-1$
private static final String KEY_TYPE= "type"; //$NON-NLS-1$
private ASTNode fNode; // MethodInvocation, ConstructorInvocation, SuperConstructorInvocation, ClassInstanceCreation, SuperMethodInvocation
private List fArguments;
private ITypeBinding fSenderBinding;
public NewMethodCompletionProposal(String label, ICompilationUnit targetCU, ASTNode invocationNode, List arguments, ITypeBinding binding, int relevance, Image image) {
super(label, targetCU, null, relevance, image);
fNode= invocationNode;
fArguments= arguments;
fSenderBinding= binding;
}
protected ASTRewrite getRewrite() throws CoreException {
CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fNode);
ASTNode typeDecl= astRoot.findDeclaringNode(fSenderBinding);
ASTNode newTypeDecl= null;
boolean isInDifferentCU;
if (typeDecl != null) {
isInDifferentCU= false;
newTypeDecl= typeDecl;
} else {
isInDifferentCU= true;
astRoot= AST.parseCompilationUnit(getCompilationUnit(), true);
newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
}
if (newTypeDecl != null) {
ASTRewrite rewrite= new ASTRewrite(astRoot);
List members;
if (fSenderBinding.isAnonymous()) {
members= ((AnonymousClassDeclaration) newTypeDecl).bodyDeclarations();
} else {
members= ((TypeDeclaration) newTypeDecl).bodyDeclarations();
}
MethodDeclaration newStub= getStub(rewrite, newTypeDecl);
if (isConstructor()) {
members.add(findConstructorInsertIndex(members), newStub);
} else if (!isInDifferentCU) {
members.add(findMethodInsertIndex(members, fNode.getStartPosition()), newStub);
} else {
members.add(newStub);
}
rewrite.markAsInserted(newStub);
if (!isInDifferentCU) {
Name invocationName= getInvocationName();
if (invocationName != null) {
markAsLinked(rewrite, invocationName, true, KEY_NAME);
}
}
markAsLinked(rewrite, newStub.getName(), false, KEY_NAME); //$NON-NLS-1$
if (!newStub.isConstructor()) {
markAsLinked(rewrite, newStub.getReturnType(), false, KEY_TYPE); //$NON-NLS-1$
}
return rewrite;
}
return null;
}
private boolean isConstructor() {
return fNode.getNodeType() != ASTNode.METHOD_INVOCATION && fNode.getNodeType() != ASTNode.SUPER_METHOD_INVOCATION;
}
private MethodDeclaration getStub(ASTRewrite rewrite, ASTNode targetTypeDecl) throws CoreException {
AST ast= targetTypeDecl.getAST();
MethodDeclaration decl= ast.newMethodDeclaration();
decl.setConstructor(isConstructor());
decl.setModifiers(evaluateModifiers(targetTypeDecl));
decl.setName(ast.newSimpleName(getMethodName()));
List arguments= fArguments;
List params= decl.parameters();
int nArguments= arguments.size();
ArrayList takenNames= new ArrayList(nArguments);
IVariableBinding[] declaredFields= fSenderBinding.getDeclaredFields();
for (int i= 0; i < declaredFields.length; i++) { // avoid to take parameter names that are equal to field names
takenNames.add(declaredFields[i].getName());
}
for (int i= 0; i < arguments.size(); i++) {
Expression elem= (Expression) arguments.get(i);
SingleVariableDeclaration param= ast.newSingleVariableDeclaration();
// argument type
String argTypeKey= "arg_type_" + i; //$NON-NLS-1$
Type type= evaluateParameterTypes(ast, elem, argTypeKey);
param.setType(type);
// argument name
String argNameKey= "arg_name_" + i; //$NON-NLS-1$
String name= evaluateParameterNames(takenNames, elem, type, argNameKey);
param.setName(ast.newSimpleName(name));
params.add(param);
markAsLinked(rewrite, param.getType(), false, argTypeKey);
markAsLinked(rewrite, param.getName(), false, argNameKey);
}
Block body= null;
String bodyStatement= ""; //$NON-NLS-1$
if (!isConstructor()) {
Type returnType= evaluateMethodType(ast);
if (returnType == null) {
decl.setReturnType(ast.newPrimitiveType(PrimitiveType.VOID));
} else {
decl.setReturnType(returnType);
}
if (!fSenderBinding.isInterface() && returnType != null) {
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(ASTNodeFactory.newDefaultExpression(ast, returnType, 0));
bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'));
}
}
if (!fSenderBinding.isInterface()) {
body= ast.newBlock();
String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), fSenderBinding.getName(), getMethodName(), isConstructor(), bodyStatement, String.valueOf('\n'));
if (placeHolder != null) {
ASTNode todoNode= rewrite.createPlaceholder(placeHolder, ASTRewrite.STATEMENT);
body.statements().add(todoNode);
}
}
decl.setBody(body);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (settings.createComments && !fSenderBinding.isAnonymous()) {
String string= CodeGeneration.getMethodComment(getCompilationUnit(), fSenderBinding.getName(), decl, null, String.valueOf('\n'));
if (string != null) {
Javadoc javadoc= (Javadoc) rewrite.createPlaceholder(string, ASTRewrite.JAVADOC);
decl.setJavadoc(javadoc);
}
}
return decl;
}
private int findMethodInsertIndex(List decls, int currPos) {
int nDecls= decls.size();
for (int i= 0; i < nDecls; i++) {
ASTNode curr= (ASTNode) decls.get(i);
if (curr instanceof MethodDeclaration && currPos < curr.getStartPosition() + curr.getLength()) {
return i + 1;
}
}
return nDecls;
}
private int findConstructorInsertIndex(List decls) {
int nDecls= decls.size();
int lastMethod= 0;
for (int i= nDecls - 1; i >= 0; i--) {
ASTNode curr= (ASTNode) decls.get(i);
if (curr instanceof MethodDeclaration) {
if (((MethodDeclaration) curr).isConstructor()) {
return i + 1;
}
lastMethod= i;
}
}
return lastMethod;
}
private Name getInvocationName() {
if (fNode instanceof MethodInvocation) {
return ((MethodInvocation)fNode).getName();
} else if (fNode instanceof SuperMethodInvocation) {
return ((SuperMethodInvocation)fNode).getName();
} else if (fNode instanceof ClassInstanceCreation) {
return ((ClassInstanceCreation)fNode).getName();
}
return null;
}
private String getMethodName() {
if (fNode instanceof MethodInvocation) {
return ((MethodInvocation)fNode).getName().getIdentifier();
} else if (fNode instanceof SuperMethodInvocation) {
return ((SuperMethodInvocation)fNode).getName().getIdentifier();
} else {
return fSenderBinding.getName(); // name of the class
}
}
private int evaluateModifiers(ASTNode targetTypeDecl) {
if (fSenderBinding.isInterface()) {
// for interface members copy the modifiers from an existing field
MethodDeclaration[] methodDecls= ((TypeDeclaration) targetTypeDecl).getMethods();
if (methodDecls.length > 0) {
return methodDecls[0].getModifiers();
}
return 0;
}
if (fNode instanceof MethodInvocation) {
int modifiers= 0;
Expression expression= ((MethodInvocation)fNode).getExpression();
if (expression != null) {
if (expression instanceof Name && ((Name) expression).resolveBinding().getKind() == IBinding.TYPE) {
modifiers |= Modifier.STATIC;
}
} else if (ASTResolving.isInStaticContext(fNode)) {
modifiers |= Modifier.STATIC;
}
ASTNode node= ASTResolving.findParentType(fNode);
if (targetTypeDecl.equals(node)) {
modifiers |= Modifier.PRIVATE;
} else if (node instanceof AnonymousClassDeclaration && ASTNodes.isParent(node, targetTypeDecl)) {
modifiers |= Modifier.PROTECTED;
} else {
modifiers |= Modifier.PUBLIC;
}
return modifiers;
}
return Modifier.PUBLIC;
}
private Type evaluateMethodType(AST ast) throws CoreException {
ITypeBinding binding= ASTResolving.guessBindingForReference(fNode);
if (binding != null) {
String typeName= addImport(binding);
return ASTNodeFactory.newType(ast, typeName);
} else {
ASTNode parent= fNode.getParent();
if (!(parent instanceof ExpressionStatement)) {
return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
}
}
return null;
}
private Type evaluateParameterTypes(AST ast, Expression elem, String key) throws CoreException {
ITypeBinding binding= Bindings.normalizeTypeBinding(elem.resolveTypeBinding());
if (binding != null) {
ITypeBinding[] typeProposals= ASTResolving.getRelaxingTypes(ast, binding);
for (int i= 0; i < typeProposals.length; i++) {
addLinkedModeProposal(key, typeProposals[i]);
}
String typeName= addImport(binding);
return ASTNodeFactory.newType(ast, typeName);
}
return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
}
private String evaluateParameterNames(ArrayList takenNames, Expression argNode, Type type, String key) {
IJavaProject project= getCompilationUnit().getJavaProject();
String[] excludedNames= (String[]) takenNames.toArray(new String[takenNames.size()]);
String favourite= null;
if (argNode instanceof SimpleName) {
SimpleName name= (SimpleName) argNode;
favourite= StubUtility.suggestArgumentName(project, name.getIdentifier(), excludedNames);
}
int dim= 0;
if (type.isArrayType()) {
ArrayType arrayType= (ArrayType) type;
dim= arrayType.getDimensions();
type= arrayType.getElementType();
}
String typeName= ASTNodes.asString(type);
String packName= Signature.getQualifier(typeName);
String[] names= NamingConventions.suggestArgumentNames(project, packName, typeName, dim, excludedNames);
if (favourite == null) {
favourite= names[0];
}
for (int i= 0; i < names.length; i++) {
addLinkedModeProposal(key, names[i]);
}
takenNames.add(favourite);
return favourite;
}
}
|
46,088 |
Bug 46088 Create method quick fix declares Object as return type [quick fix]
|
When you write the following code Bla var = getMyBla(); and press Ctrl-1, you can have the method "getMyBla" created. However, if the type Bla is not (yet) known, the method gets declared as private Object getMyBla() { ... } If you press Ctrl-1 again, the import for Bla is added. If the order of the two quickfixes was reversed, you'd get the correct method declaration.
|
resolved fixed
|
d5ef949
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-13T23:16:12Z | 2003-11-05T11:00:00Z |
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.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;
private static final String KEY_NAME= "name"; //$NON-NLS-1$
private static final String KEY_TYPE= "type"; //$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) {
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.markAsInserted(newDecl);
((MethodDeclaration)decl).parameters().add(newDecl);
markAsLinked(rewrite, node, true, KEY_NAME);
markAsLinked(rewrite, newDecl.getType(), false, KEY_TYPE);
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, newDeclFrag.getName(), true, KEY_NAME);
markAsLinked(rewrite, newDecl.getType(), false, KEY_TYPE);
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, frag.getName(), true, KEY_NAME);
markAsLinked(rewrite, expression.getType(), false, KEY_TYPE);
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, node, true, KEY_NAME);
markAsLinked(rewrite, newDecl.getType(), false, KEY_TYPE);
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()) {
fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0));
}
boolean isAnonymous= newTypeDecl.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION;
List decls= isAnonymous ? ((AnonymousClassDeclaration) newTypeDecl).bodyDeclarations() : ((TypeDeclaration) newTypeDecl).bodyDeclarations();
decls.add(findFieldInsertIndex(decls, node.getStartPosition()), newDecl);
rewrite.markAsInserted(newDecl);
if (!isInDifferentCU) {
markAsLinked(rewrite, node, true, KEY_NAME);
}
markAsLinked(rewrite, fragment.getName(), false, KEY_NAME);
markAsLinked(rewrite, newDecl.getType(), false, KEY_TYPE);
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);
}
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;
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;
}
}
|
46,639 |
Bug 46639 JavadocWizard disposing Window.getDefaultImage()
|
Build I20031111 JavadocWizard.performFinish() OptionalMessageDialog.open(..., Window.getDefaultImage(), ...); I believe passing Window.getDefaultImage() to the dialog is bad. When the dialog closes, it disposes of the default window image.
|
resolved fixed
|
c55af1a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-14T10:25:22Z | 2003-11-13T21:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocWizard.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 38692
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javadocexport;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.debug.core.DebugEvent;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IDebugEventSetListener;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.Launch;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceDescription;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IExportWizard;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbench;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.actions.OpenBrowserUtil;
import org.eclipse.jdt.internal.ui.dialogs.OptionalMessageDialog;
import org.eclipse.jdt.internal.ui.jarpackager.ConfirmSaveModifiedResourcesDialog;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
public class JavadocWizard extends Wizard implements IExportWizard {
private JavadocTreeWizardPage fJTWPage;
private JavadocSpecificsWizardPage fJSWPage;
private JavadocStandardWizardPage fJSpWPage;
private IPath fDestination;
private boolean fWriteCustom;
private boolean fOpenInBrowser;
protected final String CommandDesc= "JavadocCommandPage"; //$NON-NLS-1$
protected final String TreePageDesc= "JavadocTreePage"; //$NON-NLS-1$
protected final String SpecificsPageDesc= "JavadocSpecificsPage"; //$NON-NLS-1$
protected final String StandardPageDesc= "JavadocStandardPage"; //$NON-NLS-1$
private final int YES= 0;
private final int YES_TO_ALL= 1;
private final int NO= 2;
private final int NO_TO_ALL= 3;
private final String JAVADOC_ANT_INFORMATION_DIALOG= "javadocAntInformationDialog";//$NON-NLS-1$
private JavadocOptionsManager fStore;
private IWorkspaceRoot fRoot;
private Set fSelectedProjects;
private IFile fXmlJavadocFile;
//private ILaunchConfiguration fConfig;
public JavadocWizard() {
this(null);
}
public JavadocWizard(IFile xmlJavadocFile) {
super();
setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_EXPORT_JAVADOC);
setWindowTitle(JavadocExportMessages.getString("JavadocWizard.javadocwizard.title")); //$NON-NLS-1$
setDialogSettings(JavaPlugin.getDefault().getDialogSettings());
fRoot= ResourcesPlugin.getWorkspace().getRoot();
fXmlJavadocFile= xmlJavadocFile;
fWriteCustom= false;
fSelectedProjects= null;
}
/*
* @see IWizard#performFinish()
*/
public boolean performFinish() {
IJavaProject[] projects= (IJavaProject[]) fSelectedProjects.toArray(new IJavaProject[fSelectedProjects.size()]);
//writes the new settings to store
fJTWPage.finish();
if (!fJTWPage.getCustom())
fJSpWPage.finish();
fJSWPage.finish();
// Wizard will not run with unsaved files.
if (!checkPreconditions(fStore.getSourceElements())) {
return false;
}
fDestination= new Path(fStore.getDestination());
fDestination.toFile().mkdirs();
this.fOpenInBrowser= fStore.doOpenInBrowser();
//Ask if you wish to set the javadoc location for the projects (all) to
//the location of the newly generated javadoc
if (fStore.fromStandard()) {
try {
URL newURL= fDestination.toFile().toURL();
List projs= new ArrayList();
//get javadoc locations for all projects
for (int i= 0; i < projects.length; i++) {
IJavaProject iJavaProject= projects[i];
URL currURL= JavaUI.getProjectJavadocLocation(iJavaProject);
if (!newURL.equals(currURL)) { // currURL can be null
//if not all projects have the same javadoc location ask if you want to change
//them to have the same javadoc location
projs.add(iJavaProject);
}
}
if (!projs.isEmpty()) {
setAllJavadocLocations((IJavaProject[]) projs.toArray(new IJavaProject[projs.size()]), newURL);
}
} catch (MalformedURLException e) {
JavaPlugin.log(e);
}
}
if (fJSWPage.generateAnt()) {
//@Improve: make a better message
OptionalMessageDialog.open(JAVADOC_ANT_INFORMATION_DIALOG, getShell(), JavadocExportMessages.getString("JavadocWizard.antInformationDialog.title"), Window.getDefaultImage(), JavadocExportMessages.getString("JavadocWizard.antInformationDialog.message"), MessageDialog.INFORMATION, new String[] { IDialogConstants.OK_LABEL }, 0); //$NON-NLS-1$ //$NON-NLS-2$
try {
fStore.createXML();
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(),JavadocExportMessages.getString("JavadocWizard.error.writeANT.title"), JavadocExportMessages.getString("JavadocWizard.error.writeANT.message")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
//If the wizard was not launched from an ant file store the setttings
if (fXmlJavadocFile == null) {
getDialogSettings().addSection(fStore.createDialogSettings());
}
if (!executeJavadocGeneration(fStore.createArgumentArray()))
return false;
return true;
}
public void setAllJavadocLocations(IJavaProject[] projects, URL newURL) {
for (int j= 0; j < projects.length; j++) {
IJavaProject iJavaProject= projects[j];
String message= JavadocExportMessages.getFormattedString("JavadocWizard.updatejavadoclocation.message", new String[] { iJavaProject.getElementName(), fDestination.toOSString()}); //$NON-NLS-1$
String[] buttonlabels= new String[] { IDialogConstants.YES_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.NO_TO_ALL_LABEL };
MessageDialog dialog= new MessageDialog(getShell(), JavadocExportMessages.getString("JavadocWizard.updatejavadocdialog.label"), Dialog.getImage(Dialog.DLG_IMG_QUESTION), message, 4, buttonlabels, 1);//$NON-NLS-1$
switch (dialog.open()) {
case YES :
JavaUI.setProjectJavadocLocation(iJavaProject, newURL);
break;
case YES_TO_ALL :
for (int i= j; i < projects.length; i++) {
iJavaProject= projects[i];
JavaUI.setProjectJavadocLocation(iJavaProject, newURL);
j++;
}
break;
case NO_TO_ALL :
j= projects.length;
break;
case NO :
default :
break;
}
}
}
private boolean executeJavadocGeneration(String[] args) {
Process process= null;
try {
process= Runtime.getRuntime().exec(args);
if (process != null) {
// contruct a formatted command line for the process properties
StringBuffer buf= new StringBuffer();
for (int i= 0; i < args.length; i++) {
buf.append(args[i]);
buf.append(' ');
}
IDebugEventSetListener listener= new JavadocDebugEventListener(getShell().getDisplay());
DebugPlugin.getDefault().addDebugEventListener(listener);
ILaunchConfigurationWorkingCopy wc= null;
try {
ILaunchConfigurationType lcType= DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurationType(IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION);
String name= JavadocExportMessages.getString("JavadocWizard.launchconfig.name"); //$NON-NLS-1$
wc= lcType.newInstance(null, name);
wc.setAttribute(IDebugUIConstants.ATTR_PRIVATE, true);
ILaunch newLaunch= new Launch(wc, ILaunchManager.RUN_MODE, null);
IProcess iprocess= DebugPlugin.newProcess(newLaunch, process, JavadocExportMessages.getString("JavadocWizard.javadocprocess.label")); //$NON-NLS-1$
iprocess.setAttribute(IProcess.ATTR_CMDLINE, buf.toString());
DebugPlugin.getDefault().getLaunchManager().addLaunch(newLaunch);
} catch (CoreException e) {
JavaPlugin.log(e);
}
return true;
}
} catch (IOException e) {
JavaPlugin.log(e);
return false;
}
return false;
}
/**
* Creates a list of all CompilationUnits and extracts from that list a list of dirty
* files. The user is then asked to confirm if those resources should be saved or
* not.
*
* @return <code>true</code> if all preconditions are satisfied otherwise false
*/
private boolean checkPreconditions(IJavaElement[] elements) {
ArrayList resources= new ArrayList();
for (int i= 0; i < elements.length; i++) {
if (elements[i] instanceof ICompilationUnit) {
resources.add(elements[i].getResource());
}
}
//message could be null
IFile[] unSavedFiles= getUnsavedFiles(resources);
return saveModifiedResourcesIfUserConfirms(unSavedFiles);
}
/**
* Returns the files which are not saved and which are
* part of the files being exported.
*
* @return an array of unsaved files
*/
private IFile[] getUnsavedFiles(List resources) {
IEditorPart[] dirtyEditors= JavaPlugin.getDirtyEditors();
Set unsavedFiles= new HashSet(dirtyEditors.length);
if (dirtyEditors.length > 0) {
for (int i= 0; i < dirtyEditors.length; i++) {
if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput) dirtyEditors[i].getEditorInput()).getFile();
if (resources.contains(dirtyFile)) {
unsavedFiles.add(dirtyFile);
}
}
}
}
return (IFile[]) unsavedFiles.toArray(new IFile[unsavedFiles.size()]);
}
/**
* Asks to confirm to save the modified resources
* and save them if OK is pressed. Must be run in the display thread.
*
* @return true if user pressed OK and save was successful.
*/
private boolean saveModifiedResourcesIfUserConfirms(IFile[] dirtyFiles) {
if (confirmSaveModifiedResources(dirtyFiles)) {
try {
if (saveModifiedResources(dirtyFiles))
return true;
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogCE.title"), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogCE.message")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogITE.title"), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogITE.message")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
return false;
}
/**
* Asks the user to confirm to save the modified resources.
*
* @return true if user pressed OK.
*/
private boolean confirmSaveModifiedResources(IFile[] dirtyFiles) {
if (dirtyFiles == null || dirtyFiles.length == 0)
return true;
// Get display for further UI operations
Display display= getShell().getDisplay();
if (display == null || display.isDisposed())
return false;
// Ask user to confirm saving of all files
final ConfirmSaveModifiedResourcesDialog dlg= new ConfirmSaveModifiedResourcesDialog(getShell(), dirtyFiles);
final int[] intResult= new int[1];
Runnable runnable= new Runnable() {
public void run() {
intResult[0]= dlg.open();
}
};
display.syncExec(runnable);
return intResult[0] == IDialogConstants.OK_ID;
}
/**
* Save all of the editors in the workbench. Must be run in the display thread.
*
* @return true if successful.
*/
private boolean saveModifiedResources(final IFile[] dirtyFiles) throws CoreException, InvocationTargetException {
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IWorkspaceDescription description= workspace.getDescription();
boolean autoBuild= description.isAutoBuilding();
description.setAutoBuilding(false);
try {
workspace.setDescription(description);
// This save operation can not be canceled.
try {
new ProgressMonitorDialog(getShell()).run(false, false, createSaveModifiedResourcesRunnable(dirtyFiles));
} finally {
description.setAutoBuilding(autoBuild);
workspace.setDescription(description);
}
} catch (InterruptedException ex) {
return false;
}
return true;
}
private IRunnableWithProgress createSaveModifiedResourcesRunnable(final IFile[] dirtyFiles) {
return new IRunnableWithProgress() {
public void run(final IProgressMonitor pm) {
IEditorPart[] editorsToSave= JavaPlugin.getDirtyEditors();
String name= JavadocExportMessages.getString("JavadocWizard.savetask.name"); //$NON-NLS-1$
pm.beginTask(name, editorsToSave.length);
try {
List dirtyFilesList= Arrays.asList(dirtyFiles);
for (int i= 0; i < editorsToSave.length; i++) {
if (editorsToSave[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput) editorsToSave[i].getEditorInput()).getFile();
if (dirtyFilesList.contains((dirtyFile)))
editorsToSave[i].doSave(new SubProgressMonitor(pm, 1));
}
pm.worked(1);
}
} finally {
pm.done();
}
}
};
}
/*
* @see IWizard#addPages()
*/
public void addPages() {
fJTWPage= new JavadocTreeWizardPage(TreePageDesc, fStore);
fJSWPage= new JavadocSpecificsWizardPage(SpecificsPageDesc, fStore);
fJSpWPage= new JavadocStandardWizardPage(StandardPageDesc, fStore);
super.addPage(fJTWPage);
super.addPage(fJSpWPage);
super.addPage(fJSWPage);
fJTWPage.init();
fJSpWPage.init();
fJSWPage.init();
}
public void init(IWorkbench workbench, IStructuredSelection structuredSelection) {
IDialogSettings settings= getDialogSettings().getSection("javadoc"); //$NON-NLS-1$
fStore= new JavadocOptionsManager(fXmlJavadocFile, settings, structuredSelection);
fSelectedProjects= new HashSet(fStore.getJavaProjects());
}
private void refresh(IPath path) {
if (fRoot.findContainersForLocation(path).length > 0) {
try {
fRoot.refreshLocal(IResource.DEPTH_INFINITE, null);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
private void spawnInBrowser(Display display) {
if (fOpenInBrowser) {
try {
IPath indexFile= fDestination.append("index.html"); //$NON-NLS-1$
URL url= indexFile.toFile().toURL();
OpenBrowserUtil.open(url, display, getWindowTitle());
} catch (MalformedURLException e) {
JavaPlugin.log(e);
}
}
}
private class JavadocDebugEventListener implements IDebugEventSetListener {
private Display fDisplay;
public JavadocDebugEventListener(Display display) {
fDisplay= display;
}
public void handleDebugEvents(DebugEvent[] events) {
for (int i= 0; i < events.length; i++) {
if (events[i].getKind() == DebugEvent.TERMINATE) {
try {
if (!fWriteCustom) {
refresh(fDestination); //If destination of javadoc is in workspace then refresh workspace
spawnInBrowser(fDisplay);
}
} finally {
DebugPlugin.getDefault().removeDebugEventListener(this);
}
return;
}
}
}
}
public IWizardPage getNextPage(IWizardPage page) {
if (page instanceof JavadocTreeWizardPage) {
if (!fJTWPage.getCustom()) {
return fJSpWPage;
}
return fJSWPage;
} else if (page instanceof JavadocSpecificsWizardPage) {
return null;
} else if (page instanceof JavadocStandardWizardPage)
return fJSWPage;
else
return null;
}
public IWizardPage getPreviousPage(IWizardPage page) {
if (page instanceof JavadocSpecificsWizardPage) {
if (!fJTWPage.getCustom()) {
return fJSpWPage;
}
return fJSWPage;
} else if (page instanceof JavadocTreeWizardPage) {
return null;
} else if (page instanceof JavadocStandardWizardPage)
return fJTWPage;
else
return null;
}
protected void setSelectedProjects(Set projects) {
fSelectedProjects= projects;
}
protected Set getSelectedProjects() {
return fSelectedProjects;
}
protected void addSelectedProject(IJavaProject project) {
fSelectedProjects.add(project);
}
protected void removeSelectedProject(IJavaProject project) {
if (fSelectedProjects.contains(project))
fSelectedProjects.remove(project);
}
void removeAllProjects() {
fSelectedProjects.clear();
}
}
|
46,639 |
Bug 46639 JavadocWizard disposing Window.getDefaultImage()
|
Build I20031111 JavadocWizard.performFinish() OptionalMessageDialog.open(..., Window.getDefaultImage(), ...); I believe passing Window.getDefaultImage() to the dialog is bad. When the dialog closes, it disposes of the default window image.
|
resolved fixed
|
c55af1a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-14T10:25:22Z | 2003-11-13T21:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewElementWizard.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;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard;
import org.eclipse.jdt.internal.corext.template.Templates;
import org.eclipse.jdt.internal.ui.IUIConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.dialogs.OptionalMessageDialog;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
public abstract class NewElementWizard extends Wizard implements INewWizard {
private IWorkbench fWorkbench;
private IStructuredSelection fSelection;
public NewElementWizard() {
setNeedsProgressMonitor(true);
}
protected void openResource(final IFile resource) {
final IWorkbenchPage activePage= JavaPlugin.getActivePage();
if (activePage != null) {
final Display display= getShell().getDisplay();
if (display != null) {
display.asyncExec(new Runnable() {
public void run() {
try {
IDE.openEditor(activePage, resource, true);
} catch (PartInitException e) {
JavaPlugin.log(e);
}
}
});
}
}
}
/**
* Subclasses should override to perform the actions of the wizard.
* This method is run in the wizard container's context as a workspace runnable.
*/
protected void finishPage(IProgressMonitor monitor) throws InterruptedException, CoreException {
}
protected void handleFinishException(Shell shell, InvocationTargetException e) {
String title= NewWizardMessages.getString("NewElementWizard.op_error.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("NewElementWizard.op_error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, shell, title, message);
}
/*
* @see Wizard#performFinish
*/
public boolean performFinish() {
IWorkspaceRunnable op= new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
try {
finishPage(monitor);
} catch (InterruptedException e) {
throw new OperationCanceledException(e.getMessage());
}
}
};
try {
getContainer().run(false, true, new WorkbenchRunnableAdapter(op));
} catch (InvocationTargetException e) {
handleFinishException(getShell(), e);
return false;
} catch (InterruptedException e) {
return false;
}
return true;
}
protected void warnAboutTypeCommentDeprecation() {
String key= IUIConstants.DIALOGSTORE_TYPECOMMENT_DEPRECATED;
if (OptionalMessageDialog.isDialogEnabled(key)) {
Templates templates= Templates.getInstance();
boolean isOldWorkspace= templates.getTemplates("filecomment").length > 0 && templates.getTemplates("typecomment").length > 0; //$NON-NLS-1$ //$NON-NLS-2$
if (!isOldWorkspace) {
OptionalMessageDialog.setDialogEnabled(key, false);
}
String title= NewWizardMessages.getString("NewElementWizard.typecomment.deprecated.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("NewElementWizard.typecomment.deprecated.message"); //$NON-NLS-1$
OptionalMessageDialog.open(key, getShell(), title, Window.getDefaultImage(), message, MessageDialog.INFORMATION, new String[] { IDialogConstants.OK_LABEL }, 0);
}
}
/* (non-Javadoc)
* @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection)
*/
public void init(IWorkbench workbench, IStructuredSelection currentSelection) {
fWorkbench= workbench;
fSelection= currentSelection;
}
public IStructuredSelection getSelection() {
return fSelection;
}
public IWorkbench getWorkbench() {
return fWorkbench;
}
protected void selectAndReveal(IResource newResource) {
BasicNewResourceWizard.selectAndReveal(newResource, fWorkbench.getActiveWorkbenchWindow());
}
}
|
45,352 |
Bug 45352 Smart paste garbles indentation of commented code block
|
Copy this: // int abs(int i) { // //TODO: use Math.abs // if (i > 0) { // return i; // } else { // return -i; // } // } Pasting yields: // int abs(int i) { // //TODO: use Math.abs // if (i > 0) { // return i; // } else { // return -i; // } // }
|
resolved fixed
|
fbc9bb0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-14T11:02:26Z | 2003-10-22T08:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaAutoIndentStrategy.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
* Nikolay Metchev - Fixed bug 29909
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPartitioningException;
import org.eclipse.jface.text.DefaultAutoIndentStrategy;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.rules.DefaultPartitioner;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.texteditor.ITextEditorExtension3;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.compiler.IScanner;
import org.eclipse.jdt.core.compiler.ITerminalSymbols;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.DoStatement;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ForStatement;
import org.eclipse.jdt.core.dom.IfStatement;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.WhileStatement;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.FastJavaPartitionScanner;
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.Symbols;
/**
* Auto indent strategy sensitive to brackets.
*/
public class JavaAutoIndentStrategy extends DefaultAutoIndentStrategy {
private static class CompilationUnitInfo {
public char[] buffer;
public int delta;
public CompilationUnitInfo(char[] buffer, int delta) {
this.buffer= buffer;
this.delta= delta;
}
}
private boolean fCloseBrace;
private boolean fIsSmartMode;
private String fPartitioning;
/**
* Creates a new Java auto indent strategy for the given document partitioning.
*
* @param partitioning the document partitioning
*/
public JavaAutoIndentStrategy(String partitioning) {
fPartitioning= partitioning;
}
/**
* Evaluates the given line for the opening bracket that matches the closing bracket on the given line.
*/
private int findMatchingOpenBracket(IDocument d, int lineNumber, int endOffset, int closingBracketIncrease) throws BadLocationException {
int startOffset= d.getLineOffset(lineNumber);
int bracketCount= getBracketCount(d, startOffset, endOffset, false) - closingBracketIncrease;
// sum up the brackets counts of each line (closing brackets count negative,
// opening positive) until we find a line the brings the count to zero
while (bracketCount < 0) {
--lineNumber;
if (lineNumber < 0)
return -1;
startOffset= d.getLineOffset(lineNumber);
endOffset= startOffset + d.getLineLength(lineNumber) - 1;
bracketCount += getBracketCount(d, startOffset, endOffset, false);
}
return lineNumber;
}
private int getBracketCount(IDocument d, int startOffset, int endOffset, boolean ignoreCloseBrackets) throws BadLocationException {
int bracketCount= 0;
while (startOffset < endOffset) {
char curr= d.getChar(startOffset);
startOffset++;
switch (curr) {
case '/' :
if (startOffset < endOffset) {
char next= d.getChar(startOffset);
if (next == '*') {
// a comment starts, advance to the comment end
startOffset= getCommentEnd(d, startOffset + 1, endOffset);
} else if (next == '/') {
// '//'-comment: nothing to do anymore on this line
startOffset= endOffset;
}
}
break;
case '*' :
if (startOffset < endOffset) {
char next= d.getChar(startOffset);
if (next == '/') {
// we have been in a comment: forget what we read before
bracketCount= 0;
startOffset++;
}
}
break;
case '{' :
bracketCount++;
ignoreCloseBrackets= false;
break;
case '}' :
if (!ignoreCloseBrackets) {
bracketCount--;
}
break;
case '"' :
case '\'' :
startOffset= getStringEnd(d, startOffset, endOffset, curr);
break;
default :
}
}
return bracketCount;
}
// ----------- bracket counting ------------------------------------------------------
private int getCommentEnd(IDocument d, int offset, int endOffset) throws BadLocationException {
while (offset < endOffset) {
char curr= d.getChar(offset);
offset++;
if (curr == '*') {
if (offset < endOffset && d.getChar(offset) == '/') {
return offset + 1;
}
}
}
return endOffset;
}
private String getIndentOfLine(IDocument d, int line) throws BadLocationException {
if (line > -1) {
int start= d.getLineOffset(line);
int end= start + d.getLineLength(line) - 1;
int whiteEnd= findEndOfWhiteSpace(d, start, end);
return d.get(start, whiteEnd - start);
} else {
return ""; //$NON-NLS-1$
}
}
private int getStringEnd(IDocument d, int offset, int endOffset, char ch) throws BadLocationException {
while (offset < endOffset) {
char curr= d.getChar(offset);
offset++;
if (curr == '\\') {
// ignore escaped characters
offset++;
} else if (curr == ch) {
return offset;
}
}
return endOffset;
}
private void smartIndentAfterClosingBracket(IDocument d, DocumentCommand c) {
if (c.offset == -1 || d.getLength() == 0)
return;
try {
int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);
int line= d.getLineOfOffset(p);
int start= d.getLineOffset(line);
int whiteend= findEndOfWhiteSpace(d, start, c.offset);
// shift only when line does not contain any text up to the closing bracket
if (whiteend == c.offset) {
// evaluate the line with the opening bracket that matches out closing bracket
int indLine= findMatchingOpenBracket(d, line, c.offset, 1);
if (indLine != -1 && indLine != line) {
// take the indent of the found line
StringBuffer replaceText= new StringBuffer(getIndentOfLine(d, indLine));
// add the rest of the current line including the just added close bracket
replaceText.append(d.get(whiteend, c.offset - whiteend));
replaceText.append(c.text);
// modify document command
c.length += c.offset - start;
c.offset= start;
c.text= replaceText.toString();
}
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
private void smartIndentAfterOpeningBracket(IDocument d, DocumentCommand c) {
if (c.offset < 1 || d.getLength() == 0)
return;
JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);
int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);
try {
// current line
int line= d.getLineOfOffset(p);
int lineOffset= d.getLineOffset(line);
// line of last javacode
int pos= scanner.findNonWhitespaceBackward(p, JavaHeuristicScanner.UNBOUND);
if (pos == -1)
return;
int lastLine= d.getLineOfOffset(pos);
// only shift if the last java line is further up and is a braceless block candidate
if (lastLine < line) {
if (scanner.isBracelessBlockStart(pos + 1, JavaHeuristicScanner.UNBOUND)) {
// if the last line was a braceless block candidate, we have indented
// after the new line. This has to be undone as we *are* starting a block
// on the new line
StringBuffer replace= new StringBuffer(getIndentOfLine(d, lastLine));
c.length += replace.length();
replace.append(c.text);
c.offset= lineOffset;
c.text= replace.toString();
}
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
private void smartIndentAfterNewLine(IDocument d, DocumentCommand c) {
JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);
JavaIndenter indenter= new JavaIndenter(d, scanner);
String indent= indenter.computeIndentation(c.offset);
if (indent == null)
indent= ""; //$NON-NLS-1$
int docLength= d.getLength();
if (c.offset == -1 || docLength == 0)
return;
try {
int p= (c.offset == docLength ? c.offset - 1 : c.offset);
int line= d.getLineOfOffset(p);
StringBuffer buf= new StringBuffer(c.text + indent);
IRegion reg= d.getLineInformation(line);
int lineEnd= reg.getOffset() + reg.getLength();
int contentStart= findEndOfWhiteSpace(d, c.offset, lineEnd);
c.length= Math.max(contentStart - c.offset, 0);
int start= reg.getOffset();
ITypedRegion region= TextUtilities.getPartition(d, fPartitioning, start);
if (IJavaPartitions.JAVA_DOC.equals(region.getType()))
start= d.getLineInformationOfOffset(region.getOffset()).getOffset();
if (getBracketCount(d, start, c.offset, true) > 0 && closeBrace() && !isClosed(d, c.offset, c.length)) {
c.caretOffset= c.offset + buf.length();
c.shiftsCaret= false;
// copy old content of line behind insertion point to new line
// unless we think we are inserting an anonymous type definition
if (c.offset == 0 || !(computeAnonymousPosition(d, c.offset - 1, fPartitioning, lineEnd) != -1)) {
if (lineEnd - contentStart > 0) {
c.length= lineEnd - c.offset;
buf.append(d.get(contentStart, lineEnd - contentStart).toCharArray());
}
}
buf.append(getLineDelimiter(d));
String reference= indenter.getReferenceIndentation(c.offset);
buf.append(reference == null ? "" : reference); //$NON-NLS-1$
buf.append('}');
}
c.text= buf.toString();
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
/**
* Computes an insert position for an opening brace if <code>offset</code> maps to a position in
* <code>document</code> with a expression in parenthesis that will take a block after the closing parenthesis.
*
* @param document the document being modified
* @param offset the offset of the caret position, relative to the line start.
* @param partitioning the document partitioning
* @param max the max position
* @return an insert position relative to the line start if <code>line</code> contains a parenthesized expression that can be followed by a block, -1 otherwise
*/
private static int computeAnonymousPosition(IDocument document, int offset, String partitioning, int max) {
// find the opening parenthesis for every closing parenthesis on the current line after offset
// return the position behind the closing parenthesis if it looks like a method declaration
// or an expression for an if, while, for, catch statement
JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
int pos= offset;
int length= max;
int scanTo= scanner.scanForward(pos, length, '}');
if (scanTo == -1)
scanTo= length;
int closingParen= findClosingParenToLeft(scanner, pos) - 1;
while (true) {
int startScan= closingParen + 1;
closingParen= scanner.scanForward(startScan, scanTo, ')');
if (closingParen == -1)
break;
int openingParen= scanner.findOpeningPeer(closingParen - 1, '(', ')');
// no way an expression at the beginning of the document can mean anything
if (openingParen < 1)
break;
// only select insert positions for parenthesis currently embracing the caret
if (openingParen > pos)
continue;
if (looksLikeAnonymousClassDef(document, partitioning, scanner, openingParen - 1))
return closingParen + 1;
}
return -1;
}
/**
* Finds a closing parenthesis to the left of <code>position</code> in document, where that parenthesis is only
* separated by whitespace from <code>position</code>. If no such parenthesis can be found, <code>position</code> is returned.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return the position of a closing parenthesis left to <code>position</code> separated only by whitespace, or <code>position</code> if no parenthesis can be found
*/
private static int findClosingParenToLeft(JavaHeuristicScanner scanner, int position) {
if (position < 1)
return position;
if (scanner.previousToken(position - 1, JavaHeuristicScanner.UNBOUND) == Symbols.TokenRPAREN)
return scanner.getPosition() + 1;
return position;
}
/**
* Checks whether the content of <code>document</code> in the range (<code>offset</code>, <code>length</code>)
* contains the <code>new</code> keyword.
*
* @param document the document being modified
* @param offset the first character position in <code>document</code> to be considered
* @param length the length of the character range to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if the specified character range contains a <code>new</code> keyword, <code>false</code> otherwise.
*/
private static boolean isNewMatch(IDocument document, int offset, int length, String partitioning) {
Assert.isTrue(length >= 0);
Assert.isTrue(offset >= 0);
Assert.isTrue(offset + length < document.getLength() + 1);
try {
String text= document.get(offset, length);
int pos= text.indexOf("new"); //$NON-NLS-1$
while (pos != -1 && !isDefaultPartition(document, pos + offset, partitioning))
pos= text.indexOf("new", pos + 2); //$NON-NLS-1$
if (pos < 0)
return false;
if (pos != 0 && Character.isJavaIdentifierPart(document.getChar(pos - 1)))
return false;
if (pos + 3 < length && Character.isJavaIdentifierPart(document.getChar(pos + 3)))
return false;
return true;
} catch (BadLocationException e) {
}
return false;
}
/**
* Checks whether the content of <code>document</code> at <code>position</code> looks like an
* anonymous class definition. <code>position</code> must be to the left of the opening
* parenthesis of the definition's parameter list.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if the content of <code>document</code> looks like an anonymous class definition, <code>false</code> otherwise
*/
private static boolean looksLikeAnonymousClassDef(IDocument document, String partitioning, JavaHeuristicScanner scanner, int position) {
int previousCommaOrParen= scanner.scanBackward(position - 1, JavaHeuristicScanner.UNBOUND, new char[] {',', '('});
if (previousCommaOrParen == -1 || position < previousCommaOrParen + 5) // 2 for borders, 3 for "new"
return false;
if (isNewMatch(document, previousCommaOrParen + 1, position - previousCommaOrParen - 2, partitioning))
return true;
return false;
}
/**
* Checks whether <code>position</code> resides in a default (Java) partition of <code>document</code>.
*
* @param document the document being modified
* @param position the position to be checked
* @param partitioning the document partitioning
* @return <code>true</code> if <code>position</code> is in the default partition of <code>document</code>, <code>false</code> otherwise
*/
private static boolean isDefaultPartition(IDocument document, int position, String partitioning) {
Assert.isTrue(position >= 0);
Assert.isTrue(position <= document.getLength());
try {
ITypedRegion region= TextUtilities.getPartition(document, partitioning, position);
return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE);
} catch (BadLocationException e) {
}
return false;
}
private boolean isClosed(IDocument document, int offset, int length) {
CompilationUnitInfo info= getCompilationUnitForMethod(document, offset, fPartitioning);
if (info == null)
return false;
CompilationUnit compilationUnit= null;
try {
compilationUnit= AST.parseCompilationUnit(info.buffer);
} catch (ArrayIndexOutOfBoundsException x) {
// work around for parser problem
return false;
}
IProblem[] problems= compilationUnit.getProblems();
for (int i= 0; i != problems.length; ++i) {
if (problems[i].getID() == IProblem.UnmatchedBracket)
return true;
}
final int relativeOffset= offset - info.delta;
ASTNode node= NodeFinder.perform(compilationUnit, relativeOffset, length);
if (node == null)
return false;
if (length == 0) {
while (node != null && (relativeOffset == node.getStartPosition() || relativeOffset == node.getStartPosition() + node.getLength()))
node= node.getParent();
}
switch (node.getNodeType()) {
case ASTNode.BLOCK:
return areBlocksConsistent(document, offset, fPartitioning);
case ASTNode.IF_STATEMENT:
{
IfStatement ifStatement= (IfStatement) node;
Expression expression= ifStatement.getExpression();
IRegion expressionRegion= createRegion(expression, info.delta);
Statement thenStatement= ifStatement.getThenStatement();
IRegion thenRegion= createRegion(thenStatement, info.delta);
// between expression and then statement
if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset && offset + length <= thenRegion.getOffset())
return thenStatement != null;
Statement elseStatement= ifStatement.getElseStatement();
IRegion elseRegion= createRegion(elseStatement, info.delta);
IRegion elseToken= null;
if (elseStatement != null) {
int sourceOffset= thenRegion.getOffset() + thenRegion.getLength();
int sourceLength= elseRegion.getOffset() - sourceOffset;
elseToken= getToken(document, new Region(sourceOffset, sourceLength), ITerminalSymbols.TokenNameelse);
}
// between 'else' keyword and else statement
if (elseToken.getOffset() + elseToken.getLength() <= offset && offset + length < elseRegion.getOffset())
return elseStatement != null;
}
break;
case ASTNode.WHILE_STATEMENT:
case ASTNode.FOR_STATEMENT:
{
Expression expression= node.getNodeType() == ASTNode.WHILE_STATEMENT ? ((WhileStatement) node).getExpression() : ((ForStatement) node).getExpression();
IRegion expressionRegion= createRegion(expression, info.delta);
Statement body= node.getNodeType() == ASTNode.WHILE_STATEMENT ? ((WhileStatement) node).getBody() : ((ForStatement) node).getBody();
IRegion bodyRegion= createRegion(body, info.delta);
// between expression and body statement
if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset && offset + length <= bodyRegion.getOffset())
return body != null;
}
break;
case ASTNode.DO_STATEMENT:
{
DoStatement doStatement= (DoStatement) node;
IRegion doRegion= createRegion(doStatement, info.delta);
Statement body= doStatement.getBody();
IRegion bodyRegion= createRegion(body, info.delta);
if (doRegion.getOffset() + doRegion.getLength() <= offset && offset + length <= bodyRegion.getOffset())
return body != null;
}
break;
}
return true;
}
private static String getLineDelimiter(IDocument document) {
try {
if (document.getNumberOfLines() > 1)
return document.getLineDelimiter(0);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return System.getProperty("line.separator"); //$NON-NLS-1$
}
private static void smartPaste(IDocument document, DocumentCommand command) {
try {
JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
JavaIndenter indenter= new JavaIndenter(document, scanner);
int offset= command.offset;
// reference position to get the indent from
int refPos= indenter.findReferencePosition(offset);
if (refPos == JavaHeuristicScanner.NOT_FOUND)
return;
IRegion region= document.getLineInformationOfOffset(refPos);
int lineOffset= region.getOffset();
// get the base indentation from the reference position
int endOfWS= scanner.findNonWhitespaceForwardInAnyPartition(lineOffset, JavaHeuristicScanner.UNBOUND);
if (endOfWS == JavaHeuristicScanner.NOT_FOUND)
endOfWS= lineOffset;
String baseIndent= document.get(lineOffset, endOfWS - lineOffset);
if (refPos == JavaHeuristicScanner.NOT_FOUND)
return;
// eat any WS before the insertion to the beginning of the line
region= document.getLineInformationOfOffset(offset);
String notSelected= document.get(region.getOffset(), offset - region.getOffset());
if (notSelected.trim().length() == 0) {
command.length += notSelected.length();
command.offset= region.getOffset();
}
// prefix: the part we need for formatting but won't paste
String prefix= baseIndent + document.get(refPos, command.offset - refPos);
Document temp= new Document(prefix + command.text);
// eat any WS after the insertion, up to the delimiter, if the pasted text ends with
// a newline (with optional WS on the new line).
region= temp.getLineInformation(temp.getNumberOfLines() - 1);
boolean eatAfterSpace= temp.get(region.getOffset(), region.getLength()).trim().length() == 0;
String afterContent= new String();
if (eatAfterSpace) {
int selectionEnd= command.offset + command.length;
region= document.getLineInformationOfOffset(selectionEnd);
endOfWS= scanner.findNonWhitespaceForwardInAnyPartition(selectionEnd, region.getOffset() + region.getLength());
if (endOfWS != JavaHeuristicScanner.NOT_FOUND) {
int token= scanner.nextToken(selectionEnd, region.getOffset() + region.getLength());
if (token != Symbols.TokenEOF && token != Symbols.TokenCASE) { // doesn't work nicely with case
command.length += endOfWS - selectionEnd;
afterContent= document.get(endOfWS, scanner.getPosition() - endOfWS);
}
} else {
// simulate something to get the indentation
command.length += region.getOffset() + region.getLength() - selectionEnd;
afterContent= "x"; //$NON-NLS-1$
}
}
// add context behind the insertion
temp.replace(temp.getLength(), 0, afterContent);
scanner= new JavaHeuristicScanner(temp);
indenter= new JavaIndenter(temp, scanner);
String[] types= new String[] {
IJavaPartitions.JAVA_DOC,
IJavaPartitions.JAVA_MULTI_LINE_COMMENT,
IJavaPartitions.JAVA_SINGLE_LINE_COMMENT,
IJavaPartitions.JAVA_STRING,
IJavaPartitions.JAVA_CHARACTER,
IDocument.DEFAULT_CONTENT_TYPE
};
DefaultPartitioner partitioner= new DefaultPartitioner(new FastJavaPartitionScanner(), types);
partitioner.connect(temp);
temp.setDocumentPartitioner(IJavaPartitions.JAVA_PARTITIONING, partitioner);
int lines= temp.getNumberOfLines();
for (int l= document.computeNumberOfLines(prefix); l < lines; l++) { // we don't change the number of lines while adding indents
IRegion r= temp.getLineInformation(l);
lineOffset= r.getOffset();
if (r.getLength() == 0) // don't format empty lines
continue;
String indent= indenter.computeIndentation(lineOffset);
if (indent == null) // bail out
return;
// add single character for *-ed multiline comments
ITypedRegion partition= temp.getPartition(IJavaPartitions.JAVA_PARTITIONING, lineOffset);
String type= partition.getType();
if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT))
if (partition.getOffset() != lineOffset) // not for first line
indent += ' ';
endOfWS= scanner.findNonWhitespaceForwardInAnyPartition(lineOffset, lineOffset + r.getLength());
if (endOfWS == JavaHeuristicScanner.NOT_FOUND)
endOfWS= lineOffset + r.getLength();
if (lineOffset < temp.getLength() - 1) {
// special single line comment handling
String s= temp.get(lineOffset, 2);
if ("//".equals(s)) { //$NON-NLS-1$
endOfWS= scanner.findNonWhitespaceForwardInAnyPartition(lineOffset + 2, lineOffset + r.getLength());
lineOffset += 2;
}
}
int wsLen= Math.max(endOfWS - lineOffset, 0);
temp.replace(lineOffset, wsLen, indent);
}
temp.setDocumentPartitioner(IJavaPartitions.JAVA_PARTITIONING, null);
partitioner.disconnect();
command.text= temp.get(prefix.length(), temp.getLength() - prefix.length() - afterContent.length());
} catch (BadLocationException e) {
JavaPlugin.log(e);
} catch (BadPartitioningException e) {
JavaPlugin.log(e);
}
}
private boolean isLineDelimiter(IDocument document, String text) {
String[] delimiters= document.getLegalLineDelimiters();
if (delimiters != null)
return TextUtilities.equals(delimiters, text) > -1;
return false;
}
private void smartIndentAfterBlockDelimiter(IDocument document, DocumentCommand command) {
if (command.text.charAt(0) == '}')
smartIndentAfterClosingBracket(document, command);
else if (command.text.charAt(0) == '{')
smartIndentAfterOpeningBracket(document, command);
}
/*
* @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand)
*/
public void customizeDocumentCommand(IDocument d, DocumentCommand c) {
clearCachedValues();
if (!isSmartMode() || c.doit == false)
return;
if (c.length == 0 && c.text != null && isLineDelimiter(d, c.text))
smartIndentAfterNewLine(d, c);
else if (c.text.length() == 1)
smartIndentAfterBlockDelimiter(d, c);
else if (c.text.length() > 1 && getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_PASTE))
smartPaste(d, c);
}
private static IPreferenceStore getPreferenceStore() {
return JavaPlugin.getDefault().getPreferenceStore();
}
private boolean closeBrace() {
return fCloseBrace;
}
private boolean isSmartMode() {
return fIsSmartMode;
}
private void clearCachedValues() {
IPreferenceStore preferenceStore= getPreferenceStore();
fCloseBrace= preferenceStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_BRACES);
fIsSmartMode= computeSmartMode();
}
private boolean computeSmartMode() {
IWorkbenchPage page= JavaPlugin.getActivePage();
if (page != null) {
IEditorPart part= page.getActiveEditor();
if (part instanceof ITextEditorExtension3) {
ITextEditorExtension3 extension= (ITextEditorExtension3) part;
return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT;
}
}
return false;
}
private static CompilationUnitInfo getCompilationUnitForMethod(IDocument document, int offset, String partitioning) {
try {
JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
IRegion sourceRange= scanner.findSurroundingBlock(offset);
if (sourceRange == null)
return null;
String source= document.get(sourceRange.getOffset(), sourceRange.getLength());
StringBuffer contents= new StringBuffer();
contents.append("class ____C{void ____m()"); //$NON-NLS-1$
final int methodOffset= contents.length();
contents.append(source);
contents.append('}');
char[] buffer= contents.toString().toCharArray();
return new CompilationUnitInfo(buffer, sourceRange.getOffset() - methodOffset);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return null;
}
private static boolean areBlocksConsistent(IDocument document, int offset, String partitioning) {
if (offset < 1 || offset >= document.getLength())
return false;
int begin= offset;
int end= offset - 1;
JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
while (true) {
begin= scanner.findOpeningPeer(begin - 1, '{', '}');
end= scanner.findClosingPeer(end + 1, '{', '}');
if (begin == -1 && end == -1)
return true;
if (begin == -1 || end == -1)
return false;
}
}
private static IRegion createRegion(ASTNode node, int delta) {
return node == null ? null : new Region(node.getStartPosition() + delta, node.getLength());
}
private static IRegion getToken(IDocument document, IRegion scanRegion, int tokenId) {
try {
final String source= document.get(scanRegion.getOffset(), scanRegion.getLength());
IScanner scanner= ToolFactory.createScanner(false, false, false, false);
scanner.setSource(source.toCharArray());
int id= scanner.getNextToken();
while (id != ITerminalSymbols.TokenNameEOF && id != tokenId)
id= scanner.getNextToken();
if (id == ITerminalSymbols.TokenNameEOF)
return null;
int tokenOffset= scanner.getCurrentTokenStartPosition();
int tokenLength= scanner.getCurrentTokenEndPosition() + 1 - tokenOffset; // inclusive end
return new Region(tokenOffset + scanRegion.getOffset(), tokenLength);
} catch (InvalidInputException x) {
return null;
} catch (BadLocationException x) {
return null;
}
}
}
|
45,110 |
Bug 45110 No constant for '..compiler.problem.missingAnnotation'
|
20031015 The constant for "org.eclipse.jdt.core.compiler.problem.missingAnnotation" is missing. e.g. JavaCore.COMPILER_PB_MISSING_ANNOTATION;
|
verified fixed
|
2a475ab
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T10:37:59Z | 2003-10-17T14:13: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_ANNOTATION= JavaCore.COMPILER_PB_INVALID_ANNOTATION;
private static final String PREF_PB_MISSING_ANNOTATION= "org.eclipse.jdt.core.compiler.problem.missingAnnotation"; //$NON-NLS-1$
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 DEFAULT= "default"; //$NON-NLS-1$
private static final String USER= "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_ANNOTATION,
PREF_PB_MISSING_ANNOTATION
};
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 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.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$
};
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.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);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_invalid_javadoc.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_INVALID_ANNOTATION, errorWarningIgnore, errorWarningIgnoreLabels, 0);
int indent= fPixelConverter.convertWidthInCharsToPixels(2);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_missing_javadoc.label"); //$NON-NLS-1$
addCheckBox(composite, label, PREF_PB_MISSING_ANNOTATION, enabledDisabled, indent);
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);
Composite combos= composite;
String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_local.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_UNUSED_LOCAL, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_parameter.label"); //$NON-NLS-1$
addComboBox(combos, 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(combos, label, PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING, enabledDisabled, indent);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_signal_param_in_abstract.label"); //$NON-NLS-1$
addCheckBox(combos, label, PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT, enabledDisabled, indent);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_imports.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_UNUSED_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_private.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_UNUSED_PRIVATE, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_deprecation.label"); //$NON-NLS-1$
addComboBox(combos, 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 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, USER }, 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.equals(newValue)) {
updateComplianceDefaultSettings();
}
fComplianceStatus= validateCompliance();
} else if (PREF_COMPLIANCE.equals(changedKey)) {
if (checkValue(INTR_DEFAULT_COMPLIANCE, DEFAULT)) {
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_ANNOTATION.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 enableJavadocErrors= !checkValue(PREF_PB_INVALID_ANNOTATION, IGNORE);
getCheckBox(PREF_PB_MISSING_ANNOTATION).setEnabled(enableJavadocErrors);
}
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);
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;
}
return USER;
}
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 };
}
}
|
45,332 |
Bug 45332 Method inline fails [refactoring]
|
Problem was also present in R2.1. Tried to inline all invocations of a simple method: public static void assertTrue(boolean invariant) { assert invariant; } !SESSION Oct 21, 2003 13:33:31.629 --------------------------------------------- java.version=1.4.1_01 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=linux, ARCH=x86, WS=gtk, NL=en_US Command-line arguments: -os linux -ws gtk -arch x86 -data /local/home/nickell/eclipse -install file:/opt/eclipse/ !ENTRY org.eclipse.jdt.ui 4 10001 Oct 21, 2003 13:33:31.630 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetExceptionjava.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:313) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run(RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactoring(PerformRefactoringUtil.java:53) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish(RefactoringWizard.java:409) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish(UserInputWizardPage.java:119) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish(RefactoringWizard.java:472) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed(RefactoringWizardDialog2.java:395) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:263) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:430) 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:962) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1815) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1595) 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.internal.ui.refactoring.actions.InlineMethodAction.activate(InlineMethodAction.java:128) at org.eclipse.jdt.internal.ui.refactoring.actions.InlineMethodAction.run(InlineMethodAction.java:121) at org.eclipse.jdt.internal.ui.refactoring.actions.InlineMethodAction.run(InlineMethodAction.java:82) at org.eclipse.jdt.ui.actions.InlineAction.tryInlineMethod(InlineAction.java:132) at org.eclipse.jdt.ui.actions.InlineAction.run(InlineAction.java:109) 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.ui.actions.RetargetAction.runWithEvent(RetargetAction.java:203) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent(WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:541) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:962) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1815) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1595) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2347) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2330) 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: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:765) at org.eclipse.core.launcher.Main.main(Main.java:599) Caused by: java.lang.ArrayIndexOutOfBoundsException: 1 at org.eclipse.jdt.internal.corext.refactoring.code.flow.LocalFlowInfo.<init>(LocalFlowInfo.java:24) at org.eclipse.jdt.internal.corext.refactoring.code.flow.FlowAnalyzer.endVisit(FlowAnalyzer.java:666) at org.eclipse.jdt.core.dom.SimpleName.accept0(SimpleName.java:85) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:1353) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:1400) at org.eclipse.jdt.core.dom.QualifiedName.accept0(QualifiedName.java:91) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:1353) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:1400) at org.eclipse.jdt.core.dom.Assignment.accept0(Assignment.java:209) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:1353) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:1400) at org.eclipse.jdt.core.dom.ExpressionStatement.accept0(ExpressionStatement.java:81) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:1353) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:1423) at org.eclipse.jdt.core.dom.Block.accept0(Block.java:81) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:1353) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:1400) at org.eclipse.jdt.core.dom.MethodDeclaration.accept0(MethodDeclaration.java:178) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:1353) at org.eclipse.jdt.internal.corext.refactoring.code.flow.InputFlowAnalyzer.perform(InputFlowAnalyzer.java:111) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.flowAnalysis(CallInliner.java:390) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initialize(CallInliner.java:269) at org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring.checkInput(InlineMethodRefactoring.java:211) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run(CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run(CreateChangeOperation.java:100) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run(PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:302) ... 45 more
|
resolved fixed
|
e8a7136
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T10:55:56Z | 2003-10-21T21:00:00Z |
org.eclipse.jdt.ui/core
| |
45,332 |
Bug 45332 Method inline fails [refactoring]
|
Problem was also present in R2.1. Tried to inline all invocations of a simple method: public static void assertTrue(boolean invariant) { assert invariant; } !SESSION Oct 21, 2003 13:33:31.629 --------------------------------------------- java.version=1.4.1_01 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=linux, ARCH=x86, WS=gtk, NL=en_US Command-line arguments: -os linux -ws gtk -arch x86 -data /local/home/nickell/eclipse -install file:/opt/eclipse/ !ENTRY org.eclipse.jdt.ui 4 10001 Oct 21, 2003 13:33:31.630 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetExceptionjava.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:313) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run(RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactoring(PerformRefactoringUtil.java:53) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish(RefactoringWizard.java:409) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish(UserInputWizardPage.java:119) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish(RefactoringWizard.java:472) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed(RefactoringWizardDialog2.java:395) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:263) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:430) 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:962) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1815) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1595) 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.internal.ui.refactoring.actions.InlineMethodAction.activate(InlineMethodAction.java:128) at org.eclipse.jdt.internal.ui.refactoring.actions.InlineMethodAction.run(InlineMethodAction.java:121) at org.eclipse.jdt.internal.ui.refactoring.actions.InlineMethodAction.run(InlineMethodAction.java:82) at org.eclipse.jdt.ui.actions.InlineAction.tryInlineMethod(InlineAction.java:132) at org.eclipse.jdt.ui.actions.InlineAction.run(InlineAction.java:109) 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.ui.actions.RetargetAction.runWithEvent(RetargetAction.java:203) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent(WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:541) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:962) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1815) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1595) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2347) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2330) 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: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:765) at org.eclipse.core.launcher.Main.main(Main.java:599) Caused by: java.lang.ArrayIndexOutOfBoundsException: 1 at org.eclipse.jdt.internal.corext.refactoring.code.flow.LocalFlowInfo.<init>(LocalFlowInfo.java:24) at org.eclipse.jdt.internal.corext.refactoring.code.flow.FlowAnalyzer.endVisit(FlowAnalyzer.java:666) at org.eclipse.jdt.core.dom.SimpleName.accept0(SimpleName.java:85) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:1353) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:1400) at org.eclipse.jdt.core.dom.QualifiedName.accept0(QualifiedName.java:91) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:1353) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:1400) at org.eclipse.jdt.core.dom.Assignment.accept0(Assignment.java:209) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:1353) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:1400) at org.eclipse.jdt.core.dom.ExpressionStatement.accept0(ExpressionStatement.java:81) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:1353) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:1423) at org.eclipse.jdt.core.dom.Block.accept0(Block.java:81) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:1353) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:1400) at org.eclipse.jdt.core.dom.MethodDeclaration.accept0(MethodDeclaration.java:178) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:1353) at org.eclipse.jdt.internal.corext.refactoring.code.flow.InputFlowAnalyzer.perform(InputFlowAnalyzer.java:111) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.flowAnalysis(CallInliner.java:390) at org.eclipse.jdt.internal.corext.refactoring.code.CallInliner.initialize(CallInliner.java:269) at org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring.checkInput(InlineMethodRefactoring.java:211) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run(CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run(CreateChangeOperation.java:100) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run(PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:302) ... 45 more
|
resolved fixed
|
e8a7136
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T10:55:56Z | 2003-10-21T21:00:00Z |
extension/org/eclipse/jdt/internal/corext/dom/LocalVariableIndex.java
| |
46,608 |
Bug 46608 Introduce Factory: internal error
|
I20031111 + Introduce Factory patch Test Case /* * Created on Nov 10, 2003 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package p2; /** * @author dbaeumer * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class TT { public void foo() { new TT(); } public void bar() { new TT(); } } - select TT in foo - introduce factory. !ENTRY org.eclipse.jdt.ui 4 10001 Nov 13, 2003 19:30:44.143 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java:104) at java.lang.reflect.InvocationTargetException.<init> (InvocationTargetException.java:66) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:112) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101) Caused by: Java Model Exception: Java Model Status [Unexpected AST node type for constructor search hit: org.eclipse.jdt.core.dom.SimpleName('Sub')in compilation unit TT.java] at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.core.runtime.CoreException.<init>(CoreException.java:35) at org.eclipse.jdt.core.JavaModelException.<init> (JavaModelException.java:67) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ge tCtorCallAt(IntroduceFactoryRefactoring.java:795) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.re placeConstructorCalls(IntroduceFactoryRefactoring.java:730) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ad dAllChangesFor(IntroduceFactoryRefactoring.java:691) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.cr eateChange(IntroduceFactoryRefactoring.java:839) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
|
resolved fixed
|
a305932
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T11:12:50Z | 2003-11-13T19:00:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceFactory/Bugzilla/46608/p1/TT.java
| |
46,608 |
Bug 46608 Introduce Factory: internal error
|
I20031111 + Introduce Factory patch Test Case /* * Created on Nov 10, 2003 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package p2; /** * @author dbaeumer * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class TT { public void foo() { new TT(); } public void bar() { new TT(); } } - select TT in foo - introduce factory. !ENTRY org.eclipse.jdt.ui 4 10001 Nov 13, 2003 19:30:44.143 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java:104) at java.lang.reflect.InvocationTargetException.<init> (InvocationTargetException.java:66) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:112) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101) Caused by: Java Model Exception: Java Model Status [Unexpected AST node type for constructor search hit: org.eclipse.jdt.core.dom.SimpleName('Sub')in compilation unit TT.java] at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.core.runtime.CoreException.<init>(CoreException.java:35) at org.eclipse.jdt.core.JavaModelException.<init> (JavaModelException.java:67) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ge tCtorCallAt(IntroduceFactoryRefactoring.java:795) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.re placeConstructorCalls(IntroduceFactoryRefactoring.java:730) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ad dAllChangesFor(IntroduceFactoryRefactoring.java:691) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.cr eateChange(IntroduceFactoryRefactoring.java:839) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
|
resolved fixed
|
a305932
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T11:12:50Z | 2003-11-13T19:00:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceFactory/Bugzilla/46608/p1/TT_out.java
| |
46,608 |
Bug 46608 Introduce Factory: internal error
|
I20031111 + Introduce Factory patch Test Case /* * Created on Nov 10, 2003 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package p2; /** * @author dbaeumer * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class TT { public void foo() { new TT(); } public void bar() { new TT(); } } - select TT in foo - introduce factory. !ENTRY org.eclipse.jdt.ui 4 10001 Nov 13, 2003 19:30:44.143 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java:104) at java.lang.reflect.InvocationTargetException.<init> (InvocationTargetException.java:66) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:112) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101) Caused by: Java Model Exception: Java Model Status [Unexpected AST node type for constructor search hit: org.eclipse.jdt.core.dom.SimpleName('Sub')in compilation unit TT.java] at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.core.runtime.CoreException.<init>(CoreException.java:35) at org.eclipse.jdt.core.JavaModelException.<init> (JavaModelException.java:67) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ge tCtorCallAt(IntroduceFactoryRefactoring.java:795) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.re placeConstructorCalls(IntroduceFactoryRefactoring.java:730) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ad dAllChangesFor(IntroduceFactoryRefactoring.java:691) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.cr eateChange(IntroduceFactoryRefactoring.java:839) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
|
resolved fixed
|
a305932
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T11:12:50Z | 2003-11-13T19:00:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceFactory/Bugzilla/46608/p2/TT.java
| |
46,608 |
Bug 46608 Introduce Factory: internal error
|
I20031111 + Introduce Factory patch Test Case /* * Created on Nov 10, 2003 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package p2; /** * @author dbaeumer * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class TT { public void foo() { new TT(); } public void bar() { new TT(); } } - select TT in foo - introduce factory. !ENTRY org.eclipse.jdt.ui 4 10001 Nov 13, 2003 19:30:44.143 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java:104) at java.lang.reflect.InvocationTargetException.<init> (InvocationTargetException.java:66) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:112) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101) Caused by: Java Model Exception: Java Model Status [Unexpected AST node type for constructor search hit: org.eclipse.jdt.core.dom.SimpleName('Sub')in compilation unit TT.java] at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.core.runtime.CoreException.<init>(CoreException.java:35) at org.eclipse.jdt.core.JavaModelException.<init> (JavaModelException.java:67) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ge tCtorCallAt(IntroduceFactoryRefactoring.java:795) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.re placeConstructorCalls(IntroduceFactoryRefactoring.java:730) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ad dAllChangesFor(IntroduceFactoryRefactoring.java:691) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.cr eateChange(IntroduceFactoryRefactoring.java:839) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
|
resolved fixed
|
a305932
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T11:12:50Z | 2003-11-13T19:00:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceFactory/Bugzilla/46608/p2/TT_out.java
| |
46,608 |
Bug 46608 Introduce Factory: internal error
|
I20031111 + Introduce Factory patch Test Case /* * Created on Nov 10, 2003 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package p2; /** * @author dbaeumer * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class TT { public void foo() { new TT(); } public void bar() { new TT(); } } - select TT in foo - introduce factory. !ENTRY org.eclipse.jdt.ui 4 10001 Nov 13, 2003 19:30:44.143 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java:104) at java.lang.reflect.InvocationTargetException.<init> (InvocationTargetException.java:66) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:112) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101) Caused by: Java Model Exception: Java Model Status [Unexpected AST node type for constructor search hit: org.eclipse.jdt.core.dom.SimpleName('Sub')in compilation unit TT.java] at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.core.runtime.CoreException.<init>(CoreException.java:35) at org.eclipse.jdt.core.JavaModelException.<init> (JavaModelException.java:67) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ge tCtorCallAt(IntroduceFactoryRefactoring.java:795) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.re placeConstructorCalls(IntroduceFactoryRefactoring.java:730) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ad dAllChangesFor(IntroduceFactoryRefactoring.java:691) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.cr eateChange(IntroduceFactoryRefactoring.java:839) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
|
resolved fixed
|
a305932
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T11:12:50Z | 2003-11-13T19:00:00Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
46,608 |
Bug 46608 Introduce Factory: internal error
|
I20031111 + Introduce Factory patch Test Case /* * Created on Nov 10, 2003 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package p2; /** * @author dbaeumer * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class TT { public void foo() { new TT(); } public void bar() { new TT(); } } - select TT in foo - introduce factory. !ENTRY org.eclipse.jdt.ui 4 10001 Nov 13, 2003 19:30:44.143 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java:104) at java.lang.reflect.InvocationTargetException.<init> (InvocationTargetException.java:66) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:112) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101) Caused by: Java Model Exception: Java Model Status [Unexpected AST node type for constructor search hit: org.eclipse.jdt.core.dom.SimpleName('Sub')in compilation unit TT.java] at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.core.runtime.CoreException.<init>(CoreException.java:35) at org.eclipse.jdt.core.JavaModelException.<init> (JavaModelException.java:67) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ge tCtorCallAt(IntroduceFactoryRefactoring.java:795) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.re placeConstructorCalls(IntroduceFactoryRefactoring.java:730) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ad dAllChangesFor(IntroduceFactoryRefactoring.java:691) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.cr eateChange(IntroduceFactoryRefactoring.java:839) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
|
resolved fixed
|
a305932
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T11:12:50Z | 2003-11-13T19:00:00Z |
cases/org/eclipse/jdt/ui/tests/refactoring/IntroduceFactoryTests.java
| |
46,608 |
Bug 46608 Introduce Factory: internal error
|
I20031111 + Introduce Factory patch Test Case /* * Created on Nov 10, 2003 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package p2; /** * @author dbaeumer * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class TT { public void foo() { new TT(); } public void bar() { new TT(); } } - select TT in foo - introduce factory. !ENTRY org.eclipse.jdt.ui 4 10001 Nov 13, 2003 19:30:44.143 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java:104) at java.lang.reflect.InvocationTargetException.<init> (InvocationTargetException.java:66) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:112) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101) Caused by: Java Model Exception: Java Model Status [Unexpected AST node type for constructor search hit: org.eclipse.jdt.core.dom.SimpleName('Sub')in compilation unit TT.java] at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.core.runtime.CoreException.<init>(CoreException.java:35) at org.eclipse.jdt.core.JavaModelException.<init> (JavaModelException.java:67) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ge tCtorCallAt(IntroduceFactoryRefactoring.java:795) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.re placeConstructorCalls(IntroduceFactoryRefactoring.java:730) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ad dAllChangesFor(IntroduceFactoryRefactoring.java:691) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.cr eateChange(IntroduceFactoryRefactoring.java:839) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
|
resolved fixed
|
a305932
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T11:12:50Z | 2003-11-13T19:00:00Z |
org.eclipse.jdt.ui/core
| |
46,608 |
Bug 46608 Introduce Factory: internal error
|
I20031111 + Introduce Factory patch Test Case /* * Created on Nov 10, 2003 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package p2; /** * @author dbaeumer * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class TT { public void foo() { new TT(); } public void bar() { new TT(); } } - select TT in foo - introduce factory. !ENTRY org.eclipse.jdt.ui 4 10001 Nov 13, 2003 19:30:44.143 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java:104) at java.lang.reflect.InvocationTargetException.<init> (InvocationTargetException.java:66) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:112) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101) Caused by: Java Model Exception: Java Model Status [Unexpected AST node type for constructor search hit: org.eclipse.jdt.core.dom.SimpleName('Sub')in compilation unit TT.java] at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.core.runtime.CoreException.<init>(CoreException.java:35) at org.eclipse.jdt.core.JavaModelException.<init> (JavaModelException.java:67) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ge tCtorCallAt(IntroduceFactoryRefactoring.java:795) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.re placeConstructorCalls(IntroduceFactoryRefactoring.java:730) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.ad dAllChangesFor(IntroduceFactoryRefactoring.java:691) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring.cr eateChange(IntroduceFactoryRefactoring.java:839) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
|
resolved fixed
|
a305932
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T11:12:50Z | 2003-11-13T19:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/IntroduceFactoryRefactoring.java
| |
46,674 |
Bug 46674 Introduce Factory: use message format for NLS string which contains parts
|
I20031111 The programm should never build up a message string consiting of parts since the parts might not be traslatable into other languages. Always use message format instead (e.g. the following ''{0}'' has compile errors). Affected keys are: IntroduceFactory.noASTNodeForConstructorSearchHit IntroduceFactory.noASTNodeForConstructorSearchHitPart2 IntroduceFactory.unexpectedInitializerNodeType IntroduceFactory.unexpectedInitializerNodeTypePart2 IntroduceFactory.unexpectedASTNodeTypeForConstructorSearchHit IntroduceFactory.unexpectedASTNodeTypeForConstructorSearchHitPart2
|
resolved fixed
|
c77fc32
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T11:42:36Z | 2003-11-14T17:13:20Z |
org.eclipse.jdt.ui/core
| |
46,674 |
Bug 46674 Introduce Factory: use message format for NLS string which contains parts
|
I20031111 The programm should never build up a message string consiting of parts since the parts might not be traslatable into other languages. Always use message format instead (e.g. the following ''{0}'' has compile errors). Affected keys are: IntroduceFactory.noASTNodeForConstructorSearchHit IntroduceFactory.noASTNodeForConstructorSearchHitPart2 IntroduceFactory.unexpectedInitializerNodeType IntroduceFactory.unexpectedInitializerNodeTypePart2 IntroduceFactory.unexpectedASTNodeTypeForConstructorSearchHit IntroduceFactory.unexpectedASTNodeTypeForConstructorSearchHitPart2
|
resolved fixed
|
c77fc32
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T11:42:36Z | 2003-11-14T17:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/IntroduceFactoryRefactoring.java
| |
45,349 |
Bug 45349 [typing] Smart ; must replace selection
|
I20031015 1. enter "int a= 3;" 2. select "=3;" 3. press ";"
|
verified fixed
|
e3175ca
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T16:43:02Z | 2003-10-22T08:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/SmartSemicolonAutoEditStrategy.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import java.util.Arrays;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IAutoEditStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.texteditor.ITextEditorExtension2;
import org.eclipse.ui.texteditor.ITextEditorExtension3;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.core.Assert;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
/**
* Modifies <code>DocumentCommand</code>s inserting semicolons and opening braces to place them
* smartly, i.e. moving them to the end of a line if that is what the user expects.
*
* <p>In practice, semicolons and braces (and the caret) are moved to the end of the line if they are typed
* anywhere except for semicolons in a <code>for</code> statements definition. If the line contains a semicolon
* or brace after the current caret position, the cursor is moved after it.</p>
*
* @see org.eclipse.jface.text.DocumentCommand
* @since 3.0
*/
public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy {
/** String representation of a semicolon. */
private static final String SEMICOLON= ";"; //$NON-NLS-1$
/** Char representation of a semicolon. */
private static final char SEMICHAR= ';';
/** String represenattion of a opening brace. */
private static final String BRACE= "{"; //$NON-NLS-1$
/** Char representation of a opening brace */
private static final char BRACECHAR= '{';
private char fCharacter;
private String fPartitioning;
/**
* Creates a new SmartSemicolonAutoEditStrategy.
*
* @param partitioning the document partitioning
*/
public SmartSemicolonAutoEditStrategy(String partitioning) {
fPartitioning= partitioning;
}
/*
* @see org.eclipse.jface.text.IAutoEditStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand)
*/
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
// 0: early pruning
// also customize if <code>doit</code> is false (so it works in code completion situations)
// if (!command.doit)
// return;
if (command.text == null)
return;
if (command.text.equals(SEMICOLON))
fCharacter= SEMICHAR;
else if (command.text.equals(BRACE))
fCharacter= BRACECHAR;
else
return;
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
if (fCharacter == SEMICHAR && !store.getBoolean(PreferenceConstants.EDITOR_SMART_SEMICOLON))
return;
if (fCharacter == BRACECHAR && !store.getBoolean(PreferenceConstants.EDITOR_SMART_OPENING_BRACE))
return;
IWorkbenchPage page= JavaPlugin.getActivePage();
if (page == null)
return;
IEditorPart part= page.getActiveEditor();
if (!(part instanceof CompilationUnitEditor))
return;
CompilationUnitEditor editor= (CompilationUnitEditor)part;
if (editor.getInsertMode() != ITextEditorExtension3.SMART_INSERT || !editor.isEditable())
return;
ITextEditorExtension2 extension= (ITextEditorExtension2)editor.getAdapter(ITextEditorExtension2.class);
if (extension != null && !extension.validateEditorInputState())
return;
// 1: find concerned line / position in java code, location in statement
int pos= command.offset;
ITextSelection line;
try {
IRegion l= document.getLineInformationOfOffset(pos);
line= new TextSelection(document, l.getOffset(), l.getLength());
} catch (BadLocationException e) {
return;
}
// 2: choose action based on findings (is for-Statement?)
// for now: compute the best position to insert the new character
int positionInLine= computeCharacterPosition(document, line, pos - line.getOffset(), fCharacter, fPartitioning);
int position= positionInLine + line.getOffset();
// never position before the current position!
if (position < pos)
return;
// never double already existing content
if (alreadyPresent(document, fCharacter, position))
return;
// 3: modify command
command.offset= position;
command.length= 0;
command.caretOffset= position;
command.text= adjustSpacing(document, position, fCharacter);
command.doit= true;
command.owner= null;
}
/**
* Adds a space before a brace if it is inserted after a parenthesis, equal sign, or one
* of the keywords <code>try, else, do</code>.
*
* @param document the document we are working on
* @param position the insert position of <code>character</code>
* @param character the character to be inserted
* @return a <code>String</code> consisting of <code>character</code> plus any additional spacing
*/
private String adjustSpacing(IDocument doc, int position, char character) {
if (character == BRACECHAR) {
if (position > 0 && position <= doc.getLength()) {
int pos= position - 1;
if (looksLike(doc, pos, ")") //$NON-NLS-1$
|| looksLike(doc, pos, "=") //$NON-NLS-1$
|| looksLike(doc, pos, "]") //$NON-NLS-1$
|| looksLike(doc, pos, "try") //$NON-NLS-1$
|| looksLike(doc, pos, "else") //$NON-NLS-1$
|| looksLike(doc, pos, "synchronized") //$NON-NLS-1$
|| looksLike(doc, pos, "static") //$NON-NLS-1$
|| looksLike(doc, pos, "finally") //$NON-NLS-1$
|| looksLike(doc, pos, "do")) //$NON-NLS-1$
return new String(new char[] { ' ', character });
}
}
return new String(new char[] { character });
}
/**
* Checks whether a character to be inserted is already present at the insert location (perhaps
* separated by some whitespace from <code>position</code>.
*
* @param document the document we are working on
* @param position the insert position of <code>ch</code>
* @param character the character to be inserted
* @return <code>true</code> if <code>ch</code> is already present at <code>location</code>, <code>false</code> otherwise
*/
private boolean alreadyPresent(IDocument document, char ch, int position) {
int pos= firstNonWhitespaceForward(document, position, fPartitioning, document.getLength());
try {
if (pos != -1 && document.getChar(pos) == ch)
return true;
} catch (BadLocationException e) {
}
return false;
}
/**
* Computes the next insert position of the given character in the current line.
*
* @param document the document we are working on
* @param line the line where the change is being made
* @param offset the position of the caret in the line when <code>character</code> was typed
* @param character the character to look for
* @param partitioning the document partitioning
* @return the position where <code>character</code> should be inserted / replaced
*/
protected static int computeCharacterPosition(IDocument document, ITextSelection line, int offset, char character, String partitioning) {
String text= line.getText();
if (text == null)
return 0;
int insertPos;
if (character == BRACECHAR) {
insertPos= computeArrayInitializationPos(document, line, offset, partitioning);
if (insertPos == -1) {
insertPos= computeAfterTryDoElse(document, line, offset);
}
if (insertPos == -1) {
insertPos= computeAfterParenthesis(document, line, offset, partitioning);
}
} else if (character == SEMICHAR) {
if (isForStatement(text, offset)) {
insertPos= offset;
} else {
int nextPartitionPos= nextPartitionOrLineEnd(document, line, offset, partitioning);
insertPos= startOfWhitespaceBeforeOffset(text, nextPartitionPos);
if (insertPos > 0 && text.charAt(insertPos - 1) == character)
insertPos= offset;
}
} else {
Assert.isTrue(false);
return -1;
}
return insertPos;
}
/**
* Computes an insert position for an opening brace if <code>offset</code> maps to a position in
* <code>document</code> that looks like being the RHS of an assignment or like an array definition.
*
* @param document the document being modified
* @param line the current line under investigation
* @param offset the offset of the caret position, relative to the line start.
* @param partitioning the document partitioning
* @return an insert position relative to the line start if <code>line</code> looks like being an array initialization at <code>offset</code>, -1 otherwise
*/
private static int computeArrayInitializationPos(IDocument document, ITextSelection line, int offset, String partitioning) {
// search backward while WS, find = (not != <= >= ==) in default partition
int pos= offset + line.getOffset();
if (pos == 0)
return -1;
int p= firstNonWhitespaceBackward(document, pos - 1, partitioning, -1);
if (p == -1)
return -1;
try {
char ch= document.getChar(p);
if (ch != '=' && ch != ']')
return -1;
if (p == 0)
return offset;
p= firstNonWhitespaceBackward(document, p - 1, partitioning, -1);
if (p == -1)
return -1;
ch= document.getChar(p);
if (Character.isJavaIdentifierPart(ch) || ch == ']' || ch == '[')
return offset;
} catch (BadLocationException e) {
}
return -1;
}
/**
* Computes an insert position for an opening brace if <code>offset</code> maps to a position in
* <code>document</code> involving a keyword taking a block after it. These are: <code>try</code>,
* <code>do</code>, <code>synchronized</code>, <code>static</code>, <code>finally</code>, or <code>else</code>.
*
* @param document the document being modified
* @param line the current line under investigation
* @param offset the offset of the caret position, relative to the line start.
* @return an insert position relative to the line start if <code>line</code> contains one of the above keywords at or before <code>offset</code>, -1 otherwise
*/
private static int computeAfterTryDoElse(IDocument doc, ITextSelection line, int offset) {
// search backward while WS, find 'try', 'do', 'else' in default partition
int p= offset + line.getOffset();
p= firstWhitespaceToRight(doc, p);
if (p == -1)
return -1;
p--;
if (looksLike(doc, p, "try") //$NON-NLS-1$
|| looksLike(doc, p, "do") //$NON-NLS-1$
|| looksLike(doc, p, "synchronized") //$NON-NLS-1$
|| looksLike(doc, p, "static") //$NON-NLS-1$
|| looksLike(doc, p, "finally") //$NON-NLS-1$
|| looksLike(doc, p, "else")) //$NON-NLS-1$
return p + 1 - line.getOffset();
return -1;
}
/**
* Computes an insert position for an opening brace if <code>offset</code> maps to a position in
* <code>document</code> with a expression in parenthesis that will take a block after the closing parenthesis.
*
* @param document the document being modified
* @param line the current line under investigation
* @param offset the offset of the caret position, relative to the line start.
* @param partitioning the document partitioning
* @return an insert position relative to the line start if <code>line</code> contains a parenthesized expression that can be followed by a block, -1 otherwise
*/
private static int computeAfterParenthesis(IDocument document, ITextSelection line, int offset, String partitioning) {
// find the opening parenthesis for every closing parenthesis on the current line after offset
// return the position behind the closing parenthesis if it looks like a method declaration
// or an expression for an if, while, for, catch statement
int pos= offset + line.getOffset();
int length= line.getOffset() + line.getLength();
int scanTo= scanForward(document, pos, partitioning, length, '}');
if (scanTo == -1)
scanTo= length;
int closingParen= findClosingParenToLeft(document, pos, partitioning) - 1;
while (true) {
int startScan= closingParen + 1;
closingParen= scanForward(document, startScan, partitioning, scanTo, ')');
if (closingParen == -1)
break;
int openingParen= findOpeningParenMatch(document, closingParen, partitioning);
// no way an expression at the beginning of the document can mean anything
if (openingParen < 1)
break;
// only select insert positions for parenthesis currently embracing the caret
if (openingParen > pos)
continue;
if (looksLikeAnonymousClassDef(document, openingParen - 1, partitioning))
return closingParen + 1 - line.getOffset();
if (looksLikeIfWhileForCatch(document, openingParen - 1, partitioning))
return closingParen + 1 - line.getOffset();
if (looksLikeMethodDecl(document, openingParen - 1, partitioning))
return closingParen + 1 - line.getOffset();
}
return -1;
}
/**
* Finds a closing parenthesis to the left of <code>position</code> in document, where that parenthesis is only
* separated by whitespace from <code>position</code>. If no such parenthesis can be found, <code>position</code> is returned.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return the position of a closing parenthesis left to <code>position</code> separated only by whitespace, or <code>position</code> if no parenthesis can be found
*/
private static int findClosingParenToLeft(IDocument document, int position, String partitioning) {
final char CLOSING_PAREN= ')';
try {
if (position < 1)
return position;
int nonWS= firstNonWhitespaceBackward(document, position - 1, partitioning, -1);
if (nonWS != -1 && document.getChar(nonWS) == CLOSING_PAREN)
return nonWS;
} catch (BadLocationException e1) {
}
return position;
}
/**
* Finds the first whitespace character position to the right of (and including) <code>position</code>.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @return the position of a whitespace character greater or equal than <code>position</code> separated only by whitespace, or -1 if none found
*/
private static int firstWhitespaceToRight(IDocument document, int position) {
int length= document.getLength();
Assert.isTrue(position >= 0);
Assert.isTrue(position <= length);
try {
while (position < length) {
char ch= document.getChar(position);
if (Character.isWhitespace(ch))
return position;
position++;
}
return position;
} catch (BadLocationException e) {
}
return -1;
}
/**
* Finds the highest position in <code>document</code> such that the position is <= <code>position</code>
* and > <code>bound</code> and <code>Character.isWhitespace(document.getChar(pos))</code> evaluates to <code>false</code>
* and the position is in the default partition.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @param bound the first position in <code>document</code> to not consider any more, with <code>bound</code> > <code>position</code>
* @return the highest position of one element in <code>chars</code> in [<code>position</code>, <code>scanTo</code>) that resides in a Java partition, or <code>-1</code> if none can be found
*/
private static int firstNonWhitespaceBackward(IDocument document, int position, String partitioning, int bound) {
Assert.isTrue(position < document.getLength());
Assert.isTrue(bound >= -1);
try {
while (position > bound) {
char ch= document.getChar(position);
if (!Character.isWhitespace(ch) && isDefaultPartition(document, position, partitioning))
return position;
position--;
}
} catch (BadLocationException e) {
}
return -1;
}
/**
* Finds the smallest position in <code>document</code> such that the position is >= <code>position</code>
* and < <code>bound</code> and <code>Character.isWhitespace(document.getChar(pos))</code> evaluates to <code>false</code>
* and the position is in the default partition.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @param bound the first position in <code>document</code> to not consider any more, with <code>bound</code> > <code>position</code>
* @return the smallest position of one element in <code>chars</code> in [<code>position</code>, <code>scanTo</code>) that resides in a Java partition, or <code>-1</code> if none can be found
*/
private static int firstNonWhitespaceForward(IDocument document, int position, String partitioning, int bound) {
Assert.isTrue(position >= 0);
Assert.isTrue(bound <= document.getLength());
try {
while (position < bound) {
char ch= document.getChar(position);
if (!Character.isWhitespace(ch) && isDefaultPartition(document, position, partitioning))
return position;
position++;
}
} catch (BadLocationException e) {
}
return -1;
}
/**
* Finds the highest position in <code>document</code> such that the position is <= <code>position</code>
* and > <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code> for at least one
* ch in <code>chars</code> and the position is in the default partition.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> > <code>position</code>
* @param chars an array of <code>char</code> to search for
* @return the highest position of one element in <code>chars</code> in (<code>bound</code>, <code>position</code>] that resides in a Java partition, or <code>-1</code> if none can be found
*/
private static int scanBackward(IDocument document, int position, String partitioning, int bound, char[] chars) {
Assert.isTrue(bound >= -1);
Assert.isTrue(position < document.getLength() );
Arrays.sort(chars);
try {
while (position > bound) {
if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 && isDefaultPartition(document, position, partitioning))
return position;
position--;
}
} catch (BadLocationException e) {
}
return -1;
}
// /**
// * Finds the highest position in <code>document</code> such that the position is <= <code>position</code>
// * and > <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code>
// * and the position is in the default partition.
// *
// * @param document the document being modified
// * @param position the first character position in <code>document</code> to be considered
// * @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> > <code>position</code>
// * @param chars an array of <code>char</code> to search for
// * @return the highest position of one element in <code>chars</code> in [<code>position</code>, <code>scanTo</code>) that resides in a Java partition, or <code>-1</code> if none can be found
// */
// private static int scanBackward(IDocument document, int position, int bound, char ch) {
// return scanBackward(document, position, bound, new char[] {ch});
// }
//
/**
* Finds the lowest position in <code>document</code> such that the position is >= <code>position</code>
* and < <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code> for at least one
* ch in <code>chars</code> and the position is in the default partition.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> > <code>position</code>
* @param chars an array of <code>char</code> to search for
* @return the lowest position of one element in <code>chars</code> in [<code>position</code>, <code>bound</code>) that resides in a Java partition, or <code>-1</code> if none can be found
*/
private static int scanForward(IDocument document, int position, String partitioning, int bound, char[] chars) {
Assert.isTrue(position >= 0);
Assert.isTrue(bound <= document.getLength());
Arrays.sort(chars);
try {
while (position < bound) {
if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 && isDefaultPartition(document, position, partitioning))
return position;
position++;
}
} catch (BadLocationException e) {
}
return -1;
}
/**
* Finds the lowest position in <code>document</code> such that the position is >= <code>position</code>
* and < <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code>
* and the position is in the default partition.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> > <code>position</code>
* @param chars an array of <code>char</code> to search for
* @return the lowest position of one element in <code>chars</code> in [<code>position</code>, <code>bound</code>) that resides in a Java partition, or <code>-1</code> if none can be found
*/
private static int scanForward(IDocument document, int position, String partitioning, int bound, char ch) {
return scanForward(document, position, partitioning, bound, new char[] {ch});
}
/**
* Checks whether the content of <code>document</code> in the range (<code>offset</code>, <code>length</code>)
* contains the <code>new</code> keyword.
*
* @param document the document being modified
* @param offset the first character position in <code>document</code> to be considered
* @param length the length of the character range to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if the specified character range contains a <code>new</code> keyword, <code>false</code> otherwise.
*/
private static boolean isNewMatch(IDocument document, int offset, int length, String partitioning) {
Assert.isTrue(length >= 0);
Assert.isTrue(offset >= 0);
Assert.isTrue(offset + length < document.getLength() + 1);
try {
String text= document.get(offset, length);
int pos= text.indexOf("new"); //$NON-NLS-1$
while (pos != -1 && !isDefaultPartition(document, pos + offset, partitioning))
pos= text.indexOf("new", pos + 2); //$NON-NLS-1$
if (pos < 0)
return false;
if (pos != 0 && Character.isJavaIdentifierPart(text.charAt(pos - 1)))
return false;
if (pos + 3 < length && Character.isJavaIdentifierPart(text.charAt(pos + 3)))
return false;
return true;
} catch (BadLocationException e) {
}
return false;
}
/**
* Checks whether the content of <code>document</code> at <code>position</code> looks like an
* anonymous class definition. <code>position</code> must be to the left of the opening
* parenthesis of the definition's parameter list.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if the content of <code>document</code> looks like an anonymous class definition, <code>false</code> otherwise
*/
private static boolean looksLikeAnonymousClassDef(IDocument document, int position, String partitioning) {
int previousCommaOrParen= scanBackward(document, position - 1, partitioning, -1, new char[] {',', '('});
if (previousCommaOrParen == -1 || position < previousCommaOrParen + 5) // 2 for borders, 3 for "new"
return false;
if (isNewMatch(document, previousCommaOrParen + 1, position - previousCommaOrParen - 2, partitioning))
return true;
return false;
}
/**
* Checks whether <code>position</code> resides in a default (Java) partition of <code>document</code>.
*
* @param document the document being modified
* @param position the position to be checked
* @param partitioning the document partitioning
* @return <code>true</code> if <code>position</code> is in the default partition of <code>document</code>, <code>false</code> otherwise
*/
private static boolean isDefaultPartition(IDocument document, int position, String partitioning) {
Assert.isTrue(position >= 0);
Assert.isTrue(position <= document.getLength());
try {
ITypedRegion region= TextUtilities.getPartition(document, partitioning, position);
return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE);
} catch (BadLocationException e) {
}
return false;
}
/**
* Finds the position of the parenthesis matching the closing parenthesis at <code>position</code>.
*
* @param document the document being modified
* @param position the position in <code>document</code> of a closing parenthesis
* @param partitioning the document partitioning
* @return the position in <code>document</code> of the matching parenthesis, or -1 if none can be found
*/
private static int findOpeningParenMatch(IDocument document, int position, String partitioning) {
final char CLOSING_PAREN= ')';
final char OPENING_PAREN= '(';
Assert.isTrue(position < document.getLength());
Assert.isTrue(position >= 0);
Assert.isTrue(isDefaultPartition(document, position, partitioning));
try {
Assert.isTrue(document.getChar(position) == CLOSING_PAREN);
int depth= 1;
while (true) {
position= scanBackward(document, position - 1, partitioning, -1, new char[] {CLOSING_PAREN, OPENING_PAREN});
if (position == -1)
return -1;
if (document.getChar(position) == CLOSING_PAREN)
depth++;
else
depth--;
if (depth == 0)
return position;
}
} catch (BadLocationException e) {
return -1;
}
}
/**
* Checks whether, to the left of <code>position</code> and separated only by whitespace,
* <code>document</code> contains a keyword taking a parameter list and a block after it.
* These are: <code>if</code>, <code>while</code>, <code>catch</code>, <code>for</code>, <code>synchronized</code>, <code>switch</code>.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if <code>document</code> contains any of the above keywords to the left of <code>position</code>, <code>false</code> otherwise
*/
private static boolean looksLikeIfWhileForCatch(IDocument document, int position, String partitioning) {
position= firstNonWhitespaceBackward(document, position, partitioning, -1);
if (position == -1)
return false;
return looksLike(document, position, "if") //$NON-NLS-1$
|| looksLike(document, position, "while") //$NON-NLS-1$
|| looksLike(document, position, "catch") //$NON-NLS-1$
|| looksLike(document, position, "synchronized") //$NON-NLS-1$
|| looksLike(document, position, "switch") //$NON-NLS-1$
|| looksLike(document, position, "for"); //$NON-NLS-1$
}
/**
* Checks whether code>document</code> contains the <code>String</code> <code>like</code> such
* that its last character is at <code>position</code>. If <code>like</code> starts with a
* identifier part (as determined by {@link Character.isJavaIdentifier(char)}), it is also made
* sure that <code>like</code> is preceded by some non-identifier character or stands at the
* document start.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param like the <code>String</code> to look for.
* @return <code>true</code> if <code>document</code> contains <code>like</code> such that it ends at <code>position</code>, <code>false</code> otherwise
*/
private static boolean looksLike(IDocument document, int position, String like) {
int length= like.length();
if (position < length - 1)
return false;
try {
if (!like.equals(document.get(position - length + 1, length)))
return false;
if (position >= length && Character.isJavaIdentifierPart(like.charAt(0)) && Character.isJavaIdentifierPart(document.getChar(position - length)))
return false;
} catch (BadLocationException e) {
return false;
}
return true;
}
/**
* Checks whether the content of <code>document</code> at <code>position</code> looks like a
* method declaration header (i.e. only the return type and method name). <code>position</code>
* must be just left of the opening parenthesis of the parameter list.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if the content of <code>document</code> looks like a method definition, <code>false</code> otherwise
*/
private static boolean looksLikeMethodDecl(IDocument document, int position, String partitioning) {
// method name
position= eatIdentToLeft(document, position, partitioning);
if (position < 1)
return false;
position= eatBrackets(document, position - 1, partitioning);
if (position < 1)
return false;
position= eatIdentToLeft(document, position - 1, partitioning);
return position != -1;
}
/**
* From <code>position</code> to the left, eats any whitespace and then a pair of brackets
* as used to declare an array return type like <pre>String [ ]</pre>.
* The return value is either the position of the opening bracket or <code>position</code> if no
* pair of brackets can be parsed.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return the smallest character position of bracket pair or <code>position</code>
*/
private static int eatBrackets(IDocument document, int position, String partitioning) {
// accept array return type
int pos= firstNonWhitespaceBackward(document, position, partitioning, -1);
try {
if (pos > 1 && document.getChar(pos) == ']') {
pos= firstNonWhitespaceBackward(document, pos - 1, partitioning, -1);
if (pos > 0 && document.getChar(pos) == '[')
return pos;
}
} catch (BadLocationException e) {
// won't happen
}
return position;
}
/**
* From <code>position</code> to the left, eats any whitespace and the first identifier, returning
* the position of the first identifier character (in normal read order).
* <p>When called on a document with content <code>" some string "</code> and positionition 13, the
* return value will be 6 (the first letter in <code>string</code>).
* </p>
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return the smallest character position of an identifier or -1 if none can be found; always <= <code>position</code>
*/
private static int eatIdentToLeft(IDocument document, int position, String partitioning) {
if (position < 0)
return -1;
Assert.isTrue(position < document.getLength());
int p= firstNonWhitespaceBackward(document, position, partitioning, -1);
if (p == -1)
return -1;
try {
while (p >= 0) {
char ch= document.getChar(p);
if (Character.isJavaIdentifierPart(ch)) {
p--;
continue;
}
// length must be > 0
if (Character.isWhitespace(ch) && p != position)
return p + 1;
else
return -1;
}
// start of document reached
return 0;
} catch (BadLocationException e) {
}
return -1;
}
/**
* Returns a position in the first java partition after the last non-empty and non-comment partition.
* There is no non-whitespace from the returned position to the end of the partition it is contained in.
*
* @param document the document being modified
* @param line the line under investigation
* @param offset the caret offset into <code>line</code>
* @param partitioning the document partitioning
* @return the position of the next Java partition, or the end of <code>line</code>
*/
private static int nextPartitionOrLineEnd(IDocument document, ITextSelection line, int offset, String partitioning) {
// run relative to document
final int docOffset= offset + line.getOffset();
final int eol= line.getOffset() + line.getLength();
int nextPartitionPos= eol; // init with line end
int validPosition= docOffset;
try {
ITypedRegion partition= TextUtilities.getPartition(document, partitioning, nextPartitionPos);
validPosition= getValidPositionForPartition(document, partition, eol);
while (validPosition == -1) {
nextPartitionPos= partition.getOffset() - 1;
if (nextPartitionPos <= docOffset) {
validPosition= docOffset;
break;
}
partition= TextUtilities.getPartition(document, partitioning, nextPartitionPos);
validPosition= getValidPositionForPartition(document, partition, eol);
}
} catch (BadLocationException e) {
}
validPosition= Math.max(validPosition, docOffset);
// make relative to line
validPosition -= line.getOffset();
return validPosition;
}
/**
* Returns a valid insert location (except for whitespace) in <code>partition</code> or -1 if
* there is no valid insert location.
* An valid insert location is right after any java string or character partition, or at the end
* of a java default partition, but never behind <code>maxOffset</code>. Comment partitions or
* empty java partitions do never yield valid insert positions.
*
* @param doc the document being modified
* @param partition the current partition
* @param maxOffset the maximum offset to consider
* @return a valid insert location in <code>partition</code>, or -1 if there is no valid insert location
*/
private static int getValidPositionForPartition(IDocument doc, ITypedRegion partition, int maxOffset) {
final int INVALID= -1;
if (IJavaPartitions.JAVA_DOC.equals(partition.getType()))
return INVALID;
if (IJavaPartitions.JAVA_MULTI_LINE_COMMENT.equals(partition.getType()))
return INVALID;
if (IJavaPartitions.JAVA_SINGLE_LINE_COMMENT.equals(partition.getType()))
return INVALID;
int endOffset= Math.min(maxOffset, partition.getOffset() + partition.getLength());
if (IJavaPartitions.JAVA_CHARACTER.equals(partition.getType()))
return endOffset;
if (IJavaPartitions.JAVA_STRING.equals(partition.getType()))
return endOffset;
if (IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())) {
try {
if (doc.get(partition.getOffset(), endOffset - partition.getOffset()).trim().length() == 0)
return INVALID;
else
return endOffset;
} catch (BadLocationException e) {
return INVALID;
}
}
// default: we don't know anything about the partition - assume valid
return endOffset;
}
/**
* Determines whether the current line contains a for statement.
* Algorithm: any "for" word in the line is a positive, "for" contained in a string literal will
* produce a false positive.
*
* @param line the line where the change is being made
* @param offset the position of the caret
* @return <code>true</code> if <code>line</code> contains <code>for</code>, <code>false</code> otherwise
*/
private static boolean isForStatement(String line, int offset) {
/* searching for (^|\s)for(\s|$) */
int forPos= line.indexOf("for"); //$NON-NLS-1$
if (forPos != -1) {
if ((forPos == 0 || !Character.isJavaIdentifierPart(line.charAt(forPos - 1))) && (line.length() == forPos + 3 || !Character.isJavaIdentifierPart(line.charAt(forPos + 3))))
return true;
}
return false;
}
/**
* Returns the position in <code>text</code> after which there comes only whitespace, up to
* <code>offset</code>.
*
* @param text the text being searched
* @param offset the maximum offset to search for
* @return the smallest value <code>v</code> such that <code>text.substring(v, offset).trim() == 0</code>
*/
private static int startOfWhitespaceBeforeOffset(String text, int offset) {
int i= Math.min(offset, text.length());
for (; i >= 1; i--) {
if (!Character.isWhitespace(text.charAt(i - 1)))
break;
}
return i;
}
}
|
24,008 |
Bug 24008 (automatic) Global Replace
|
Currently it is only possible to do a global replace, by first searching and then replace each occurrence manually. While this ensures that nothing is accidentally replaced, it is awful if you have use cases like the following: - I want to replace "DAO" to "Dao" and "XML" to "Xml" in all methods, classes, attributes, local variables etc. - I want to replace the copyright in all files - I want to replace all 'a' (german special character) to "ae" or "ä" - I want to rename all classes that end with "Helper" to "Service" These kinds of things happen quite frequently if you incorporate code from one project into another because the responsibility for the code has changed or after a merger of two groups/companies. Often these to groups had different style guides that should now be consolidated. Or imagine taking over the ORO and the OJB stuff in the Jakarte project. And even if it would be better to have refactorings, a pragmatic approache sounds much better to me.
|
resolved fixed
|
c8c6e3f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T16:57:02Z | 2002-09-24T06:46:40Z |
org.eclipse.jdt.ui/core
| |
24,008 |
Bug 24008 (automatic) Global Replace
|
Currently it is only possible to do a global replace, by first searching and then replace each occurrence manually. While this ensures that nothing is accidentally replaced, it is awful if you have use cases like the following: - I want to replace "DAO" to "Dao" and "XML" to "Xml" in all methods, classes, attributes, local variables etc. - I want to replace the copyright in all files - I want to replace all 'a' (german special character) to "ae" or "ä" - I want to rename all classes that end with "Helper" to "Service" These kinds of things happen quite frequently if you incorporate code from one project into another because the responsibility for the code has changed or after a merger of two groups/companies. Often these to groups had different style guides that should now be consolidated. Or imagine taking over the ORO and the OJB stuff in the Jakarte project. And even if it would be better to have refactorings, a pragmatic approache sounds much better to me.
|
resolved fixed
|
c8c6e3f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T16:57:02Z | 2002-09-24T06:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/util/QualifiedNameFinder.java
| |
46,351 |
Bug 46351 Call Hierarchy must not implement IViewSite [call hierarchy]
|
I20031105 The call hierarchy component implements IViewSite which is not allowed. There seems to be no reason for doing so: the CallHierarchyViewPart should directly set the selection provider to its site.
|
resolved fixed
|
dd173ad
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T17:26:45Z | 2003-11-10T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/CallHierarchyContentProvider.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:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.internal.corext.callhierarchy.MethodWrapper;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
public class CallHierarchyContentProvider implements ITreeContentProvider {
private final static Object[] EMPTY_ARRAY = new Object[0];
private class MethodWrapperRunnable implements IRunnableWithProgress {
private MethodWrapper fMethodWrapper;
private MethodWrapper[] fCalls= null;
MethodWrapperRunnable(MethodWrapper methodWrapper) {
fMethodWrapper= methodWrapper;
}
public void run(IProgressMonitor pm) throws InvocationTargetException {
fCalls= fMethodWrapper.getCalls(pm);
}
MethodWrapper[] getCalls() {
if (fCalls != null) {
return fCalls;
}
return new MethodWrapper[0];
}
}
public CallHierarchyContentProvider() {
super();
}
/**
* @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
*/
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof TreeRoot) {
TreeRoot dummyRoot = (TreeRoot) parentElement;
return new Object[] { dummyRoot.getRoot() };
} else if (parentElement instanceof MethodWrapper) {
MethodWrapper methodWrapper = ((MethodWrapper) parentElement);
if (shouldStopTraversion(methodWrapper)) {
return EMPTY_ARRAY;
} else {
IRunnableContext context= JavaPlugin.getActiveWorkbenchWindow();
MethodWrapperRunnable runnable= new MethodWrapperRunnable(methodWrapper);
try {
context.run(true, true, runnable);
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, CallHierarchyMessages.getString("CallHierarchyContentProvider.searchError.title"), CallHierarchyMessages.getString("CallHierarchyContentProvider.searchError.message")); //$NON-NLS-1$ //$NON-NLS-2$
return EMPTY_ARRAY;
} catch (InterruptedException e) {
return new Object[] { TreeTermination.SEARCH_CANCELED };
}
return runnable.getCalls();
}
}
return EMPTY_ARRAY;
}
private boolean shouldStopTraversion(MethodWrapper methodWrapper) {
return (methodWrapper.getLevel() > CallHierarchyUI.getDefault().getMaxCallDepth()) || methodWrapper.isRecursive();
}
/**
* @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
public Object[] getElements(Object inputElement) {
return getChildren(inputElement);
}
/**
* @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object)
*/
public Object getParent(Object element) {
if (element instanceof MethodWrapper) {
return ((MethodWrapper) element).getParent();
}
return null;
}
/**
* @see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
public void dispose() {}
/**
* @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object)
*/
public boolean hasChildren(Object element) {
if (element == TreeRoot.EMPTY_ROOT || element == TreeTermination.SEARCH_CANCELED) {
return false;
}
// Only methods can have subelements, so there's no need to fool the user into believing that there is more
if (element instanceof MethodWrapper) {
MethodWrapper methodWrapper= (MethodWrapper) element;
if (methodWrapper.getMember().getElementType() != IJavaElement.METHOD) {
return false;
}
if (shouldStopTraversion(methodWrapper)) {
return false;
}
}
return true;
}
/**
* @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
|
46,351 |
Bug 46351 Call Hierarchy must not implement IViewSite [call hierarchy]
|
I20031105 The call hierarchy component implements IViewSite which is not allowed. There seems to be no reason for doing so: the CallHierarchyViewPart should directly set the selection provider to its site.
|
resolved fixed
|
dd173ad
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T17:26:45Z | 2003-11-10T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/CallHierarchyLabelDecorator.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:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.viewsupport.ImageImageDescriptor;
import org.eclipse.jdt.internal.corext.callhierarchy.MethodWrapper;
/**
* LabelDecorator that decorates an method's image with recursion overlays.
* The viewer using this decorator is responsible for updating the images on element changes.
*/
public class CallHierarchyLabelDecorator implements ILabelDecorator {
/**
* Creates a decorator. The decorator creates an own image registry to cache
* images.
*/
public CallHierarchyLabelDecorator() {
}
/* (non-Javadoc)
* @see ILabelDecorator#decorateText(String, Object)
*/
public String decorateText(String text, Object element) {
return text;
}
/* (non-Javadoc)
* @see ILabelDecorator#decorateImage(Image, Object)
*/
public Image decorateImage(Image image, Object element) {
int adornmentFlags= computeAdornmentFlags(element);
if (adornmentFlags != 0) {
ImageDescriptor baseImage= new ImageImageDescriptor(image);
Rectangle bounds= image.getBounds();
return JavaPlugin.getImageDescriptorRegistry().get(new CallHierarchyImageDescriptor(baseImage, adornmentFlags, new Point(bounds.width, bounds.height)));
}
return image;
}
/**
* Note: This method is for internal use only. Clients should not call this method.
*/
private int computeAdornmentFlags(Object element) {
int flags= 0;
if (element instanceof MethodWrapper) {
MethodWrapper methodWrapper= (MethodWrapper) element;
if (methodWrapper.isRecursive()) {
flags= CallHierarchyImageDescriptor.RECURSIVE;
}
if (methodWrapper.getDirection() == MethodWrapper.DIRECTION_CALLER) {
flags|= CallHierarchyImageDescriptor.CALLER;
} else {
flags|= CallHierarchyImageDescriptor.CALLEE;
}
if (isMaxCallDepthExceeded(methodWrapper)) {
flags|= CallHierarchyImageDescriptor.MAX_LEVEL;
}
}
return flags;
}
private boolean isMaxCallDepthExceeded(MethodWrapper methodWrapper) {
return methodWrapper.getLevel() > CallHierarchyUI.getDefault().getMaxCallDepth();
}
/* (non-Javadoc)
* @see IBaseLabelProvider#addListener(ILabelProviderListener)
*/
public void addListener(ILabelProviderListener listener) {
}
/* (non-Javadoc)
* @see IBaseLabelProvider#dispose()
*/
public void dispose() {
}
/* (non-Javadoc)
* @see IBaseLabelProvider#isLabelProperty(Object, String)
*/
public boolean isLabelProperty(Object element, String property) {
return true;
}
/* (non-Javadoc)
* @see IBaseLabelProvider#removeListener(ILabelProviderListener)
*/
public void removeListener(ILabelProviderListener listener) {
}
}
|
46,351 |
Bug 46351 Call Hierarchy must not implement IViewSite [call hierarchy]
|
I20031105 The call hierarchy component implements IViewSite which is not allowed. There seems to be no reason for doing so: the CallHierarchyViewPart should directly set the selection provider to its site.
|
resolved fixed
|
dd173ad
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T17:26:45Z | 2003-11-10T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/CallHierarchyUI.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:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.OpenStrategy;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.OpenActionUtil;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.corext.callhierarchy.CallHierarchy;
import org.eclipse.jdt.internal.corext.callhierarchy.CallLocation;
import org.eclipse.jdt.internal.corext.callhierarchy.MethodWrapper;
public class CallHierarchyUI {
private static final int DEFAULT_MAX_CALL_DEPTH= 10;
private static final String PREF_MAX_CALL_DEPTH = "PREF_MAX_CALL_DEPTH"; //$NON-NLS-1$
private static CallHierarchyUI fgInstance;
private CallHierarchyUI() { }
public static CallHierarchyUI getDefault() {
if (fgInstance == null) {
fgInstance = new CallHierarchyUI();
}
return fgInstance;
}
/**
* Returns the maximum tree level allowed
* @return int
*/
public int getMaxCallDepth() {
int maxCallDepth;
IPreferenceStore settings = JavaPlugin.getDefault().getPreferenceStore();
maxCallDepth = settings.getInt(PREF_MAX_CALL_DEPTH);
if (maxCallDepth < 1 || maxCallDepth > 99) {
maxCallDepth= DEFAULT_MAX_CALL_DEPTH;
}
return maxCallDepth;
}
public void setMaxCallDepth(int maxCallDepth) {
IPreferenceStore settings = JavaPlugin.getDefault().getPreferenceStore();
settings.setValue(PREF_MAX_CALL_DEPTH, maxCallDepth);
}
public static void jumpToMember(IJavaElement element) {
if (element != null) {
try {
IEditorPart methodEditor = EditorUtility.openInEditor(element, true);
JavaUI.revealInEditor(methodEditor, element);
} catch (JavaModelException e) {
JavaPlugin.log(e);
} catch (PartInitException e) {
JavaPlugin.log(e);
}
}
}
public static void jumpToLocation(CallLocation callLocation) {
try {
IEditorPart methodEditor = EditorUtility.openInEditor(callLocation.getMember(),
false);
if (methodEditor instanceof ITextEditor) {
ITextEditor editor = (ITextEditor) methodEditor;
editor.selectAndReveal(callLocation.getStart(),
(callLocation.getEnd() - callLocation.getStart()));
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
} catch (PartInitException e) {
JavaPlugin.log(e);
}
}
public static void openInEditor(Object element, Shell shell, String title) {
CallLocation callLocation= CallHierarchy.getCallLocation(element);
if (callLocation == null) {
return;
}
try {
boolean activateOnOpen = OpenStrategy.activateOnOpen();
IEditorPart methodEditor = EditorUtility.openInEditor(callLocation.getMember(),
activateOnOpen);
if (methodEditor instanceof ITextEditor) {
ITextEditor editor = (ITextEditor) methodEditor;
editor.selectAndReveal(callLocation.getStart(),
(callLocation.getEnd() - callLocation.getStart()));
}
} catch (JavaModelException e) {
JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(),
IJavaStatusConstants.INTERNAL_ERROR,
CallHierarchyMessages.getString(
"CallHierarchyUI.open_in_editor.error.message"), e)); //$NON-NLS-1$
ErrorDialog.openError(shell, title,
CallHierarchyMessages.getString(
"CallHierarchyUI.open_in_editor.error.messageProblems"), //$NON-NLS-1$
e.getStatus());
} catch (PartInitException x) {
String name = callLocation.getCalledMember().getElementName();
MessageDialog.openError(shell,
CallHierarchyMessages.getString(
"CallHierarchyUI.open_in_editor.error.messageProblems"), //$NON-NLS-1$
CallHierarchyMessages.getFormattedString(
"CallHierarchyUI.open_in_editor.error.messageArgs", //$NON-NLS-1$
new String[] { name, x.getMessage() }));
}
}
/**
* @param elem
* @return
*/
public static IEditorPart isOpenInEditor(Object elem) {
IJavaElement javaElement= null;
if (elem instanceof MethodWrapper) {
javaElement= ((MethodWrapper) elem).getMember();
} else if (elem instanceof CallLocation) {
javaElement= ((CallLocation) elem).getCalledMember();
}
if (javaElement != null) {
return EditorUtility.isOpenInEditor(javaElement);
}
return null;
}
/**
* Converts the input to a possible input candidates
*/
public static IJavaElement[] getCandidates(Object input) {
if (!(input instanceof IJavaElement)) {
return null;
}
IJavaElement elem= (IJavaElement) input;
if (elem.getElementType() == IJavaElement.METHOD) {
return new IJavaElement[] { elem };
}
return null;
}
public static CallHierarchyViewPart open(IJavaElement[] candidates, IWorkbenchWindow window) {
Assert.isTrue(candidates != null && candidates.length != 0);
IJavaElement input= null;
if (candidates.length > 1) {
String title= CallHierarchyMessages.getString("CallHierarchyUI.selectionDialog.title"); //$NON-NLS-1$
String message= CallHierarchyMessages.getString("CallHierarchyUI.selectionDialog.message"); //$NON-NLS-1$
input= OpenActionUtil.selectJavaElement(candidates, window.getShell(), title, message);
} else {
input= candidates[0];
}
if (input == null)
return null;
return openInViewPart(window, input);
}
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);
}
private static CallHierarchyViewPart openInViewPart(IWorkbenchWindow window, IJavaElement input) {
IWorkbenchPage page= window.getActivePage();
try {
CallHierarchyViewPart result= (CallHierarchyViewPart)page.showView(CallHierarchyViewPart.ID_CALL_HIERARCHY);
result.setMethod((IMethod)input);
openEditor(input, false);
return result;
} catch (CoreException e) {
ExceptionHandler.handle(e, window.getShell(),
CallHierarchyMessages.getString("CallHierarchyUI.error.open_view"), e.getMessage()); //$NON-NLS-1$
}
return null;
}
}
|
46,351 |
Bug 46351 Call Hierarchy must not implement IViewSite [call hierarchy]
|
I20031105 The call hierarchy component implements IViewSite which is not allowed. There seems to be no reason for doing so: the CallHierarchyViewPart should directly set the selection provider to its site.
|
resolved fixed
|
dd173ad
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T17:26:45Z | 2003-11-10T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/CallHierarchyViewAdapter.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:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPropertyListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
/**
* This class adapts a Call Hierarchy view to return an adapted Call Hierarchy view site.
*
* @see org.eclipse.jdt.internal.ui.callhierarchy.CallHierarchyViewSiteAdapter
*/
class CallHierarchyViewAdapter implements IViewPart, ICallHierarchyViewPart {
private IViewSite fSite;
/**
* Constructor for SearchViewAdapter.
*/
public CallHierarchyViewAdapter(IViewSite site) {
fSite= site;
}
/**
* @see org.eclipse.ui.IWorkbenchPart#getSite()
*/
public IWorkbenchPartSite getSite() {
return fSite;
}
/*
* @see org.eclipse.ui.IViewPart#getViewSite()
*/
public IViewSite getViewSite() {
return fSite;
}
// --------- only empty stubs below ---------
/*
* @see org.eclipse.ui.IViewPart#init(IViewSite)
*/
public void init(IViewSite site) throws PartInitException {
}
/*
* @see org.eclipse.ui.IViewPart#init(IViewSite, IMemento)
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
}
/*
* @see org.eclipse.ui.IViewPart#saveState(IMemento)
*/
public void saveState(IMemento memento) {
}
/*
* @see org.eclipse.ui.IWorkbenchPart#addPropertyListener(IPropertyListener)
*/
public void addPropertyListener(IPropertyListener listener) {
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
}
/*
* @see org.eclipse.ui.IWorkbenchPart#dispose()
*/
public void dispose() {
}
/*
* @see org.eclipse.ui.IWorkbenchPart#getTitle()
*/
public String getTitle() {
return null;
}
/*
* @see org.eclipse.ui.IWorkbenchPart#getTitleImage()
*/
public Image getTitleImage() {
return null;
}
/*
* @see org.eclipse.ui.IWorkbenchPart#getTitleToolTip()
*/
public String getTitleToolTip() {
return null;
}
/*
* @see org.eclipse.ui.IWorkbenchPart#removePropertyListener(IPropertyListener)
*/
public void removePropertyListener(IPropertyListener listener) {
}
/*
* @see org.eclipse.ui.IWorkbenchPart#setFocus()
*/
public void setFocus() {
}
/*
* @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class)
*/
public Object getAdapter(Class adapter) {
return null;
}
}
|
46,351 |
Bug 46351 Call Hierarchy must not implement IViewSite [call hierarchy]
|
I20031105 The call hierarchy component implements IViewSite which is not allowed. There seems to be no reason for doing so: the CallHierarchyViewPart should directly set the selection provider to its site.
|
resolved fixed
|
dd173ad
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T17:26:45Z | 2003-11-10T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/CallHierarchyViewPart.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:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IOpenListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.PageBook;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
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.RefactorActionGroup;
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.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.JdtViewerDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
import org.eclipse.jdt.internal.corext.callhierarchy.CallHierarchy;
import org.eclipse.jdt.internal.corext.callhierarchy.CallLocation;
import org.eclipse.jdt.internal.corext.callhierarchy.MethodWrapper;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
/**
* This is the main view for the callers plugin. It builds a tree of callers/callees
* and allows the user to double click an entry to go to the selected method.
*
*/
public class CallHierarchyViewPart extends ViewPart implements ICallHierarchyViewPart, IDoubleClickListener,
ISelectionChangedListener {
private CallHierarchyViewSiteAdapter fViewSiteAdapter;
private CallHierarchyViewAdapter fViewAdapter;
private static final String DIALOGSTORE_VIEWORIENTATION = "CallHierarchyViewPart.orientation"; //$NON-NLS-1$
private static final String DIALOGSTORE_CALL_MODE = "CallHierarchyViewPart.call_mode"; //$NON-NLS-1$
private static final String TAG_ORIENTATION = "orientation"; //$NON-NLS-1$
private static final String TAG_CALL_MODE = "call_mode"; //$NON-NLS-1$
private static final String TAG_IMPLEMENTORS_MODE = "implementors_mode"; //$NON-NLS-1$
private static final String TAG_RATIO = "ratio"; //$NON-NLS-1$
static final int VIEW_ORIENTATION_VERTICAL = 0;
static final int VIEW_ORIENTATION_HORIZONTAL = 1;
static final int VIEW_ORIENTATION_SINGLE = 2;
static final int CALL_MODE_CALLERS = 0;
static final int CALL_MODE_CALLEES = 1;
static final int IMPLEMENTORS_ENABLED = 0;
static final int IMPLEMENTORS_DISABLED = 1;
static final String GROUP_SEARCH_SCOPE = "MENU_SEARCH_SCOPE"; //$NON-NLS-1$
static final String ID_CALL_HIERARCHY = "org.eclipse.jdt.callhierarchy.view"; //$NON-NLS-1$
private static final String GROUP_FOCUS = "group.focus"; //$NON-NLS-1$
private static final int PAGE_EMPTY = 0;
private static final int PAGE_VIEWER = 1;
private Label fNoHierarchyShownLabel;
private PageBook fPagebook;
private IDialogSettings fDialogSettings;
private int fCurrentOrientation;
private int fCurrentCallMode;
private int fCurrentImplementorsMode;
private MethodWrapper fCalleeRoot;
private MethodWrapper fCallerRoot;
private IMemento fMemento;
private IMethod fShownMethod;
private SelectionProviderMediator fSelectionProviderMediator;
private List fMethodHistory;
private LocationViewer fLocationViewer;
private SashForm fHierarchyLocationSplitter;
private Clipboard fClipboard;
private SearchScopeActionGroup fSearchScopeActions;
private ToggleOrientationAction[] fToggleOrientationActions;
private ToggleCallModeAction[] fToggleCallModeActions;
private ToggleImplementorsAction[] fToggleImplementorsActions;
private CallHierarchyFiltersActionGroup fFiltersActionGroup;
private HistoryDropDownAction fHistoryDropDownAction;
private RefreshAction fRefreshAction;
private OpenLocationAction fOpenLocationAction;
private FocusOnSelectionAction fFocusOnSelectionAction;
private CopyCallHierarchyAction fCopyAction;
private CompositeActionGroup fActionGroups;
private CallHierarchyViewer fCallHierarchyViewer;
private boolean fShowCallDetails;
public CallHierarchyViewPart() {
super();
fDialogSettings = JavaPlugin.getDefault().getDialogSettings();
fMethodHistory = new ArrayList();
}
public void setFocus() {
fPagebook.setFocus();
}
/**
* Sets the history entries
*/
public void setHistoryEntries(IMethod[] elems) {
fMethodHistory.clear();
for (int i = 0; i < elems.length; i++) {
fMethodHistory.add(elems[i]);
}
updateHistoryEntries();
}
/**
* Gets all history entries.
*/
public IMethod[] getHistoryEntries() {
if (fMethodHistory.size() > 0) {
updateHistoryEntries();
}
return (IMethod[]) fMethodHistory.toArray(new IMethod[fMethodHistory.size()]);
}
/**
* Method setMethod.
* @param method
*/
public void setMethod(IMethod method) {
if (method == null) {
showPage(PAGE_EMPTY);
return;
}
method= (IMethod) JavaModelUtil.toOriginal(method);
if ((method != null) && !method.equals(fShownMethod)) {
addHistoryEntry(method);
}
this.fShownMethod = method;
refresh();
}
public IMethod getMethod() {
return fShownMethod;
}
public MethodWrapper getCurrentMethodWrapper() {
if (fCurrentCallMode == CALL_MODE_CALLERS) {
return fCallerRoot;
} else {
return fCalleeRoot;
}
}
/**
* called from ToggleOrientationAction.
* @param orientation VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL
*/
void setOrientation(int orientation) {
if (fCurrentOrientation != orientation) {
if ((fLocationViewer != null) && !fLocationViewer.getControl().isDisposed() &&
(fHierarchyLocationSplitter != null) &&
!fHierarchyLocationSplitter.isDisposed()) {
if (orientation == VIEW_ORIENTATION_SINGLE) {
setShowCallDetails(false);
} else {
if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) {
setShowCallDetails(true);
}
boolean horizontal = orientation == VIEW_ORIENTATION_HORIZONTAL;
fHierarchyLocationSplitter.setOrientation(horizontal ? SWT.HORIZONTAL
: SWT.VERTICAL);
}
fHierarchyLocationSplitter.layout();
}
for (int i = 0; i < fToggleOrientationActions.length; i++) {
fToggleOrientationActions[i].setChecked(orientation == fToggleOrientationActions[i].getOrientation());
}
fCurrentOrientation = orientation;
fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, orientation);
}
}
/**
* called from ToggleCallModeAction.
* @param orientation CALL_MODE_CALLERS or CALL_MODE_CALLEES
*/
void setCallMode(int mode) {
if (fCurrentCallMode != mode) {
for (int i = 0; i < fToggleCallModeActions.length; i++) {
fToggleCallModeActions[i].setChecked(mode == fToggleCallModeActions[i].getMode());
}
fCurrentCallMode = mode;
fDialogSettings.put(DIALOGSTORE_CALL_MODE, mode);
updateView();
}
}
/**
* called from ToggleImplementorsAction.
* @param implementorsMode IMPLEMENTORS_USED or IMPLEMENTORS_NOT_USED
*/
void setImplementorsMode(int implementorsMode) {
if (fCurrentImplementorsMode != implementorsMode) {
for (int i = 0; i < fToggleImplementorsActions.length; i++) {
fToggleImplementorsActions[i].setChecked(implementorsMode == fToggleImplementorsActions[i].getImplementorsMode());
}
fCurrentImplementorsMode = implementorsMode;
CallHierarchy.getDefault().setSearchUsingImplementorsEnabled(implementorsMode == IMPLEMENTORS_ENABLED);
updateView();
}
}
public IJavaSearchScope getSearchScope() {
return fSearchScopeActions.getSearchScope();
}
public void setShowCallDetails(boolean show) {
fShowCallDetails = show;
showOrHideCallDetailsView();
}
private void initDragAndDrop() {
Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() };
int ops= DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK;
addDragAdapters(fCallHierarchyViewer, ops, transfers);
addDropAdapters(fCallHierarchyViewer, ops | DND.DROP_DEFAULT, transfers);
addDropAdapters(fLocationViewer, ops | DND.DROP_DEFAULT, transfers);
//dnd on empty hierarchy
DropTarget dropTarget = new DropTarget(fNoHierarchyShownLabel, ops | DND.DROP_DEFAULT);
dropTarget.setTransfer(transfers);
dropTarget.addDropListener(new CallHierarchyTransferDropAdapter(this, fCallHierarchyViewer));
}
private void addDropAdapters(StructuredViewer viewer, int ops, Transfer[] transfers){
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new CallHierarchyTransferDropAdapter(this, viewer)
};
viewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
}
private void addDragAdapters(StructuredViewer viewer, int ops, Transfer[] transfers) {
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(new SelectionProviderAdapter(viewer))
};
viewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(viewer, dragListeners));
}
public void createPartControl(Composite parent) {
fPagebook = new PageBook(parent, SWT.NONE);
// Page 1: Viewers
createHierarchyLocationSplitter(fPagebook);
createCallHierarchyViewer(fHierarchyLocationSplitter);
createLocationViewer(fHierarchyLocationSplitter);
// Page 2: Nothing selected
fNoHierarchyShownLabel = new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP);
fNoHierarchyShownLabel.setText(CallHierarchyMessages.getString(
"CallHierarchyViewPart.empty")); //$NON-NLS-1$
initDragAndDrop();
showPage(PAGE_EMPTY);
WorkbenchHelp.setHelp(fPagebook, IJavaHelpContextIds.CALL_HIERARCHY_VIEW);
fSelectionProviderMediator = new SelectionProviderMediator(new Viewer[] {
fCallHierarchyViewer, fLocationViewer
});
IStatusLineManager slManager = getViewSite().getActionBars().getStatusLineManager();
new SelectionProviderAdapter(fSelectionProviderMediator).addSelectionChangedListener(new StatusBarUpdater(
slManager));
getSite().setSelectionProvider(fSelectionProviderMediator);
fClipboard= new Clipboard(parent.getDisplay());
makeActions();
fillViewMenu();
fillActionBars();
initOrientation();
initCallMode();
initImplementorsMode();
if (fMemento != null) {
restoreState(fMemento);
}
}
/**
* @param PAGE_EMPTY
*/
private void showPage(int page) {
if (page == PAGE_EMPTY) {
fPagebook.showPage(fNoHierarchyShownLabel);
} else {
fPagebook.showPage(fHierarchyLocationSplitter);
}
enableActions(page != PAGE_EMPTY);
}
/**
* @param b
*/
private void enableActions(boolean enabled) {
// TODO: Is it possible to disable the actions on the toolbar and on the view menu?
}
/**
* Restores the type hierarchy settings from a memento.
*/
private void restoreState(IMemento memento) {
Integer orientation= memento.getInteger(TAG_ORIENTATION);
if (orientation != null) {
setOrientation(orientation.intValue());
}
Integer callMode= memento.getInteger(TAG_CALL_MODE);
if (callMode != null) {
setCallMode(callMode.intValue());
}
Integer implementorsMode= memento.getInteger(TAG_IMPLEMENTORS_MODE);
if (implementorsMode != null) {
setImplementorsMode(implementorsMode.intValue());
}
Integer ratio = memento.getInteger(TAG_RATIO);
if (ratio != null) {
fHierarchyLocationSplitter.setWeights(new int[] {
ratio.intValue(), 1000 - ratio.intValue()
});
}
fSearchScopeActions.restoreState(memento);
}
private void initCallMode() {
int mode;
try {
mode = fDialogSettings.getInt(DIALOGSTORE_CALL_MODE);
if ((mode < 0) || (mode > 1)) {
mode = CALL_MODE_CALLERS;
}
} catch (NumberFormatException e) {
mode = CALL_MODE_CALLERS;
}
// force the update
fCurrentCallMode = -1;
// will fill the main tool bar
setCallMode(mode);
}
private void initImplementorsMode() {
int mode;
mode= CallHierarchy.getDefault().isSearchUsingImplementorsEnabled() ? IMPLEMENTORS_ENABLED : IMPLEMENTORS_DISABLED;
fCurrentImplementorsMode= -1;
// will fill the main tool bar
setImplementorsMode(mode);
}
private void initOrientation() {
int orientation;
try {
orientation = fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION);
if ((orientation < 0) || (orientation > 2)) {
orientation = VIEW_ORIENTATION_VERTICAL;
}
} catch (NumberFormatException e) {
orientation = VIEW_ORIENTATION_VERTICAL;
}
// force the update
fCurrentOrientation = -1;
// will fill the main tool bar
setOrientation(orientation);
}
private void fillViewMenu() {
IActionBars actionBars = getViewSite().getActionBars();
IMenuManager viewMenu = actionBars.getMenuManager();
viewMenu.add(new Separator());
for (int i = 0; i < fToggleCallModeActions.length; i++) {
viewMenu.add(fToggleCallModeActions[i]);
}
viewMenu.add(new Separator());
// TODO: Should be reenabled if this toggle should actually be used
// for (int i = 0; i < fToggleImplementorsActions.length; i++) {
// viewMenu.add(fToggleImplementorsActions[i]);
// }
//
// viewMenu.add(new Separator());
for (int i = 0; i < fToggleOrientationActions.length; i++) {
viewMenu.add(fToggleOrientationActions[i]);
}
}
/**
*
*/
public void dispose() {
if (fActionGroups != null)
fActionGroups.dispose();
if (fClipboard != null)
fClipboard.dispose();
super.dispose();
}
/**
* Double click listener which jumps to the method in the source code.
*
* @return IDoubleClickListener
*/
public void doubleClick(DoubleClickEvent event) {
jumpToSelection(event.getSelection());
}
/**
* Goes to the selected entry, without updating the order of history entries.
*/
public void gotoHistoryEntry(IMethod entry) {
if (fMethodHistory.contains(entry)) {
setMethod(entry);
}
}
/* (non-Javadoc)
* Method declared on IViewPart.
*/
public void init(IViewSite site, IMemento memento)
throws PartInitException {
super.init(site, memento);
fMemento = memento;
}
public void jumpToDeclarationOfSelection() {
ISelection selection = null;
selection = getSelection();
if ((selection != null) && selection instanceof IStructuredSelection) {
Object structuredSelection = ((IStructuredSelection) selection).getFirstElement();
if (structuredSelection instanceof IMember) {
CallHierarchyUI.jumpToMember((IMember) structuredSelection);
} else if (structuredSelection instanceof MethodWrapper) {
MethodWrapper methodWrapper = (MethodWrapper) structuredSelection;
CallHierarchyUI.jumpToMember(methodWrapper.getMember());
} else if (structuredSelection instanceof CallLocation) {
CallHierarchyUI.jumpToMember(((CallLocation) structuredSelection).getCalledMember());
}
}
}
public void jumpToSelection(ISelection selection) {
if ((selection != null) && selection instanceof IStructuredSelection) {
Object structuredSelection = ((IStructuredSelection) selection).getFirstElement();
if (structuredSelection instanceof MethodWrapper) {
MethodWrapper methodWrapper = (MethodWrapper) structuredSelection;
CallLocation firstCall = methodWrapper.getMethodCall()
.getFirstCallLocation();
if (firstCall != null) {
CallHierarchyUI.jumpToLocation(firstCall);
} else {
CallHierarchyUI.jumpToMember(methodWrapper.getMember());
}
} else if (structuredSelection instanceof CallLocation) {
CallHierarchyUI.jumpToLocation((CallLocation) structuredSelection);
}
}
}
/**
*
*/
public void refresh() {
setCalleeRoot(null);
setCallerRoot(null);
updateView();
}
public void saveState(IMemento memento) {
if (fPagebook == null) {
// part has not been created
if (fMemento != null) { //Keep the old state;
memento.putMemento(fMemento);
}
return;
}
memento.putInteger(TAG_CALL_MODE, fCurrentCallMode);
memento.putInteger(TAG_IMPLEMENTORS_MODE, fCurrentImplementorsMode);
memento.putInteger(TAG_ORIENTATION, fCurrentOrientation);
int[] weigths = fHierarchyLocationSplitter.getWeights();
int ratio = (weigths[0] * 1000) / (weigths[0] + weigths[1]);
memento.putInteger(TAG_RATIO, ratio);
fSearchScopeActions.saveState(memento);
}
/**
* @return ISelectionChangedListener
*/
public void selectionChanged(SelectionChangedEvent e) {
if (e.getSelectionProvider() == fCallHierarchyViewer) {
methodSelectionChanged(e.getSelection());
}
}
/**
* @param selection
*/
private void methodSelectionChanged(ISelection selection) {
if (selection instanceof IStructuredSelection) {
Object selectedElement = ((IStructuredSelection) selection).getFirstElement();
if (selectedElement instanceof MethodWrapper) {
MethodWrapper methodWrapper = (MethodWrapper) selectedElement;
revealElementInEditor(methodWrapper, fCallHierarchyViewer);
updateLocationsView(methodWrapper);
} else {
updateLocationsView(null);
}
}
}
private void revealElementInEditor(Object elem, Viewer originViewer) {
// only allow revealing when the type hierarchy is the active pagae
// no revealing after selection events due to model changes
if (getSite().getPage().getActivePart() != this) {
return;
}
if (fSelectionProviderMediator.getViewerInFocus() != originViewer) {
return;
}
if (elem instanceof MethodWrapper) {
CallLocation callLocation = CallHierarchy.getCallLocation(elem);
if (callLocation != null) {
IEditorPart editorPart = CallHierarchyUI.isOpenInEditor(callLocation);
if (editorPart != null) {
getSite().getPage().bringToTop(editorPart);
if (editorPart instanceof ITextEditor) {
ITextEditor editor = (ITextEditor) editorPart;
editor.selectAndReveal(callLocation.getStart(),
(callLocation.getEnd() - callLocation.getStart()));
}
}
} else {
IEditorPart editorPart = CallHierarchyUI.isOpenInEditor(elem);
getSite().getPage().bringToTop(editorPart);
EditorUtility.revealInEditor(editorPart,
((MethodWrapper) elem).getMember());
}
} else if (elem instanceof IJavaElement) {
IEditorPart editorPart = EditorUtility.isOpenInEditor(elem);
if (editorPart != null) {
// getSite().getPage().removePartListener(fPartListener);
getSite().getPage().bringToTop(editorPart);
EditorUtility.revealInEditor(editorPart, (IJavaElement) elem);
// getSite().getPage().addPartListener(fPartListener);
}
}
}
/**
* Returns the current selection.
*/
protected ISelection getSelection() {
return getSite().getSelectionProvider().getSelection();
}
protected void fillLocationViewerContextMenu(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fOpenLocationAction);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fRefreshAction);
}
protected void handleKeyEvent(KeyEvent event) {
if (event.stateMask == 0) {
if (event.keyCode == SWT.F5) {
if ((fRefreshAction != null) && fRefreshAction.isEnabled()) {
fRefreshAction.run();
return;
}
}
}
}
private IActionBars getActionBars() {
return getViewSite().getActionBars();
}
private void setCalleeRoot(MethodWrapper calleeRoot) {
this.fCalleeRoot = calleeRoot;
}
private MethodWrapper getCalleeRoot() {
if (fCalleeRoot == null) {
fCalleeRoot = CallHierarchy.getDefault().getCalleeRoot(fShownMethod);
}
return fCalleeRoot;
}
private void setCallerRoot(MethodWrapper callerRoot) {
this.fCallerRoot = callerRoot;
}
private MethodWrapper getCallerRoot() {
if (fCallerRoot == null) {
fCallerRoot = CallHierarchy.getDefault().getCallerRoot(fShownMethod);
}
return fCallerRoot;
}
/**
* Adds the entry if new. Inserted at the beginning of the history entries list.
*/
private void addHistoryEntry(IJavaElement entry) {
if (fMethodHistory.contains(entry)) {
fMethodHistory.remove(entry);
}
fMethodHistory.add(0, entry);
fHistoryDropDownAction.setEnabled(!fMethodHistory.isEmpty());
}
/**
* @param parent
*/
private void createLocationViewer(Composite parent) {
fLocationViewer= new LocationViewer(parent);
fLocationViewer.getControl().addKeyListener(createKeyListener());
fLocationViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillLocationViewerContextMenu(menu);
}
}, ID_CALL_HIERARCHY, getSite());
}
private void createHierarchyLocationSplitter(Composite parent) {
fHierarchyLocationSplitter = new SashForm(parent, SWT.NONE);
fHierarchyLocationSplitter.addKeyListener(createKeyListener());
}
private void createCallHierarchyViewer(Composite parent) {
fCallHierarchyViewer = new CallHierarchyViewer(parent, this);
fCallHierarchyViewer.addKeyListener(createKeyListener());
fCallHierarchyViewer.addSelectionChangedListener(this);
fCallHierarchyViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillCallHierarchyViewerContextMenu(menu);
}
}, ID_CALL_HIERARCHY, getSite());
}
/**
* @param fCallHierarchyViewer
* @param menu
*/
protected void fillCallHierarchyViewerContextMenu(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fRefreshAction);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, new Separator(GROUP_FOCUS));
if (fFocusOnSelectionAction.canActionBeAdded()) {
menu.appendToGroup(GROUP_FOCUS, fFocusOnSelectionAction);
}
menu.appendToGroup(GROUP_FOCUS, fCopyAction);
fActionGroups.setContext(new ActionContext(getSelection()));
fActionGroups.fillContextMenu(menu);
fActionGroups.setContext(null);
}
private void fillActionBars() {
IActionBars actionBars = getActionBars();
IToolBarManager toolBar = actionBars.getToolBarManager();
fActionGroups.fillActionBars(actionBars);
toolBar.add(fHistoryDropDownAction);
for (int i = 0; i < fToggleCallModeActions.length; i++) {
toolBar.add(fToggleCallModeActions[i]);
}
}
private KeyListener createKeyListener() {
KeyListener keyListener = new KeyAdapter() {
public void keyReleased(KeyEvent event) {
handleKeyEvent(event);
}
};
return keyListener;
}
/**
*
*/
private void makeActions() {
fRefreshAction = new RefreshAction(this);
fOpenLocationAction = new OpenLocationAction(getSite());
fLocationViewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
fOpenLocationAction.run();
}
});
fFocusOnSelectionAction = new FocusOnSelectionAction(this);
fCopyAction= new CopyCallHierarchyAction(this, fClipboard, fCallHierarchyViewer);
fSearchScopeActions = new SearchScopeActionGroup(this, fDialogSettings);
fFiltersActionGroup = new CallHierarchyFiltersActionGroup(this,
fCallHierarchyViewer);
fHistoryDropDownAction = new HistoryDropDownAction(this);
fHistoryDropDownAction.setEnabled(false);
fToggleOrientationActions = new ToggleOrientationAction[] {
new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE)
};
fToggleCallModeActions = new ToggleCallModeAction[] {
new ToggleCallModeAction(this, CALL_MODE_CALLERS),
new ToggleCallModeAction(this, CALL_MODE_CALLEES)
};
fToggleImplementorsActions = new ToggleImplementorsAction[] {
new ToggleImplementorsAction(this, IMPLEMENTORS_ENABLED),
new ToggleImplementorsAction(this, IMPLEMENTORS_DISABLED)
};
fActionGroups = new CompositeActionGroup(new ActionGroup[] {
new OpenEditorActionGroup(getViewAdapter()),
new OpenViewActionGroup(getViewAdapter()),
new CCPActionGroup(getViewAdapter()),
new GenerateActionGroup(getViewAdapter()),
new RefactorActionGroup(getViewAdapter()),
new JavaSearchActionGroup(getViewAdapter()),
fSearchScopeActions, fFiltersActionGroup
});
}
private CallHierarchyViewAdapter getViewAdapter() {
if (fViewAdapter == null) {
fViewAdapter= new CallHierarchyViewAdapter(getViewSiteAdapter());
}
return fViewAdapter;
}
private CallHierarchyViewSiteAdapter getViewSiteAdapter() {
if (fViewSiteAdapter == null) {
fViewSiteAdapter= new CallHierarchyViewSiteAdapter(this.getViewSite());
}
return fViewSiteAdapter;
}
private void showOrHideCallDetailsView() {
if (fShowCallDetails) {
fHierarchyLocationSplitter.setMaximizedControl(null);
} else {
fHierarchyLocationSplitter.setMaximizedControl(fCallHierarchyViewer.getControl());
}
}
private void updateLocationsView(MethodWrapper methodWrapper) {
if (methodWrapper != null && methodWrapper.getMethodCall().hasCallLocations()) {
fLocationViewer.setInput(methodWrapper.getMethodCall().getCallLocations());
} else {
fLocationViewer.clearViewer();
}
}
private void updateHistoryEntries() {
for (int i = fMethodHistory.size() - 1; i >= 0; i--) {
IMethod method = (IMethod) fMethodHistory.get(i);
if (!method.exists()) {
fMethodHistory.remove(i);
}
}
fHistoryDropDownAction.setEnabled(!fMethodHistory.isEmpty());
}
/**
* Method updateView.
*/
private void updateView() {
if ((fShownMethod != null)) {
clearView();
showPage(PAGE_VIEWER);
CallHierarchy.getDefault().setSearchScope(getSearchScope());
if (fCurrentCallMode == CALL_MODE_CALLERS) {
setTitle(CallHierarchyMessages.getString("CallHierarchyViewPart.callsToMethod")); //$NON-NLS-1$
fCallHierarchyViewer.setMethodWrapper(getCallerRoot());
} else {
setTitle(CallHierarchyMessages.getString("CallHierarchyViewPart.callsFromMethod")); //$NON-NLS-1$
fCallHierarchyViewer.setMethodWrapper(getCalleeRoot());
}
}
}
/**
* Clears both the tree view and the location list.
*/
private void clearView() {
fLocationViewer.clearViewer();
fCallHierarchyViewer.clearViewer();
}
static CallHierarchyViewPart findAndShowCallersView(IWorkbenchPartSite site) {
IWorkbenchPage workbenchPage = site.getPage();
CallHierarchyViewPart callersView = null;
try {
callersView = (CallHierarchyViewPart) workbenchPage.showView(CallHierarchyViewPart.ID_CALL_HIERARCHY);
} catch (PartInitException e) {
JavaPlugin.log(e);
}
return callersView;
}
}
|
46,351 |
Bug 46351 Call Hierarchy must not implement IViewSite [call hierarchy]
|
I20031105 The call hierarchy component implements IViewSite which is not allowed. There seems to be no reason for doing so: the CallHierarchyViewPart should directly set the selection provider to its site.
|
resolved fixed
|
dd173ad
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T17:26:45Z | 2003-11-10T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/CallHierarchyViewSiteAdapter.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:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import org.eclipse.core.runtime.PlatformObject;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IKeyBindingService;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.IWorkbenchWindow;
/**
* This class adapts a Call Hierarchy view site.
* It converts selection of Call Hierarchy view entries to
* be a selection of Java elements.
*
*/
class CallHierarchyViewSiteAdapter extends PlatformObject implements IViewSite {
private ISelectionProvider fProvider;
private IWorkbenchSite fSite;
public CallHierarchyViewSiteAdapter(IWorkbenchSite site){
fSite= site;
setSelectionProvider(site.getSelectionProvider());
}
public IWorkbenchPage getPage() {
return fSite.getPage();
}
public ISelectionProvider getSelectionProvider() {
return fProvider;
}
public Shell getShell() {
return fSite.getShell();
}
public IWorkbenchWindow getWorkbenchWindow() {
return fSite.getWorkbenchWindow();
}
public void setSelectionProvider(final ISelectionProvider provider) {
Assert.isNotNull(provider);
fProvider= new SelectionProviderAdapter(provider);
}
// --------- only empty stubs below ---------
/*
* @see org.eclipse.ui.IWorkbenchPartSite#getId()
*/
public String getId() {
return null;
}
/*
* @see org.eclipse.ui.IWorkbenchPartSite#getKeyBindingService()
*/
public IKeyBindingService getKeyBindingService() {
return null;
}
/*
* @see org.eclipse.ui.IWorkbenchPartSite#getPluginId()
*/
public String getPluginId() {
return null;
}
/*
* @see org.eclipse.ui.IWorkbenchPartSite#getRegisteredName()
*/
public String getRegisteredName() {
return null;
}
/*
* @see org.eclipse.ui.IWorkbenchPartSite#registerContextMenu(MenuManager, ISelectionProvider)
*/
public void registerContextMenu(MenuManager menuManager, ISelectionProvider selectionProvider) {
}
/*
* @see org.eclipse.ui.IWorkbenchPartSite#registerContextMenu(String, MenuManager, ISelectionProvider)
*/
public void registerContextMenu(String menuId, MenuManager menuManager, ISelectionProvider selectionProvider) {
}
/* (non-Javadoc)
* @see org.eclipse.ui.IViewSite#getActionBars()
*/
public IActionBars getActionBars() {
return null;
}
}
|
46,351 |
Bug 46351 Call Hierarchy must not implement IViewSite [call hierarchy]
|
I20031105 The call hierarchy component implements IViewSite which is not allowed. There seems to be no reason for doing so: the CallHierarchyViewPart should directly set the selection provider to its site.
|
resolved fixed
|
dd173ad
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T17:26:45Z | 2003-11-10T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/CallHierarchyViewer.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:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.IOpenListener;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.corext.callhierarchy.MethodWrapper;
class CallHierarchyViewer extends TreeViewer {
private CallHierarchyViewPart fPart;
private OpenLocationAction fOpen;
/**
* @param parent
*/
CallHierarchyViewer(Composite parent, CallHierarchyViewPart part) {
super(new Tree(parent, SWT.SINGLE));
fPart = part;
getControl().setLayoutData(new GridData(GridData.FILL_BOTH));
setUseHashlookup(true);
setAutoExpandLevel(2);
setContentProvider(new CallHierarchyContentProvider());
setLabelProvider(new CallHierarchyLabelProvider());
JavaUIHelp.setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_VIEW);
fOpen= new OpenLocationAction(part.getSite());
addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
fOpen.run();
}
});
clearViewer();
}
/**
* @param wrapper
*/
void setMethodWrapper(MethodWrapper wrapper) {
setInput(getTreeRoot(wrapper));
getTree().setFocus();
getTree().setSelection(new TreeItem[] { getTree().getItems()[0] });
}
CallHierarchyViewPart getPart() {
return fPart;
}
/**
*
*/
void setFocus() {
getControl().setFocus();
}
boolean isInFocus() {
return getControl().isFocusControl();
}
/**
* @param keyListener
*/
void addKeyListener(KeyListener keyListener) {
getControl().addKeyListener(keyListener);
}
/**
* Wraps the root of a MethodWrapper tree in a dummy root in order to show
* it in the tree.
*
* @param root The root of the MethodWrapper tree.
* @return A new MethodWrapper which is a dummy root above the specified root.
*/
private TreeRoot getTreeRoot(MethodWrapper root) {
TreeRoot dummyRoot = new TreeRoot(root);
return dummyRoot;
}
/**
* Attaches a contextmenu listener to the tree
*/
void initContextMenu(IMenuListener menuListener, String popupId, IWorkbenchPartSite viewSite) {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(menuListener);
Menu menu= menuMgr.createContextMenu(getTree());
getTree().setMenu(menu);
viewSite.registerContextMenu(popupId, menuMgr, this);
}
/**
*
*/
void clearViewer() {
setInput(TreeRoot.EMPTY_ROOT);
}
}
|
46,351 |
Bug 46351 Call Hierarchy must not implement IViewSite [call hierarchy]
|
I20031105 The call hierarchy component implements IViewSite which is not allowed. There seems to be no reason for doing so: the CallHierarchyViewPart should directly set the selection provider to its site.
|
resolved fixed
|
dd173ad
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T17:26:45Z | 2003-11-10T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/FocusOnSelectionAction.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:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.util.SelectionUtil;
import org.eclipse.jdt.internal.corext.callhierarchy.MethodWrapper;
class FocusOnSelectionAction extends Action {
private CallHierarchyViewPart fPart;
public FocusOnSelectionAction(CallHierarchyViewPart part) {
super(CallHierarchyMessages.getString("FocusOnSelectionAction.focusOnSelection.text")); //$NON-NLS-1$
fPart= part;
setDescription(CallHierarchyMessages.getString("FocusOnSelectionAction.focusOnSelection.description")); //$NON-NLS-1$
setToolTipText(CallHierarchyMessages.getString("FocusOnSelectionAction.focusOnSelection.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_FOCUS_ON_SELECTION_ACTION);
}
public boolean canActionBeAdded() {
Object element = SelectionUtil.getSingleElement(getSelection());
IMethod method = null;
if (element instanceof IMethod) {
method= (IMethod) element;
} else if (element instanceof MethodWrapper) {
IMember member= ((MethodWrapper) element).getMember();
if (member.getElementType() == IJavaElement.METHOD) {
method= (IMethod) member;
}
}
if (method != null) {
setText(CallHierarchyMessages.getFormattedString("FocusOnSelectionAction.focusOn.text", method.getElementName())); //$NON-NLS-1$
return true;
}
return false;
}
/*
* @see Action#run
*/
public void run() {
Object element = SelectionUtil.getSingleElement(getSelection());
if (element instanceof MethodWrapper) {
IMember member= ((MethodWrapper) element).getMember();
if (member.getElementType() == IJavaElement.METHOD) {
fPart.setMethod((IMethod) member);
}
}
}
private ISelection getSelection() {
ISelectionProvider provider = fPart.getSite().getSelectionProvider();
if (provider != null) {
return provider.getSelection();
}
return null;
}
}
|
46,351 |
Bug 46351 Call Hierarchy must not implement IViewSite [call hierarchy]
|
I20031105 The call hierarchy component implements IViewSite which is not allowed. There seems to be no reason for doing so: the CallHierarchyViewPart should directly set the selection provider to its site.
|
resolved fixed
|
dd173ad
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T17:26:45Z | 2003-11-10T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/OpenCallHierarchyAction.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:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.actions.SelectionDispatchAction;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
/**
* This action opens a call hierarchy on the selected method.
* <p>
* The action is applicable to selections containing elements of type
* <code>IMethod</code>.
*/
public class OpenCallHierarchyAction extends SelectionDispatchAction {
private JavaEditor fEditor;
/**
* Creates a new <code>OpenCallHierarchyAction</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 OpenCallHierarchyAction(IWorkbenchSite site) {
super(site);
setText(CallHierarchyMessages.getString("OpenCallHierarchyAction.label")); //$NON-NLS-1$
setToolTipText(CallHierarchyMessages.getString("OpenCallHierarchyAction.tooltip")); //$NON-NLS-1$
setDescription(CallHierarchyMessages.getString("OpenCallHierarchyAction.description")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_OPEN_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public OpenCallHierarchyAction(JavaEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
setEnabled(SelectionConverter.canOperateOn(fEditor));
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
public void selectionChanged(ITextSelection selection) {
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
public void selectionChanged(IStructuredSelection selection) {
setEnabled(isEnabled(selection));
}
private boolean isEnabled(IStructuredSelection selection) {
if (selection.size() != 1)
return false;
Object input= selection.getFirstElement();
if (!(input instanceof IJavaElement))
return false;
switch (((IJavaElement)input).getElementType()) {
case IJavaElement.METHOD:
return true;
default:
return false;
}
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
public void run(ITextSelection selection) {
IJavaElement input= SelectionConverter.getInput(fEditor);
if (!ActionUtil.isProcessable(getShell(), input))
return;
IJavaElement[] elements= SelectionConverter.codeResolveOrInputHandled(fEditor, getShell(), getDialogTitle());
if (elements == null)
return;
List candidates= new ArrayList(elements.length);
for (int i= 0; i < elements.length; i++) {
IJavaElement[] resolvedElements= CallHierarchyUI.getCandidates(elements[i]);
if (resolvedElements != null)
candidates.addAll(Arrays.asList(resolvedElements));
}
if (candidates.isEmpty()) {
IJavaElement enclosingMethod= getEnclosingMethod(input, selection);
if (enclosingMethod != null) {
candidates.add(enclosingMethod);
}
}
run((IJavaElement[])candidates.toArray(new IJavaElement[candidates.size()]));
}
private IJavaElement getEnclosingMethod(IJavaElement input, ITextSelection selection) {
IJavaElement enclosingElement= null;
try {
switch (input.getElementType()) {
case IJavaElement.CLASS_FILE :
IClassFile classFile= (IClassFile) input.getAncestor(IJavaElement.CLASS_FILE);
if (classFile != null) {
enclosingElement= classFile.getElementAt(selection.getOffset());
}
break;
case IJavaElement.COMPILATION_UNIT :
ICompilationUnit cu= (ICompilationUnit) input.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
enclosingElement= cu.getElementAt(selection.getOffset());
}
break;
}
if (enclosingElement != null && enclosingElement.getElementType() == IJavaElement.METHOD) {
return enclosingElement;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return null;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
public void run(IStructuredSelection selection) {
if (selection.size() != 1)
return;
Object input= selection.getFirstElement();
if (!(input instanceof IJavaElement)) {
IStatus status= createStatus(CallHierarchyMessages.getString("OpenCallHierarchyAction.messages.no_java_element")); //$NON-NLS-1$
ErrorDialog.openError(getShell(), getDialogTitle(), CallHierarchyMessages.getString("OpenCallHierarchyAction.messages.title"), status); //$NON-NLS-1$
return;
}
IJavaElement element= (IJavaElement) input;
if (!ActionUtil.isProcessable(getShell(), element))
return;
List result= new ArrayList(1);
IStatus status= compileCandidates(result, element);
if (status.isOK()) {
run((IJavaElement[]) result.toArray(new IJavaElement[result.size()]));
} else {
ErrorDialog.openError(getShell(), getDialogTitle(), CallHierarchyMessages.getString("OpenCallHierarchyAction.messages.title"), status); //$NON-NLS-1$
}
}
public void run(IJavaElement[] elements) {
if (elements.length == 0) {
getShell().getDisplay().beep();
return;
}
CallHierarchyUI.open(elements, getSite().getWorkbenchWindow());
}
private static String getDialogTitle() {
return CallHierarchyMessages.getString("OpenCallHierarchyAction.dialog.title"); //$NON-NLS-1$
}
private static IStatus compileCandidates(List result, IJavaElement elem) {
IStatus ok= new Status(IStatus.OK, JavaPlugin.getPluginId(), 0, "", null); //$NON-NLS-1$
switch (elem.getElementType()) {
case IJavaElement.METHOD:
result.add(elem);
return ok;
}
return createStatus(CallHierarchyMessages.getString("OpenCallHierarchyAction.messages.no_valid_java_element")); //$NON-NLS-1$
}
private static IStatus createStatus(String message) {
return new Status(IStatus.INFO, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null);
}
}
|
46,351 |
Bug 46351 Call Hierarchy must not implement IViewSite [call hierarchy]
|
I20031105 The call hierarchy component implements IViewSite which is not allowed. There seems to be no reason for doing so: the CallHierarchyViewPart should directly set the selection provider to its site.
|
resolved fixed
|
dd173ad
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T17:26:45Z | 2003-11-10T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/OpenDeclarationAction.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:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.actions.OpenAction;
import org.eclipse.jdt.internal.ui.util.SelectionUtil;
import org.eclipse.jdt.internal.corext.callhierarchy.MethodWrapper;
class OpenDeclarationAction extends OpenAction {
public OpenDeclarationAction(IWorkbenchSite site) {
super(site);
}
public boolean canActionBeAdded() {
Object element = SelectionUtil.getSingleElement(getSelection());
IMethod method = null;
if (element instanceof IMethod) {
method = (IMethod) element;
} else if (element instanceof IAdaptable) {
method = (IMethod) ((IAdaptable) element).getAdapter(IMethod.class);
}
if (method != null) {
return true;
}
return false;
}
public ISelection getSelection() {
ISelection selection= getSelectionProvider().getSelection();
if (selection instanceof IStructuredSelection) {
IStructuredSelection structuredSelection= (IStructuredSelection) selection;
List javaElements= new ArrayList();
for (Iterator iter= structuredSelection.iterator(); iter.hasNext();) {
Object element= iter.next();
if (element instanceof MethodWrapper) {
javaElements.add(((MethodWrapper)element).getMember());
}
}
return new StructuredSelection(javaElements);
}
return selection;
}
public Object getElementToOpen(Object object) throws JavaModelException {
if (object instanceof MethodWrapper) {
return ((MethodWrapper) object).getMember();
}
return object;
}
}
|
46,351 |
Bug 46351 Call Hierarchy must not implement IViewSite [call hierarchy]
|
I20031105 The call hierarchy component implements IViewSite which is not allowed. There seems to be no reason for doing so: the CallHierarchyViewPart should directly set the selection provider to its site.
|
resolved fixed
|
dd173ad
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T17:26:45Z | 2003-11-10T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/OpenLocationAction.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:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import java.util.Iterator;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.jdt.ui.actions.SelectionDispatchAction;
import org.eclipse.jdt.internal.corext.callhierarchy.CallLocation;
import org.eclipse.jdt.internal.corext.callhierarchy.MethodWrapper;
class OpenLocationAction extends SelectionDispatchAction {
public OpenLocationAction(IWorkbenchSite site) {
super(site);
setText(CallHierarchyMessages.getString("OpenLocationAction.label")); //$NON-NLS-1$
setToolTipText(CallHierarchyMessages.getString("OpenLocationAction.tooltip")); //$NON-NLS-1$
}
private boolean checkEnabled(IStructuredSelection selection) {
if (selection.isEmpty()) {
return false;
}
for (Iterator iter = selection.iterator(); iter.hasNext();) {
Object element = iter.next();
if (element instanceof MethodWrapper) {
continue;
} else if (element instanceof CallLocation) {
continue;
}
return false;
}
return true;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
public void run(IStructuredSelection selection) {
if (!checkEnabled(selection)) {
return;
}
run(selection.getFirstElement());
}
public void run(Object element) {
CallHierarchyUI.openInEditor(element, getShell(), getDialogTitle());
}
private String getDialogTitle() {
return CallHierarchyMessages.getString("OpenLocationAction.error.title"); //$NON-NLS-1$
}
}
|
46,351 |
Bug 46351 Call Hierarchy must not implement IViewSite [call hierarchy]
|
I20031105 The call hierarchy component implements IViewSite which is not allowed. There seems to be no reason for doing so: the CallHierarchyViewPart should directly set the selection provider to its site.
|
resolved fixed
|
dd173ad
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T17:26:45Z | 2003-11-10T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/SelectionProviderAdapter.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:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.internal.ui.util.SelectionUtil;
import org.eclipse.jdt.internal.corext.callhierarchy.MethodWrapper;
class SelectionProviderAdapter implements ISelectionProvider {
private ISelectionProvider fProvider;
private ISelectionChangedListener fListener;
SelectionProviderAdapter(ISelectionProvider provider) {
this.fProvider= provider;
}
public void addSelectionChangedListener(final ISelectionChangedListener listener) {
fListener=
new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
listener.selectionChanged(new SelectionChangedEvent(fProvider, convertSelection(event.getSelection())));
}
};
fProvider.addSelectionChangedListener(fListener);
}
public ISelection getSelection() {
return convertSelection(fProvider.getSelection());
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
fProvider.removeSelectionChangedListener(fListener);
}
public void setSelection(ISelection selection) {
}
private ISelection convertSelection(ISelection selection) {
Object element= SelectionUtil.getSingleElement(selection);
if (element instanceof MethodWrapper) {
MethodWrapper methodWrapper= (MethodWrapper) element;
if (methodWrapper != null) {
IJavaElement je= methodWrapper.getMember();
if (je != null)
return new StructuredSelection(je);
}
}
return StructuredSelection.EMPTY;
}
}
|
46,351 |
Bug 46351 Call Hierarchy must not implement IViewSite [call hierarchy]
|
I20031105 The call hierarchy component implements IViewSite which is not allowed. There seems to be no reason for doing so: the CallHierarchyViewPart should directly set the selection provider to its site.
|
resolved fixed
|
dd173ad
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T17:26:45Z | 2003-11-10T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/SelectionProviderMediator.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.callhierarchy;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
/**
* A selection provider for viewparts with more that one viewer.
* Tracks the focus of the viewers to provide the correct selection.
*
* NOTE: This class was copied from the org.eclipse.jdt.internal.ui.typehierarchy (without modification)
*/
public class SelectionProviderMediator implements ISelectionProvider {
private class InternalListener implements ISelectionChangedListener, FocusListener {
/*
* @see ISelectionChangedListener#selectionChanged
*/
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
/*
* @see FocusListener#focusGained
*/
public void focusGained(FocusEvent e) {
doFocusChanged(e.widget);
}
/*
* @see FocusListener#focusLost
*/
public void focusLost(FocusEvent e) {
// do not reset due to focus behaviour on GTK
//fViewerInFocus= null;
}
}
private Viewer[] fViewers;
private InternalListener fListener;
private Viewer fViewerInFocus;
private ListenerList fSelectionChangedListeners;
/**
* @param All viewers that can provide a selection
*/
public SelectionProviderMediator(Viewer[] viewers) {
Assert.isNotNull(viewers);
fViewers= viewers;
fListener= new InternalListener();
fSelectionChangedListeners= new ListenerList(4);
fViewerInFocus= null;
for (int i= 0; i < fViewers.length; i++) {
Viewer viewer= fViewers[i];
viewer.addSelectionChangedListener(fListener);
Control control= viewer.getControl();
control.addFocusListener(fListener);
}
}
private void doFocusChanged(Widget control) {
for (int i= 0; i < fViewers.length; i++) {
if (fViewers[i].getControl() == control) {
propagateFocusChanged(fViewers[i]);
return;
}
}
}
private void doSelectionChanged(SelectionChangedEvent event) {
ISelectionProvider provider= event.getSelectionProvider();
if (provider == fViewerInFocus) {
fireSelectionChanged();
}
}
private void propagateFocusChanged(Viewer viewer) {
if (viewer != fViewerInFocus) { // Ok to compare by idendity
fViewerInFocus= viewer;
fireSelectionChanged();
}
}
private void fireSelectionChanged() {
if (fSelectionChangedListeners != null) {
SelectionChangedEvent event= new SelectionChangedEvent(this, getSelection());
Object[] listeners= fSelectionChangedListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
ISelectionChangedListener listener= (ISelectionChangedListener) listeners[i];
listener.selectionChanged(event);
}
}
}
/*
* @see ISelectionProvider#addSelectionChangedListener
*/
public void addSelectionChangedListener(ISelectionChangedListener listener) {
fSelectionChangedListeners.add(listener);
}
/*
* @see ISelectionProvider#removeSelectionChangedListener
*/
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
fSelectionChangedListeners.remove(listener);
}
/*
* @see ISelectionProvider#getSelection
*/
public ISelection getSelection() {
if (fViewerInFocus != null) {
return fViewerInFocus.getSelection();
} else {
return StructuredSelection.EMPTY;
}
}
/*
* @see ISelectionProvider#setSelection
*/
public void setSelection(ISelection selection) {
if (fViewerInFocus != null) {
fViewerInFocus.setSelection(selection);
}
}
/**
* Returns the viewer in focus or null if no viewer has the focus
*/
public Viewer getViewerInFocus() {
return fViewerInFocus;
}
}
|
46,351 |
Bug 46351 Call Hierarchy must not implement IViewSite [call hierarchy]
|
I20031105 The call hierarchy component implements IViewSite which is not allowed. There seems to be no reason for doing so: the CallHierarchyViewPart should directly set the selection provider to its site.
|
resolved fixed
|
dd173ad
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T17:26:45Z | 2003-11-10T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/ToggleImplementorsAction.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:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
/**
* Toggles the orientationof the layout of the call hierarchy
*/
class ToggleImplementorsAction extends Action {
private CallHierarchyViewPart fView;
private int fImplementorsMode;
public ToggleImplementorsAction(CallHierarchyViewPart v, int implementorsMode) {
super("", AS_RADIO_BUTTON); //$NON-NLS-1$
if (implementorsMode == CallHierarchyViewPart.IMPLEMENTORS_ENABLED) {
setText(CallHierarchyMessages.getString("ToggleImplementorsAction.enabled.label")); //$NON-NLS-1$
setDescription(CallHierarchyMessages.getString("ToggleImplementorsAction.enabled.description")); //$NON-NLS-1$
setToolTipText(CallHierarchyMessages.getString("ToggleImplementorsAction.enabled.tooltip")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "th_horizontal.gif"); //$NON-NLS-1$
} else if (implementorsMode == CallHierarchyViewPart.IMPLEMENTORS_DISABLED) {
setText(CallHierarchyMessages.getString("ToggleImplementorsAction.disabled.label")); //$NON-NLS-1$
setDescription(CallHierarchyMessages.getString("ToggleImplementorsAction.disabled.description")); //$NON-NLS-1$
setToolTipText(CallHierarchyMessages.getString("ToggleImplementorsAction.disabled.tooltip")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "th_vertical.gif"); //$NON-NLS-1$
} else {
Assert.isTrue(false);
}
fView= v;
fImplementorsMode= implementorsMode;
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_TOGGLE_IMPLEMENTORS_ACTION);
}
public int getImplementorsMode() {
return fImplementorsMode;
}
/*
* @see Action#actionPerformed
*/
public void run() {
fView.setImplementorsMode(fImplementorsMode); // will toggle the checked state
}
}
|
46,656 |
Bug 46656 Find Occurences does not find all occurences
|
20031111 In jdt.ui selfhost workspace open CyclePartAction (in binary). Select 'commandForward' and use 'Find Occurenced'. Only 3 references are found. Missing are e.g. line 317, 'if (commandForward != null) {'
|
resolved fixed
|
716cedf
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T18:24:22Z | 2003-11-14T11:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/OccurrencesFinder.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.search;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.Assignment;
import org.eclipse.jdt.core.dom.ClassInstanceCreation;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.FieldAccess;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.PostfixExpression;
import org.eclipse.jdt.core.dom.PrefixExpression;
import org.eclipse.jdt.core.dom.QualifiedName;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.PrefixExpression.Operator;
import org.eclipse.jdt.internal.corext.dom.Bindings;
public class OccurrencesFinder extends ASTVisitor {
private IBinding fTarget;
private List fUsages= new ArrayList();
private List fWriteUsages= new ArrayList();
public OccurrencesFinder(IBinding target) {
super();
fTarget= target;
}
public List getUsages() {
return fUsages;
}
public List getWriteUsages() {
return fWriteUsages;
}
public boolean visit(QualifiedName node) {
IBinding binding= node.resolveBinding();
if (binding instanceof IVariableBinding && ((IVariableBinding)binding).isField()) {
SimpleName name= node.getName();
return !match(name, fUsages, name.resolveBinding());
}
return !match(node, fUsages, node.resolveBinding());
}
public boolean visit(SimpleName node) {
return !match(node, fUsages, node.resolveBinding());
}
/*
* @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.ConstructorInvocation)
*/
public boolean visit(ClassInstanceCreation node) {
match(node.getName(), fUsages, node.resolveConstructorBinding());
Expression expression = node.getExpression();
if (expression != null)
expression.accept(this);
List list = node.arguments();
for (Iterator iter= list.iterator(); iter.hasNext();)
((ASTNode)iter.next()).accept(this);
return false;
}
public boolean visit(Assignment node) {
Expression lhs= node.getLeftHandSide();
Name name= getName(lhs);
if (name != null)
match(name, fWriteUsages, name.resolveBinding());
lhs.accept(this);
node.getRightHandSide().accept(this);
return false;
}
public boolean visit(SingleVariableDeclaration node) {
if (node.getInitializer() != null)
match(node.getName(), fWriteUsages, node.resolveBinding());
return super.visit(node);
}
public boolean visit(VariableDeclarationFragment node) {
if (node.getInitializer() != null)
match(node.getName(), fWriteUsages, node.resolveBinding());
return super.visit(node);
}
public boolean visit(PrefixExpression node) {
PrefixExpression.Operator operator= node.getOperator();
if (operator == Operator.INCREMENT || operator == Operator.DECREMENT) {
Expression operand= node.getOperand();
Name name= getName(operand);
if (name != null)
match(name, fWriteUsages, name.resolveBinding());
}
return super.visit(node);
}
public boolean visit(PostfixExpression node) {
Expression operand= node.getOperand();
Name name= getName(operand);
if (name != null)
match(name, fWriteUsages, name.resolveBinding());
return super.visit(node);
}
private boolean match(Name node, List result, IBinding binding) {
if (binding != null && Bindings.equals(binding, fTarget)) {
result.add(node);
return true;
}
return false;
}
private Name getName(Expression expression) {
if (expression instanceof SimpleName)
return ((SimpleName)expression);
else if (expression instanceof QualifiedName)
return ((QualifiedName)expression);
else if (expression instanceof FieldAccess)
return ((FieldAccess)expression).getName();
return null;
}
}
|
42,699 |
Bug 42699 Unexpected error in organize imports [code manipulation]
|
To recreate this error, you must have two java projects set up. Create a new class file in one of the projects that refers to an existing class in the other project. In the project properties I'm resolving the foreign class file picking "add class folder" and choosing the class folder from the other project but leave out the import for now. There should be an error in the new class about the unresolved type. Choose "organize imports" from the menu (or hit ctl+shift+o). You get the following error message: Unexpected error in organize imports. See log for details. Reason: classes/whatever (in other project) does not exist. The exact same message appears in the log too. Now manually type in the import the old way. The class dependency is now resolved and the error goes away. After the import is added to the class file, "organize imports" runs with no error.
|
resolved fixed
|
8e14bfc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T19:01:50Z | 2003-09-08T14:06:40Z |
org.eclipse.jdt.ui/core
| |
42,699 |
Bug 42699 Unexpected error in organize imports [code manipulation]
|
To recreate this error, you must have two java projects set up. Create a new class file in one of the projects that refers to an existing class in the other project. In the project properties I'm resolving the foreign class file picking "add class folder" and choosing the class folder from the other project but leave out the import for now. There should be an error in the new class about the unresolved type. Choose "organize imports" from the menu (or hit ctl+shift+o). You get the following error message: Unexpected error in organize imports. See log for details. Reason: classes/whatever (in other project) does not exist. The exact same message appears in the log too. Now manually type in the import the old way. The class dependency is now resolved and the error goes away. After the import is added to the class file, "organize imports" runs with no error.
|
resolved fixed
|
8e14bfc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T19:01:50Z | 2003-09-08T14:06:40Z |
extension/org/eclipse/jdt/internal/corext/util/IFileTypeInfo.java
| |
46,614 |
Bug 46614 Introduce Factory: make constructor private should be disabled for syntetic default constructors
|
I20031111 Title says it all.
|
resolved fixed
|
01336fa
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T21:04:04Z | 2003-11-13T19:00:00Z |
org.eclipse.jdt.ui/core
| |
46,614 |
Bug 46614 Introduce Factory: make constructor private should be disabled for syntetic default constructors
|
I20031111 Title says it all.
|
resolved fixed
|
01336fa
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T21:04:04Z | 2003-11-13T19:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/IntroduceFactoryRefactoring.java
| |
46,614 |
Bug 46614 Introduce Factory: make constructor private should be disabled for syntetic default constructors
|
I20031111 Title says it all.
|
resolved fixed
|
01336fa
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T21:04:04Z | 2003-11-13T19:00:00Z |
org.eclipse.jdt.ui/ui
| |
46,614 |
Bug 46614 Introduce Factory: make constructor private should be disabled for syntetic default constructors
|
I20031111 Title says it all.
|
resolved fixed
|
01336fa
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T21:04:04Z | 2003-11-13T19:00:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/IntroduceFactoryInputPage.java
| |
46,764 |
Bug 46764 Change type refactoring: NLS has two keys ChangeTypeRefactoring.invalidSelection with different values
|
N20031114 Please use the NLS search facility to make sure your NLS stuff is correct. To enable go to Search Dialog -> Customize and check NLS search. Then fill in the NLS search page.
|
resolved fixed
|
8e4e4cd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T22:01:07Z | 2003-11-17T11:53:20Z |
org.eclipse.jdt.ui/core
| |
46,764 |
Bug 46764 Change type refactoring: NLS has two keys ChangeTypeRefactoring.invalidSelection with different values
|
N20031114 Please use the NLS search facility to make sure your NLS stuff is correct. To enable go to Search Dialog -> Customize and check NLS search. Then fill in the NLS search page.
|
resolved fixed
|
8e4e4cd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T22:01:07Z | 2003-11-17T11:53:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeTypeRefactoring.java
| |
46,764 |
Bug 46764 Change type refactoring: NLS has two keys ChangeTypeRefactoring.invalidSelection with different values
|
N20031114 Please use the NLS search facility to make sure your NLS stuff is correct. To enable go to Search Dialog -> Customize and check NLS search. Then fill in the NLS search page.
|
resolved fixed
|
8e4e4cd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T22:01:07Z | 2003-11-17T11:53:20Z |
org.eclipse.jdt.ui/ui
| |
46,764 |
Bug 46764 Change type refactoring: NLS has two keys ChangeTypeRefactoring.invalidSelection with different values
|
N20031114 Please use the NLS search facility to make sure your NLS stuff is correct. To enable go to Search Dialog -> Customize and check NLS search. Then fill in the NLS search page.
|
resolved fixed
|
8e4e4cd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T22:01:07Z | 2003-11-17T11:53:20Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeTypeWizard.java
| |
46,764 |
Bug 46764 Change type refactoring: NLS has two keys ChangeTypeRefactoring.invalidSelection with different values
|
N20031114 Please use the NLS search facility to make sure your NLS stuff is correct. To enable go to Search Dialog -> Customize and check NLS search. Then fill in the NLS search page.
|
resolved fixed
|
8e4e4cd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T22:01:07Z | 2003-11-17T11:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/ChangeTypeAction.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.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.internal.corext.refactoring.base.Refactoring;
import org.eclipse.jdt.internal.corext.refactoring.structure.ChangeTypeRefactoring;
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.refactoring.ChangeTypeWizard;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
/**
* @author tip
*/
public class ChangeTypeAction extends SelectionDispatchAction {
private CompilationUnitEditor fEditor;
private String fDialogMessageTitle;
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public ChangeTypeAction(CompilationUnitEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
setEnabled(SelectionConverter.getInputAsCompilationUnit(fEditor) != null);
}
/**
* Creates a new <code>ChangeTypeAction</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 ChangeTypeAction(IWorkbenchSite site) {
super(site);
setText(RefactoringMessages.getString("ChangeTypeAction.label")); //$NON-NLS-1$
setToolTipText(RefactoringMessages.getString("ChangeTypeAction.tooltipText")); //$NON-NLS-1$
setDescription(RefactoringMessages.getString("ChangeTypeAction.description")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.CHANGE_TYPE_ACTION);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
public void run(ITextSelection selection) {
if (!ActionUtil.isProcessable(getShell(), fEditor))
return;
try{
ChangeTypeRefactoring refactoring= createRefactoring(SelectionConverter.getInputAsCompilationUnit(fEditor), selection);
if (refactoring == null)
return;
new RefactoringStarter().activate(refactoring, createWizard(refactoring), getShell(), fDialogMessageTitle, false);
} catch (CoreException e){
ExceptionHandler.handle(e, fDialogMessageTitle, RefactoringMessages.getString("ChangeTypeAction.exception")); //$NON-NLS-1$
}
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
public void selectionChanged(ITextSelection selection) {
setEnabled(checkEnabled(selection));
}
private static ChangeTypeRefactoring createRefactoring(ICompilationUnit cunit, ITextSelection selection) throws CoreException {
return ChangeTypeRefactoring.create(cunit,
selection.getOffset(), selection.getLength());
}
private RefactoringWizard createWizard(ChangeTypeRefactoring refactoring) {
String pageTitle= RefactoringMessages.getString("ChangeTypeAction.change_type"); //$NON-NLS-1$
return new ChangeTypeWizard(refactoring);
}
private boolean checkEnabled(ITextSelection selection) {
return fEditor != null && SelectionConverter.getInputAsCompilationUnit(fEditor) != null;
}
private RefactoringWizard createWizard(Refactoring refactoring) {
return new ChangeTypeWizard((ChangeTypeRefactoring)refactoring);
}
}
|
46,805 |
Bug 46805 prepare Compare for encoding support
|
I20031111 The Compare plugin only supports the global workspace encoding. It does not support encodings per file.
|
resolved fixed
|
842e720
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T23:11:14Z | 2003-11-17T23:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaAddElementFromHistory.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.compare;
import java.util.List;
import java.util.ResourceBundle;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.*;
import org.eclipse.jdt.core.*;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.BodyDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.corext.textmanipulation.*;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.compare.*;
import org.eclipse.compare.structuremergeviewer.DocumentRangeNode;
public class JavaAddElementFromHistory extends JavaHistoryAction {
private static final String BUNDLE_NAME= "org.eclipse.jdt.internal.ui.compare.AddFromHistoryAction"; //$NON-NLS-1$
public JavaAddElementFromHistory() {
super(true);
}
public void run(ISelection selection) {
String errorTitle= CompareMessages.getString("AddFromHistory.title"); //$NON-NLS-1$
String errorMessage= CompareMessages.getString("AddFromHistory.internalErrorMessage"); //$NON-NLS-1$
Shell shell= getShell();
ICompilationUnit cu= null;
IParent parent= null;
IMember input= null;
// analyse selection
if (selection.isEmpty()) {
// no selection: we try to use the editor's input
JavaEditor editor= getEditor();
if (editor != null) {
IEditorInput editorInput= editor.getEditorInput();
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
if (manager != null) {
cu= manager.getWorkingCopy(editorInput);
parent= cu;
}
}
} else {
input= getEditionElement(selection);
if (input != null) {
cu= input.getCompilationUnit();
if (input instanceof IParent) {
parent= (IParent)input;
input= null;
} else {
IJavaElement parentElement= input.getParent();
if (parentElement instanceof IParent)
parent= (IParent)parentElement;
}
} else {
if (selection instanceof IStructuredSelection) {
Object o= ((IStructuredSelection)selection).getFirstElement();
if (o instanceof ICompilationUnit) {
cu= (ICompilationUnit) o;
parent= cu;
}
}
}
}
if (parent == null || cu == null) {
String invalidSelectionMessage= CompareMessages.getString("AddFromHistory.invalidSelectionMessage"); //$NON-NLS-1$
MessageDialog.openInformation(shell, errorTitle, invalidSelectionMessage);
return;
}
IFile file= getFile(parent);
if (file == null) {
MessageDialog.openError(shell, errorTitle, errorMessage);
return;
}
boolean inEditor= beingEdited(file);
if (inEditor) {
parent= (IParent) getWorkingCopy((IJavaElement)parent);
if (input != null)
input= (IMember) getWorkingCopy(input);
}
// get a TextBuffer where to insert the text
TextBuffer buffer= null;
try {
buffer= TextBuffer.acquire(file);
if (! buffer.makeCommittable(shell).isOK())
return;
// configure EditionSelectionDialog and let user select an edition
ITypedElement target= new JavaTextBufferNode(buffer, inEditor);
ITypedElement[] editions= buildEditions(target, file);
ResourceBundle bundle= ResourceBundle.getBundle(BUNDLE_NAME);
EditionSelectionDialog d= new EditionSelectionDialog(shell, bundle);
d.setAddMode(true);
d.setHelpContextId(IJavaHelpContextIds.ADD_ELEMENT_FROM_HISTORY_DIALOG);
ITypedElement selected= d.selectEdition(target, editions, parent);
if (selected == null)
return; // user cancel
ICompilationUnit cu2= cu;
if (parent instanceof IMember)
cu2= ((IMember)parent).getCompilationUnit();
CompilationUnit root= AST.parsePartialCompilationUnit(cu2, 0, false);
ASTRewrite rewriter= new ASTRewrite(root);
List list= getContainerList(parent, root);
if (list == null) {
MessageDialog.openError(shell, errorTitle, errorMessage);
return;
}
int pos= getIndex(root, input, list);
ITypedElement[] results= d.getSelection();
for (int i= 0; i < results.length; i++) {
ASTNode newNode= createASTNode(rewriter, results[i], buffer.getLineDelimiter());
if (newNode == null) {
MessageDialog.openError(shell, errorTitle, errorMessage);
return;
}
if (pos < 0 || pos >= list.size()) {
if (newNode instanceof BodyDeclaration) {
pos= ASTNodes.getInsertionIndex((BodyDeclaration)newNode, list);
list.add(pos, newNode);
} else
list.add(newNode);
} else
list.add(pos+1, newNode);
rewriter.markAsInserted(newNode);
}
applyChanges(rewriter, buffer, shell, inEditor);
} catch(InvocationTargetException ex) {
ExceptionHandler.handle(ex, shell, errorTitle, errorMessage);
} catch(InterruptedException ex) {
// shouldn't be called because is not cancable
Assert.isTrue(false);
} catch(CoreException ex) {
ExceptionHandler.handle(ex, shell, errorTitle, errorMessage);
} finally {
if (buffer != null)
TextBuffer.release(buffer);
}
}
/**
* Creates a place holder ASTNode for the given element.
* @param rewriter
* @param element
* @param delimiter the line delimiter
* @return a ASTNode or null
* @throws CoreException
*/
private ASTNode createASTNode(ASTRewrite rewriter, ITypedElement element, String delimiter) throws CoreException {
if (element instanceof IStreamContentAccessor) {
InputStream is= ((IStreamContentAccessor)element).getContents();
if (is != null) {
String content= trimTextBlock(is, delimiter);
if (content != null)
return rewriter.createPlaceholder(content, getPlaceHolderType(element));
}
}
return null;
}
/**
* Finds the corresponding ASTNode for the given container and returns
* its list of children. This list can be used to add a new child nodes to the container.
* @param container the container for which to return the children list
* @param root the AST
* @return list of children or null
* @throws JavaModelException
*/
private List getContainerList(IParent container, CompilationUnit root) throws JavaModelException {
if (container instanceof ICompilationUnit)
return root.types();
if (container instanceof IType) {
ISourceRange sourceRange= ((IType)container).getNameRange();
ASTNode n= NodeFinder.perform(root, sourceRange);
if (n != null) {
BodyDeclaration parentNode= (BodyDeclaration)ASTNodes.getParent(n, BodyDeclaration.class);
if (parentNode != null)
return ((TypeDeclaration)parentNode).bodyDeclarations();
}
return null;
}
return null;
}
/**
* Returns the corresponding place holder type for the given element.
* @return a place holder type (see ASTRewrite)
*/
private int getPlaceHolderType(ITypedElement element) {
if (element instanceof DocumentRangeNode) {
JavaNode jn= (JavaNode) element;
switch (jn.getTypeCode()) {
case JavaNode.CLASS:
case JavaNode.INTERFACE:
return ASTRewrite.TYPE_DECLARATION;
case JavaNode.CONSTRUCTOR:
case JavaNode.METHOD:
return ASTRewrite.METHOD_DECLARATION;
case JavaNode.FIELD:
return ASTRewrite.FIELD_DECLARATION;
case JavaNode.INIT:
return ASTRewrite.INITIALIZER;
default:
break;
}
}
// cannot happen
Assert.isTrue(false);
return ASTRewrite.UNKNOWN;
}
/**
* Returns the index of the given node within its container.
* If node is null -1 is returned.
* @param node
* @return the index of the given node or -1 if the node couldn't be found
*/
private int getIndex(CompilationUnit root, IMember node, List container) throws JavaModelException {
if (node != null) {
ISourceRange sourceRange= node.getNameRange();
ASTNode n= NodeFinder.perform(root, sourceRange);
if (n != null) {
MethodDeclaration parentNode= (MethodDeclaration)ASTNodes.getParent(n, MethodDeclaration.class);
if (parentNode != null)
return container.indexOf(parentNode);
}
}
// NeedWork: not yet implemented
return -1;
}
protected boolean isEnabled(ISelection selection) {
if (selection.isEmpty()) {
JavaEditor editor= getEditor();
if (editor != null) {
// we check whether editor shows CompilationUnit
IEditorInput editorInput= editor.getEditorInput();
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
return manager.getWorkingCopy(editorInput) != null;
}
return false;
}
if (selection instanceof IStructuredSelection) {
Object o= ((IStructuredSelection)selection).getFirstElement();
if (o instanceof ICompilationUnit)
return true;
}
return super.isEnabled(selection);
}
}
|
46,805 |
Bug 46805 prepare Compare for encoding support
|
I20031111 The Compare plugin only supports the global workspace encoding. It does not support encodings per file.
|
resolved fixed
|
842e720
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T23:11:14Z | 2003-11-17T23:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaCompareAction.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.compare;
import java.io.*;
import java.util.ResourceBundle;
import java.text.MessageFormat;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.*;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.*;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.compare.*;
import org.eclipse.compare.structuremergeviewer.DiffNode;
public class JavaCompareAction implements IActionDelegate {
class TypedElement implements ITypedElement, IStreamContentAccessor {
private ISourceReference fSource;
private String fContents;
TypedElement(ISourceReference s, String contents) {
fSource= s;
fContents= contents;
}
public String getName() {
return fJavaElementLabelProvider.getText(fSource);
}
public String getType() {
return "JAVA"; //$NON-NLS-1$
}
public Image getImage() {
return fJavaElementLabelProvider.getImage(fSource);
}
public InputStream getContents() throws CoreException {
return new ByteArrayInputStream(fContents.getBytes());
}
}
private static final String BUNDLE_NAME= "org.eclipse.jdt.internal.ui.compare.CompareAction"; //$NON-NLS-1$
private ISourceReference fLeft;
private ISourceReference fRight;
private JavaElementLabelProvider fJavaElementLabelProvider;
public void selectionChanged(IAction action, ISelection selection) {
action.setEnabled(isEnabled(selection));
}
public void run(IAction action) {
Shell shell= JavaPlugin.getActiveWorkbenchShell();
ResourceBundle bundle= ResourceBundle.getBundle(BUNDLE_NAME);
CompareDialog d= new CompareDialog(shell, bundle);
String left= null;
String right= null;
try {
left= getExtendedSource(fLeft);
} catch (JavaModelException ex) {
JavaPlugin.log(ex);
}
try {
right= getExtendedSource(fRight);
} catch (JavaModelException ex) {
JavaPlugin.log(ex);
}
fJavaElementLabelProvider= new JavaElementLabelProvider(
JavaElementLabelProvider.SHOW_PARAMETERS |
JavaElementLabelProvider.SHOW_OVERLAY_ICONS |
JavaElementLabelProvider.SHOW_ROOT);
if (left == null || right == null) {
String errorTitle= JavaCompareUtilities.getString(bundle, "errorTitle"); //$NON-NLS-1$
String errorFormat= JavaCompareUtilities.getString(bundle, "errorFormat"); //$NON-NLS-1$
Object element= null;
if (left == null)
element= fLeft;
else
element= fRight;
String message= MessageFormat.format(errorFormat, new String[] { fJavaElementLabelProvider.getText(element) } );
MessageDialog.openError(shell, errorTitle, message);
return;
}
d.compare(new DiffNode(new TypedElement(fLeft, left), new TypedElement(fRight, right)));
fJavaElementLabelProvider.dispose();
fJavaElementLabelProvider= null;
}
protected boolean isEnabled(ISelection selection) {
if (selection instanceof IStructuredSelection) {
Object[] sel= ((IStructuredSelection) selection).toArray();
if (sel.length == 2) {
for (int i= 0; i < 2; i++) {
Object o= sel[i];
if (!(o instanceof ISourceReference))
return false;
}
fLeft= (ISourceReference) sel[0];
fRight= (ISourceReference) sel[1];
return true;
}
}
return false;
}
private String getExtendedSource(ISourceReference ref) throws JavaModelException {
// get parent
if (ref instanceof IJavaElement) {
IJavaElement parent= ((IJavaElement) ref).getParent();
if (parent instanceof ISourceReference) {
ISourceReference sr= (ISourceReference) parent;
String parentContent= sr.getSource();
if (parentContent != null) {
ISourceRange parentRange= sr.getSourceRange();
ISourceRange childRange= ref.getSourceRange();
int start= childRange.getOffset() - parentRange.getOffset();
int end= start + childRange.getLength();
// search backwards for beginning of line
while (start > 0) {
char c= parentContent.charAt(start-1);
if (c == '\n' || c == '\r')
break;
start--;
}
return parentContent.substring(start, end);
}
}
}
return ref.getSource();
}
}
|
46,805 |
Bug 46805 prepare Compare for encoding support
|
I20031111 The Compare plugin only supports the global workspace encoding. It does not support encodings per file.
|
resolved fixed
|
842e720
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T23:11:14Z | 2003-11-17T23:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaCompareUtilities.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.compare;
import java.io.*;
import java.net.*;
import java.util.*;
import org.eclipse.swt.graphics.Image;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.util.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.*;
import org.eclipse.jdt.internal.core.JavaElement;
import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.jdt.internal.ui.*;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.ui.text.JavaTextTools;
class JavaCompareUtilities {
static int getTabSize() {
return CodeFormatterUtil.getTabWidth();
}
static String getString(ResourceBundle bundle, String key, String dfltValue) {
if (bundle != null) {
try {
return bundle.getString(key);
} catch (MissingResourceException x) {
// NeedWork
}
}
return dfltValue;
}
static String getString(ResourceBundle bundle, String key) {
return getString(bundle, key, key);
}
static int getInteger(ResourceBundle bundle, String key, int dfltValue) {
if (bundle != null) {
try {
String s= bundle.getString(key);
if (s != null)
return Integer.parseInt(s);
} catch (NumberFormatException x) {
// NeedWork
} catch (MissingResourceException x) {
// NeedWork
}
}
return dfltValue;
}
static ImageDescriptor getImageDescriptor(int type) {
switch (type) {
case IJavaElement.INITIALIZER:
case IJavaElement.METHOD:
return getImageDescriptor("obj16/compare_method.gif"); //$NON-NLS-1$
case IJavaElement.FIELD:
return getImageDescriptor("obj16/compare_field.gif"); //$NON-NLS-1$
case IJavaElement.PACKAGE_DECLARATION:
return JavaPluginImages.DESC_OBJS_PACKDECL;
case IJavaElement.IMPORT_DECLARATION:
return JavaPluginImages.DESC_OBJS_IMPDECL;
case IJavaElement.IMPORT_CONTAINER:
return JavaPluginImages.DESC_OBJS_IMPCONT;
case IJavaElement.COMPILATION_UNIT:
return JavaPluginImages.DESC_OBJS_CUNIT;
}
return ImageDescriptor.getMissingImageDescriptor();
}
static ImageDescriptor getTypeImageDescriptor(boolean isClass) {
if (isClass)
return JavaPluginImages.DESC_OBJS_CLASS;
return JavaPluginImages.DESC_OBJS_INTERFACE;
}
static ImageDescriptor getImageDescriptor(IMember element) {
int t= element.getElementType();
if (t == IJavaElement.TYPE) {
IType type= (IType) element;
try {
return getTypeImageDescriptor(type.isClass());
} catch (CoreException e) {
JavaPlugin.log(e);
return JavaPluginImages.DESC_OBJS_GHOST;
}
}
return getImageDescriptor(t);
}
/**
* Returns a name for the given Java element that uses the same conventions
* as the JavaNode name of a corresponding element.
*/
static String getJavaElementID(IJavaElement je) {
if (je instanceof IMember && ((IMember)je).isBinary())
return null;
StringBuffer sb= new StringBuffer();
switch (je.getElementType()) {
case IJavaElement.COMPILATION_UNIT:
sb.append(JavaElement.JEM_COMPILATIONUNIT);
break;
case IJavaElement.TYPE:
sb.append(JavaElement.JEM_TYPE);
sb.append(je.getElementName());
break;
case IJavaElement.FIELD:
sb.append(JavaElement.JEM_FIELD);
sb.append(je.getElementName());
break;
case IJavaElement.METHOD:
sb.append(JavaElement.JEM_METHOD);
sb.append(JavaElementLabels.getElementLabel(je, JavaElementLabels.M_PARAMETER_TYPES));
break;
case IJavaElement.INITIALIZER:
String id= je.getHandleIdentifier();
int pos= id.lastIndexOf(JavaElement.JEM_INITIALIZER);
if (pos >= 0)
sb.append(id.substring(pos));
break;
case IJavaElement.PACKAGE_DECLARATION:
sb.append(JavaElement.JEM_PACKAGEDECLARATION);
break;
case IJavaElement.IMPORT_CONTAINER:
sb.append('<');
break;
case IJavaElement.IMPORT_DECLARATION:
sb.append(JavaElement.JEM_IMPORTDECLARATION);
sb.append(je.getElementName());
break;
default:
return null;
}
return sb.toString();
}
/**
* Returns a name which identifies the given typed name.
* The type is encoded as a single character at the beginning of the string.
*/
static String buildID(int type, String name) {
StringBuffer sb= new StringBuffer();
switch (type) {
case JavaNode.CU:
sb.append(JavaElement.JEM_COMPILATIONUNIT);
break;
case JavaNode.CLASS:
case JavaNode.INTERFACE:
sb.append(JavaElement.JEM_TYPE);
sb.append(name);
break;
case JavaNode.FIELD:
sb.append(JavaElement.JEM_FIELD);
sb.append(name);
break;
case JavaNode.CONSTRUCTOR:
case JavaNode.METHOD:
sb.append(JavaElement.JEM_METHOD);
sb.append(name);
break;
case JavaNode.INIT:
sb.append(JavaElement.JEM_INITIALIZER);
sb.append(name);
break;
case JavaNode.PACKAGE:
sb.append(JavaElement.JEM_PACKAGEDECLARATION);
break;
case JavaNode.IMPORT:
sb.append(JavaElement.JEM_IMPORTDECLARATION);
sb.append(name);
break;
case JavaNode.IMPORT_CONTAINER:
sb.append('<');
break;
default:
Assert.isTrue(false);
break;
}
return sb.toString();
}
static ImageDescriptor getImageDescriptor(String relativePath) {
JavaPlugin plugin= JavaPlugin.getDefault();
URL installURL= null;
if (plugin != null)
installURL= plugin.getDescriptor().getInstallURL();
if (installURL != null) {
try {
URL url= new URL(installURL, "icons/full/" + relativePath); //$NON-NLS-1$
return ImageDescriptor.createFromURL(url);
} catch (MalformedURLException e) {
Assert.isTrue(false);
}
}
return null;
}
static Image getImage(IMember member) {
ImageDescriptor id= getImageDescriptor(member);
return id.createImage();
}
static JavaTextTools getJavaTextTools() {
JavaPlugin plugin= JavaPlugin.getDefault();
if (plugin != null)
return plugin.getJavaTextTools();
return null;
}
static IDocumentPartitioner createJavaPartitioner() {
JavaTextTools tools= getJavaTextTools();
if (tools != null)
return tools.createDocumentPartitioner();
return null;
}
static void setupDocument(IDocument document) {
JavaTextTools tools= getJavaTextTools();
if (tools != null)
tools.setupJavaDocumentPartitioner(document);
}
/**
* Reads the contents of the given input stream into a string.
* The function assumes that the input stream uses the platform's default encoding
* (<code>ResourcesPlugin.getEncoding()</code>).
* Returns null if an error occurred.
*/
static String readString(InputStream is) {
if (is == null)
return null;
BufferedReader reader= null;
try {
StringBuffer buffer= new StringBuffer();
char[] part= new char[2048];
int read= 0;
reader= new BufferedReader(new InputStreamReader(is, ResourcesPlugin.getEncoding()));
while ((read= reader.read(part)) != -1)
buffer.append(part, 0, read);
return buffer.toString();
} catch (IOException ex) {
// NeedWork
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
// silently ignored
}
}
}
return null;
}
/**
* Returns the contents of the given string as an array of bytes
* in the platform's default encoding.
*/
static byte[] getBytes(String s) {
try {
return s.getBytes(ResourcesPlugin.getEncoding());
} catch (UnsupportedEncodingException e) {
return s.getBytes();
}
}
/**
* Breaks the contents of the given input stream into an array of strings.
* The function assumes that the input stream uses the platform's default encoding
* (<code>ResourcesPlugin.getEncoding()</code>).
* Returns null if an error occurred.
*/
static String[] readLines(InputStream is2) {
BufferedReader reader= null;
try {
reader= new BufferedReader(new InputStreamReader(is2, ResourcesPlugin.getEncoding()));
StringBuffer sb= new StringBuffer();
List list= new ArrayList();
while (true) {
int c= reader.read();
if (c == -1)
break;
sb.append((char)c);
if (c == '\r') { // single CR or a CR followed by LF
c= reader.read();
if (c == -1)
break;
sb.append((char)c);
if (c == '\n') {
list.add(sb.toString());
sb= new StringBuffer();
}
} else if (c == '\n') { // a single LF
list.add(sb.toString());
sb= new StringBuffer();
}
}
if (sb.length() > 0)
list.add(sb.toString());
return (String[]) list.toArray(new String[list.size()]);
} catch (IOException ex) {
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
// silently ignored
}
}
}
}
}
|
46,805 |
Bug 46805 prepare Compare for encoding support
|
I20031111 The Compare plugin only supports the global workspace encoding. It does not support encodings per file.
|
resolved fixed
|
842e720
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T23:11:14Z | 2003-11-17T23:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaHistoryAction.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.compare;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.text.edits.MultiTextEdit;
import org.eclipse.compare.HistoryItem;
import org.eclipse.compare.IStreamContentAccessor;
import org.eclipse.compare.ITypedElement;
import org.eclipse.compare.ResourceNode;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFileState;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer;
import org.eclipse.jdt.internal.corext.textmanipulation.TextBufferEditor;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
/**
* Base class for the "Replace with local history"
* and "Add from local history" actions.
*/
public abstract class JavaHistoryAction extends Action implements IActionDelegate {
/**
* Implements the IStreamContentAccessor and ITypedElement protocols
* for a TextBuffer.
*/
class JavaTextBufferNode implements ITypedElement, IStreamContentAccessor {
private TextBuffer fBuffer;
private boolean fInEditor;
JavaTextBufferNode(TextBuffer buffer, boolean inEditor) {
fBuffer= buffer;
fInEditor= inEditor;
}
public String getName() {
if (fInEditor)
return CompareMessages.getString("Editor_Buffer"); //$NON-NLS-1$
return CompareMessages.getString("Workspace_File"); //$NON-NLS-1$
}
public String getType() {
return "java"; //$NON-NLS-1$
}
public Image getImage() {
return null;
}
public InputStream getContents() {
return new ByteArrayInputStream(JavaCompareUtilities.getBytes(fBuffer.getContent()));
}
}
private boolean fModifiesFile;
private ISelection fSelection;
JavaHistoryAction(boolean modifiesFile) {
fModifiesFile= modifiesFile;
}
ISelection getSelection() {
return fSelection;
}
final IFile getFile(Object input) {
// extract CU from input
ICompilationUnit cu= null;
if (input instanceof ICompilationUnit)
cu= (ICompilationUnit) input;
else if (input instanceof IMember)
cu= ((IMember)input).getCompilationUnit();
if (cu == null || !cu.exists())
return null;
// get to original CU
cu= JavaModelUtil.toOriginal(cu);
// find underlying file
IFile file= (IFile) cu.getResource();
if (file != null && file.exists())
return file;
return null;
}
final ITypedElement[] buildEditions(ITypedElement target, IFile file) {
// setup array of editions
IFileState[] states= null;
// add available editions
try {
states= file.getHistory(null);
} catch (CoreException ex) {
JavaPlugin.log(ex);
}
int count= 1;
if (states != null)
count+= states.length;
ITypedElement[] editions= new ITypedElement[count];
editions[0]= new ResourceNode(file);
if (states != null)
for (int i= 0; i < states.length; i++)
editions[i+1]= new HistoryItem(target, states[i]);
return editions;
}
final Shell getShell() {
if (fEditor != null)
return fEditor.getEditorSite().getShell();
return JavaPlugin.getActiveWorkbenchShell();
}
/**
* Tries to find the given element in a workingcopy.
*/
final IJavaElement getWorkingCopy(IJavaElement input) {
try {
return EditorUtility.getWorkingCopy(input, true);
} catch (JavaModelException ex) {
// NeedWork
}
return null;
}
/**
* Returns true if the given file is open in an editor.
*/
final boolean beingEdited(IFile file) {
IDocumentProvider dp= JavaPlugin.getDefault().getCompilationUnitDocumentProvider();
FileEditorInput input= new FileEditorInput(file);
return dp.getDocument(input) != null;
}
/**
* Returns an IMember or null.
*/
final IMember getEditionElement(ISelection selection) {
if (selection instanceof IStructuredSelection) {
IStructuredSelection ss= (IStructuredSelection) selection;
if (ss.size() == 1) {
Object o= ss.getFirstElement();
if (o instanceof IMember) {
IMember m= (IMember) o;
if (m.exists() && !m.isBinary() && JavaStructureCreator.hasEdition(m))
return m;
}
}
}
return null;
}
final boolean isEnabled(IFile file) {
if (file == null || ! file.exists())
return false;
if (fModifiesFile) {
// without validate/edit we would do this:
// return !file.isReadOnly();
// with validate/edit we have to return true
return true;
}
return true;
}
boolean isEnabled(ISelection selection) {
IMember m= getEditionElement(selection);
if (m == null)
return false;
IFile file= getFile(m);
if (!isEnabled(file))
return false;
if (file != null && beingEdited(file))
return getWorkingCopy(m) != null;
return true;
}
void applyChanges(ASTRewrite rewriter, final TextBuffer buffer, Shell shell, boolean inEditor) throws CoreException, InvocationTargetException, InterruptedException {
MultiTextEdit edit= new MultiTextEdit();
rewriter.rewriteNode(buffer, edit);
IProgressMonitor nullProgressMonitor= new NullProgressMonitor();
TextBufferEditor editor= new TextBufferEditor(buffer);
editor.add(edit);
editor.performEdits(nullProgressMonitor);
IRunnableWithProgress r= new IRunnableWithProgress() {
public void run(IProgressMonitor pm) throws InvocationTargetException {
try {
TextBuffer.commitChanges(buffer, false, pm);
} catch (CoreException ex) {
throw new InvocationTargetException(ex);
}
}
};
if (inEditor) {
// we don't show progress
r.run(nullProgressMonitor);
} else {
ProgressMonitorDialog pd= new ProgressMonitorDialog(shell);
pd.run(true, false, r);
}
}
static String trimTextBlock(InputStream is, String delimiter) {
String content= JavaCompareUtilities.readString(is);
if (content != null) {
String[] lines= Strings.convertIntoLines(content);
if (lines != null) {
Strings.trimIndentation(lines, JavaCompareUtilities.getTabSize());
return Strings.concatenate(lines, delimiter);
}
}
return null;
}
final JavaEditor getEditor(IFile file) {
IWorkbench workbench= JavaPlugin.getDefault().getWorkbench();
IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
for (int i= 0; i < windows.length; i++) {
IWorkbenchPage[] pages= windows[i].getPages();
for (int x= 0; x < pages.length; x++) {
IEditorPart[] editors= pages[x].getDirtyEditors();
for (int z= 0; z < editors.length; z++) {
IEditorPart ep= editors[z];
if (ep instanceof JavaEditor)
return (JavaEditor) ep;
}
}
}
return null;
}
/**
* Executes this action with the given selection.
*/
public abstract void run(ISelection selection);
//---- Action
private JavaEditor fEditor;
private String fTitle;
private String fMessage;
void init(JavaEditor editor, String text, String title, String message) {
Assert.isNotNull(editor);
Assert.isNotNull(title);
Assert.isNotNull(message);
fEditor= editor;
fTitle= title;
fMessage= message;
setText(text);
setEnabled(checkEnabled());
}
final JavaEditor getEditor() {
return fEditor;
}
final public void run() {
// this run is called from Editor
IJavaElement element= null;
try {
element= SelectionConverter.getElementAtOffset(fEditor);
} catch (JavaModelException e) {
// ignored
}
fSelection= element != null
? new StructuredSelection(element)
: StructuredSelection.EMPTY;
boolean isEnabled= isEnabled(fSelection);
setEnabled(isEnabled);
if (!isEnabled) {
MessageDialog.openInformation(getShell(), fTitle, fMessage);
return;
}
run(fSelection);
}
private boolean checkEnabled() {
ICompilationUnit unit= SelectionConverter.getInputAsCompilationUnit(fEditor);
IFile file= getFile(unit);
return isEnabled(file);
}
final public void update() {
setEnabled(checkEnabled());
}
//---- IActionDelegate
final public void selectionChanged(IAction uiProxy, ISelection selection) {
fSelection= selection;
uiProxy.setEnabled(isEnabled(selection));
}
final public void run(IAction action) {
run(fSelection);
}
}
|
46,805 |
Bug 46805 prepare Compare for encoding support
|
I20031111 The Compare plugin only supports the global workspace encoding. It does not support encodings per file.
|
resolved fixed
|
842e720
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T23:11:14Z | 2003-11-17T23:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaReplaceWithEditionAction.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.compare;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ResourceBundle;
import org.eclipse.compare.EditionSelectionDialog;
import org.eclipse.compare.HistoryItem;
import org.eclipse.compare.IStreamContentAccessor;
import org.eclipse.compare.ITypedElement;
import org.eclipse.compare.ResourceNode;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFileState;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.BodyDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.swt.widgets.Shell;
/**
* Provides "Replace from local history" for Java elements.
*/
public class JavaReplaceWithEditionAction extends JavaHistoryAction {
private static final String BUNDLE_NAME= "org.eclipse.jdt.internal.ui.compare.ReplaceWithEditionAction"; //$NON-NLS-1$
protected boolean fPrevious= false;
public JavaReplaceWithEditionAction() {
super(true);
}
public void run(ISelection selection) {
String errorTitle= CompareMessages.getString("ReplaceFromHistory.title"); //$NON-NLS-1$
String errorMessage= CompareMessages.getString("ReplaceFromHistory.internalErrorMessage"); //$NON-NLS-1$
Shell shell= getShell();
IMember input= getEditionElement(selection);
if (input == null) {
String invalidSelectionMessage= CompareMessages.getString("ReplaceFromHistory.invalidSelectionMessage"); //$NON-NLS-1$
MessageDialog.openInformation(shell, errorTitle, invalidSelectionMessage);
return;
}
IFile file= getFile(input);
if (file == null) {
MessageDialog.openError(shell, errorTitle, errorMessage);
return;
}
boolean inEditor= beingEdited(file);
if (inEditor)
input= (IMember) getWorkingCopy(input);
// get a TextBuffer where to insert the text
TextBuffer buffer= null;
try {
buffer= TextBuffer.acquire(file);
if (! buffer.makeCommittable(shell).isOK())
return;
ResourceBundle bundle= ResourceBundle.getBundle(BUNDLE_NAME);
EditionSelectionDialog d= new EditionSelectionDialog(shell, bundle);
d.setHelpContextId(IJavaHelpContextIds.REPLACE_ELEMENT_WITH_HISTORY_DIALOG);
ITypedElement target= new JavaTextBufferNode(buffer, inEditor);
ITypedElement[] editions= buildEditions(target, file);
ITypedElement ti= null;
if (fPrevious) {
ti= d.selectPreviousEdition(target, editions, input);
if (ti == null) {
MessageDialog.openInformation(shell, errorTitle, CompareMessages.getString("ReplaceFromHistory.parsingErrorMessage")); //$NON-NLS-1$
return;
}
} else
ti= d.selectEdition(target, editions, input);
if (ti instanceof IStreamContentAccessor) {
InputStream is= ((IStreamContentAccessor)ti).getContents();
String newContent= trimTextBlock(is, buffer.getLineDelimiter());
if (newContent == null) {
MessageDialog.openError(shell, errorTitle, errorMessage);
return;
}
CompilationUnit root= AST.parsePartialCompilationUnit(input.getCompilationUnit(), 0, false);
BodyDeclaration node= (BodyDeclaration)ASTNodes.getParent(NodeFinder.perform(root, input.getNameRange()), BodyDeclaration.class);
if (node == null) {
MessageDialog.openError(shell, errorTitle, errorMessage);
return;
}
ASTRewrite rewriter= new ASTRewrite(root);
rewriter.markAsReplaced(node, rewriter.createPlaceholder(newContent, ASTRewrite.getPlaceholderType(node)));
if (inEditor) {
JavaEditor je= getEditor(file);
if (je != null)
je.setFocus();
}
applyChanges(rewriter, buffer, shell, inEditor);
}
} catch(InvocationTargetException ex) {
ExceptionHandler.handle(ex, shell, errorTitle, errorMessage);
} catch(InterruptedException ex) {
// shouldn't be called because is not cancable
Assert.isTrue(false);
} catch(CoreException ex) {
ExceptionHandler.handle(ex, shell, errorTitle, errorMessage);
} finally {
if (buffer != null)
TextBuffer.release(buffer);
}
}
protected ITypedElement[] buildEditions(ITypedElement target, IFile file, IFileState[] states) {
ITypedElement[] editions= new ITypedElement[states.length+1];
editions[0]= new ResourceNode(file);
for (int i= 0; i < states.length; i++)
editions[i+1]= new HistoryItem(target, states[i]);
return editions;
}
}
|
46,805 |
Bug 46805 prepare Compare for encoding support
|
I20031111 The Compare plugin only supports the global workspace encoding. It does not support encodings per file.
|
resolved fixed
|
842e720
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T23:11:14Z | 2003-11-17T23:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaStructureCreator.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.compare;
import java.io.UnsupportedEncodingException;
import java.util.*;
import org.eclipse.jface.text.*;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.*;
import org.eclipse.jdt.core.compiler.*;
import org.eclipse.jdt.internal.compiler.*;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblem;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.compare.*;
import org.eclipse.compare.internal.DocumentManager;
import org.eclipse.compare.structuremergeviewer.*;
public class JavaStructureCreator implements IStructureCreator {
/**
* Used to bail out from ProblemFactory.
*/
private static class ParseError extends Error {
}
/**
* This problem factory aborts parsing on first syntax error.
* tod
*/
static class ProblemFactory implements IProblemFactory {
public IProblem createProblem(char[] originatingFileName, int problemId, String[] arguments,
String[] messageArguments, int severity, int startPosition, int endPosition, int lineNumber) {
IProblem problem= new DefaultProblem(originatingFileName, "", problemId, arguments, severity, //$NON-NLS-1$
startPosition, endPosition, lineNumber);
if (problem.isError() && ((problemId & IProblem.Syntax) != 0))
throw new ParseError();
return problem;
}
public Locale getLocale() {
return Locale.getDefault();
}
public String getLocalizedMessage(int problemId, String[] problemArguments) {
return "" + problemId; //$NON-NLS-1$
}
}
/**
* RewriteInfos are used temporarily when rewriting the diff tree
* in order to combine similar diff nodes ("smart folding").
*/
static class RewriteInfo {
boolean fIsOut= false;
JavaNode fAncestor= null;
JavaNode fLeft= null;
JavaNode fRight= null;
ArrayList fChildren= new ArrayList();
void add(IDiffElement diff) {
fChildren.add(diff);
}
void setDiff(ICompareInput diff) {
if (fIsOut)
return;
fIsOut= true;
JavaNode a= (JavaNode) diff.getAncestor();
JavaNode y= (JavaNode) diff.getLeft();
JavaNode m= (JavaNode) diff.getRight();
if (a != null) {
if (fAncestor != null)
return;
fAncestor= a;
}
if (y != null) {
if (fLeft != null)
return;
fLeft= y;
}
if (m != null) {
if (fRight != null)
return;
fRight= m;
}
fIsOut= false;
}
/**
* Returns true if some nodes could be successfully combined into one.
*/
boolean matches() {
return !fIsOut && fAncestor != null && fLeft != null && fRight != null;
}
}
public JavaStructureCreator() {
}
/**
* Returns the name that appears in the enclosing pane title bar.
*/
public String getName() {
return CompareMessages.getString("JavaStructureViewer.title"); //$NON-NLS-1$
}
/**
* Returns a tree of JavaNodes for the given input
* which must implement the IStreamContentAccessor interface.
* In case of error null is returned.
*/
public IStructureComparator getStructure(final Object input) {
String contents= null;
char[] buffer= null;
IDocument doc= DocumentManager.get(input);
if (doc == null) {
if (input instanceof IStreamContentAccessor) {
IStreamContentAccessor sca= (IStreamContentAccessor) input;
try {
contents= JavaCompareUtilities.readString(sca.getContents());
} catch (CoreException ex) {
JavaPlugin.log(ex);
return null;
}
}
if (contents != null) {
int n= contents.length();
buffer= new char[n];
contents.getChars(0, n, buffer, 0);
doc= new Document(contents);
DocumentManager.put(input, doc);
JavaCompareUtilities.setupDocument(doc);
}
}
if (doc != null) {
boolean isEditable= false;
if (input instanceof IEditableContent)
isEditable= ((IEditableContent) input).isEditable();
// we hook into the root node to intercept all node changes
JavaNode root= new JavaNode(doc, isEditable) {
void nodeChanged(JavaNode node) {
save(this, input);
}
};
if (buffer == null) {
contents= doc.get();
int n= contents.length();
buffer= new char[n];
contents.getChars(0, n, buffer, 0);
}
JavaParseTreeBuilder builder= new JavaParseTreeBuilder(root, buffer);
SourceElementParser parser= new SourceElementParser(builder,
new ProblemFactory(), new CompilerOptions(JavaCore.getOptions()));
try {
parser.parseCompilationUnit(builder, false);
} catch (ParseError ex) {
// NeedWork
// parse error: bail out
return null;
}
return root;
}
return null;
}
/**
* Returns true because this IStructureCreator knows how to save.
*/
public boolean canSave() {
return true;
}
public void save(IStructureComparator node, Object input) {
if (node instanceof JavaNode && input instanceof IEditableContent) {
IDocument document= ((JavaNode)node).getDocument();
IEditableContent bca= (IEditableContent) input;
String contents= document.get();
byte[] bytes;
try {
bytes= contents.getBytes(ResourcesPlugin.getEncoding());
} catch (UnsupportedEncodingException e) {
bytes= contents.getBytes();
}
bca.setContent(bytes);
}
}
/**
* Returns the contents of the given node as a string.
* This string is used to test the content of a Java element
* for equality. Is is never shown in the UI, so any string representing
* the content will do.
* @param node must implement the IStreamContentAccessor interface
* @param ignoreWhiteSpace if true all Java white space (incl. comments) is removed from the contents.
*/
public String getContents(Object node, boolean ignoreWhiteSpace) {
if (! (node instanceof IStreamContentAccessor))
return null;
IStreamContentAccessor sca= (IStreamContentAccessor) node;
String content= null;
try {
content= JavaCompareUtilities.readString(sca.getContents());
} catch (CoreException ex) {
JavaPlugin.log(ex);
return null;
}
if (ignoreWhiteSpace) { // we return everything but Java whitespace
// replace comments and whitespace by a single blank
StringBuffer buf= new StringBuffer();
char[] b= content.toCharArray();
// to avoid the trouble when dealing with Unicode
// we use the Java scanner to extract non-whitespace and non-comment tokens
IScanner scanner= ToolFactory.createScanner(true, true, false, false); // however we request Whitespace and Comments
scanner.setSource(b);
try {
int token;
while ((token= scanner.getNextToken()) != ITerminalSymbols.TokenNameEOF) {
switch (token) {
case ITerminalSymbols.TokenNameWHITESPACE:
case ITerminalSymbols.TokenNameCOMMENT_BLOCK:
case ITerminalSymbols.TokenNameCOMMENT_JAVADOC:
case ITerminalSymbols.TokenNameCOMMENT_LINE:
int l= buf.length();
if (l > 0 && buf.charAt(l-1) != ' ')
buf.append(' ');
break;
default:
buf.append(scanner.getCurrentTokenSource());
buf.append(' ');
break;
}
}
content= buf.toString(); // success!
} catch (InvalidInputException ex) {
// NeedWork
}
}
return content;
}
/**
* Returns true since this IStructureCreator can rewrite the diff tree
* in order to fold certain combinations of additons and deletions.
*/
public boolean canRewriteTree() {
return true;
}
/**
* Tries to detect certain combinations of additons and deletions
* as renames or signature changes and foldes them into a single node.
*/
public void rewriteTree(Differencer differencer, IDiffContainer root) {
HashMap map= new HashMap(10);
Object[] children= root.getChildren();
for (int i= 0; i < children.length; i++) {
DiffNode diff= (DiffNode) children[i];
JavaNode jn= (JavaNode) diff.getId();
if (jn == null)
continue;
int type= jn.getTypeCode();
// we can only combine methods or constructors
if (type == JavaNode.METHOD || type == JavaNode.CONSTRUCTOR) {
// find or create a RewriteInfo for all methods with the same name
String name= jn.extractMethodName();
RewriteInfo nameInfo= (RewriteInfo) map.get(name);
if (nameInfo == null) {
nameInfo= new RewriteInfo();
map.put(name, nameInfo);
}
nameInfo.add(diff);
// find or create a RewriteInfo for all methods with the same
// (non-empty) argument list
String argList= jn.extractArgumentList();
RewriteInfo argInfo= null;
if (argList != null && !argList.equals("()")) { //$NON-NLS-1$
argInfo= (RewriteInfo) map.get(argList);
if (argInfo == null) {
argInfo= new RewriteInfo();
map.put(argList, argInfo);
}
argInfo.add(diff);
}
switch (diff.getKind() & Differencer.CHANGE_TYPE_MASK) {
case Differencer.ADDITION:
case Differencer.DELETION:
// we only consider addition and deletions
// since a rename or arg list change looks
// like a pair of addition and deletions
if (type != JavaNode.CONSTRUCTOR)
nameInfo.setDiff(diff);
if (argInfo != null)
argInfo.setDiff(diff);
break;
default:
break;
}
}
// recurse
if (diff instanceof IDiffContainer)
rewriteTree(differencer, diff);
}
// now we have to rebuild the diff tree according to the combined
// changes
Iterator it= map.keySet().iterator();
while (it.hasNext()) {
String name= (String) it.next();
RewriteInfo i= (RewriteInfo) map.get(name);
if (i.matches()) { // we found a RewriteInfo that could be succesfully combined
// we have to find the differences of the newly combined node
// (because in the first pass we only got a deletion and an addition)
DiffNode d= (DiffNode) differencer.findDifferences(true, null, root, i.fAncestor, i.fLeft, i.fRight);
if (d != null) {// there better should be a difference
d.setDontExpand(true);
Iterator it2= i.fChildren.iterator();
while (it2.hasNext()) {
IDiffElement rd= (IDiffElement) it2.next();
root.removeToRoot(rd);
d.add(rd);
}
}
}
}
}
/**
* If selector is an IJavaElement this method tries to return an
* IStructureComparator object for it.
* In case of error or if the given selector cannot be found
* null is returned.
* @param selector the IJavaElement to extract
* @param input must implement the IStreamContentAccessor interface.
*/
public IStructureComparator locate(Object selector, Object input) {
if (!(selector instanceof IJavaElement))
return null;
// try to build the JavaNode tree from input
IStructureComparator structure= getStructure(input);
if (structure == null) // we couldn't parse the structure
return null; // so we can't find anything
// build a path
String[] path= createPath((IJavaElement) selector);
// find the path in the JavaNode tree
return find(structure, path, 0);
}
private static String[] createPath(IJavaElement je) {
// build a path starting at the given Java element and walk
// up the parent chain until we reach a IWorkingCopy or ICompilationUnit
List args= new ArrayList();
while (je != null) {
// each path component has a name that uses the same
// conventions as a JavaNode name
String name= JavaCompareUtilities.getJavaElementID(je);
if (name == null)
return null;
args.add(name);
if (je instanceof IWorkingCopy || je instanceof ICompilationUnit)
break;
je= je.getParent();
}
// revert the path
int n= args.size();
String[] path= new String[n];
for (int i= 0; i < n; i++)
path[i]= (String) args.get(n-1-i);
return path;
}
/**
* Recursivly extracts the given path from the tree.
*/
private static IStructureComparator find(IStructureComparator tree, String[] path, int index) {
if (tree != null) {
Object[] children= tree.getChildren();
if (children != null) {
for (int i= 0; i < children.length; i++) {
IStructureComparator child= (IStructureComparator) children[i];
if (child instanceof ITypedElement && child instanceof DocumentRangeNode) {
String n1= null;
if (child instanceof DocumentRangeNode)
n1= ((DocumentRangeNode)child).getId();
if (n1 == null)
n1= ((ITypedElement)child).getName();
String n2= path[index];
if (n1.equals(n2)) {
if (index == path.length-1)
return child;
IStructureComparator result= find(child, path, index+1);
if (result != null)
return result;
}
}
}
}
}
return null;
}
/**
* Returns true if the given IJavaElement maps to a JavaNode.
* The JavaHistoryAction uses this function to determine whether
* a selected Java element can be replaced by some piece of
* code from the local history.
*/
static boolean hasEdition(IJavaElement je) {
if (je instanceof IMember && ((IMember)je).isBinary())
return false;
switch (je.getElementType()) {
case IJavaElement.COMPILATION_UNIT:
case IJavaElement.TYPE:
case IJavaElement.FIELD:
case IJavaElement.METHOD:
case IJavaElement.INITIALIZER:
case IJavaElement.PACKAGE_DECLARATION:
case IJavaElement.IMPORT_CONTAINER:
case IJavaElement.IMPORT_DECLARATION:
return true;
}
return false;
}
}
|
46,805 |
Bug 46805 prepare Compare for encoding support
|
I20031111 The Compare plugin only supports the global workspace encoding. It does not support encodings per file.
|
resolved fixed
|
842e720
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T23:11:14Z | 2003-11-17T23:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaTextViewer.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.compare;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.compare.IStreamContentAccessor;
public class JavaTextViewer extends Viewer {
private SourceViewer fSourceViewer;
private Object fInput;
JavaTextViewer(Composite parent) {
fSourceViewer= new SourceViewer(parent, null, SWT.H_SCROLL + SWT.V_SCROLL);
JavaTextTools tools= JavaCompareUtilities.getJavaTextTools();
if (tools != null)
fSourceViewer.configure(new JavaSourceViewerConfiguration(tools, null));
fSourceViewer.setEditable(false);
}
public Control getControl() {
return fSourceViewer.getControl();
}
public void setInput(Object input) {
if (input instanceof IStreamContentAccessor) {
Document document= new Document(getString(input));
JavaCompareUtilities.setupDocument(document);
fSourceViewer.setDocument(document);
}
fInput= input;
}
public Object getInput() {
return fInput;
}
public ISelection getSelection() {
return null;
}
public void setSelection(ISelection s, boolean reveal) {
}
public void refresh() {
}
/**
* A helper method to retrieve the contents of the given object
* if it implements the IStreamContentAccessor interface.
*/
private static String getString(Object input) {
if (input instanceof IStreamContentAccessor) {
IStreamContentAccessor sca= (IStreamContentAccessor) input;
try {
return JavaCompareUtilities.readString(sca.getContents());
} catch (CoreException ex) {
JavaPlugin.log(ex);
}
}
return ""; //$NON-NLS-1$
}
}
|
46,805 |
Bug 46805 prepare Compare for encoding support
|
I20031111 The Compare plugin only supports the global workspace encoding. It does not support encodings per file.
|
resolved fixed
|
842e720
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-17T23:11:14Z | 2003-11-17T23:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/PropertiesStructureCreator.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.compare;
import java.io.IOException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.text.*;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.compare.*;
import org.eclipse.compare.structuremergeviewer.*;
import org.eclipse.core.runtime.CoreException;
public class PropertiesStructureCreator implements IStructureCreator {
/**
* A PropertyNode represents a key/value pair of a Java property file.
* The text range of a ley/value pair starts with an optional
* comment and ends right after the value.
*/
static class PropertyNode extends DocumentRangeNode implements ITypedElement {
private boolean fIsEditable;
private PropertyNode fParent;
public PropertyNode(PropertyNode parent, int type, String id, String value, IDocument doc, int start, int length) {
super(type, id, doc, start, length);
fParent= parent;
if (parent != null) {
parent.addChild(this);
fIsEditable= parent.isEditable(); // propagate editability
}
}
public PropertyNode(IDocument doc, boolean editable) {
super(0, "root", doc, 0, doc.getLength()); //$NON-NLS-1$
fIsEditable= editable;
}
/* (non Java doc)
* see ITypedElement#getName
*/
public String getName() {
return this.getId();
}
/* (non Java doc)
* see ITypedElement#getType
*/
public String getType() {
return "txt"; //$NON-NLS-1$
}
/* (non Java doc)
* see ITypedElement#getImage
*/
public Image getImage() {
return CompareUI.getImage(getType());
}
/* (non Java doc)
* see IEditableContent.isEditable
*/
public boolean isEditable() {
return fIsEditable;
}
public void setContent(byte[] content) {
super.setContent(content);
nodeChanged(this);
}
public ITypedElement replace(ITypedElement child, ITypedElement other) {
ITypedElement e= super.replace(child, other);
nodeChanged(this);
return e;
}
void nodeChanged(PropertyNode node) {
if (fParent != null)
fParent.nodeChanged(node);
}
}
private static final String WHITESPACE= " \t\r\n\f"; //$NON-NLS-1$
private static final String SEPARATORS= "=:"; //$NON-NLS-1$
private static final String SEPARATORS2= SEPARATORS + WHITESPACE;
public PropertiesStructureCreator() {
}
public String getName() {
return CompareMessages.getString("PropertyCompareViewer.title"); //$NON-NLS-1$
}
public IStructureComparator getStructure(final Object input) {
String content= null;
if (input instanceof IStreamContentAccessor) {
try {
content= JavaCompareUtilities.readString(((IStreamContentAccessor) input).getContents());
} catch(CoreException ex) {
JavaPlugin.log(ex);
}
}
Document doc= new Document(content != null ? content : ""); //$NON-NLS-1$
boolean isEditable= false;
if (input instanceof IEditableContent)
isEditable= ((IEditableContent) input).isEditable();
PropertyNode root= new PropertyNode(doc, isEditable) {
void nodeChanged(PropertyNode node) {
save(this, input);
}
};
try {
parsePropertyFile(root, doc);
} catch (IOException ex) {
JavaPlugin.log(ex);
}
return root;
}
public boolean canSave() {
return true;
}
public void save(IStructureComparator structure, Object input) {
if (input instanceof IEditableContent && structure instanceof PropertyNode) {
IDocument doc= ((PropertyNode)structure).getDocument();
IEditableContent bca= (IEditableContent) input;
String content= doc.get();
bca.setContent(content.getBytes());
}
}
public IStructureComparator locate(Object path, Object source) {
return null;
}
public boolean canRewriteTree() {
return false;
}
/*
public void rewriteTree(Differencer differencer, IDiffContainer root) {
// empty implementation
}
*/
public String getContents(Object node, boolean ignoreWhitespace) {
if (node instanceof IStreamContentAccessor) {
IStreamContentAccessor sca= (IStreamContentAccessor) node;
try {
return JavaCompareUtilities.readString(sca.getContents());
} catch (CoreException ex) {
JavaPlugin.log(ex);
}
}
return null;
}
private String readLine(int[] args, IDocument doc) {
int line= args[0]++;
try {
IRegion region= doc.getLineInformation(line);
int start= region.getOffset();
int length= region.getLength();
try {
region= doc.getLineInformation(line+1);
args[1]= region.getOffset();
} catch (BadLocationException ex) {
args[1]= doc.getLength();
}
return doc.get(start, length);
} catch (BadLocationException ex) {
// silently ignored
}
return null;
}
private void parsePropertyFile(PropertyNode root, IDocument doc) throws IOException {
int start= -1;
int lineStart= 0;
int[] args= new int[2];
args[0]= 0; // here we return the line number
args[1]= 0; // and here the offset of the first character of the line
for (;;) {
lineStart= args[1]; // start of current line
String line= readLine(args, doc);
if (line == null)
return;
if (line.length() <= 0)
continue; // empty line
char firstChar= line.charAt(0);
if (firstChar == '#' || firstChar == '!') {
if (start < 0) // comment belongs to next key/value pair
start= lineStart;
continue; // comment
}
// find continuation lines
while (needNextLine(line)) {
String nextLine= readLine(args, doc);
if (nextLine == null)
nextLine= ""; //$NON-NLS-1$
String line2= line.substring(0, line.length()-1);
int startPos= 0;
for (; startPos < nextLine.length(); startPos++)
if (WHITESPACE.indexOf(nextLine.charAt(startPos)) == -1)
break;
nextLine= nextLine.substring(startPos, nextLine.length());
line= line2 + nextLine;
}
// key start
int len= line.length();
int keyPos= 0;
for (; keyPos < len; keyPos++) {
if (WHITESPACE.indexOf(line.charAt(keyPos)) == -1)
break;
}
// key/value separator
int separatorPos;
for (separatorPos= keyPos; separatorPos < len; separatorPos++) {
char c= line.charAt(separatorPos);
if (c == '\\')
separatorPos++;
else if (SEPARATORS2.indexOf(c) != -1)
break;
}
int valuePos;
for (valuePos= separatorPos; valuePos < len; valuePos++)
if (WHITESPACE.indexOf(line.charAt(valuePos)) == -1)
break;
if (valuePos < len)
if (SEPARATORS.indexOf(line.charAt(valuePos)) != -1)
valuePos++;
while (valuePos < len) {
if (WHITESPACE.indexOf(line.charAt(valuePos)) == -1)
break;
valuePos++;
}
String key= convert(line.substring(keyPos, separatorPos));
if (key.length() > 0) {
if (start < 0)
start= lineStart;
String value= ""; //$NON-NLS-1$
if (separatorPos < len)
value= convert(line.substring(valuePos, len));
int length= args[1] - start;
try {
String s= doc.get(start, length);
for (int i= s.length()-1; i >= 0; i--) {
char c= s.charAt(i);
if (c !='\r' && c != '\n')
break;
length--;
}
} catch (BadLocationException e) {
// silently ignored
}
new PropertyNode(root, 0, key, value, doc, start, length);
start= -1;
}
}
}
private boolean needNextLine(String line) {
int slashes= 0;
int ix= line.length() - 1;
while ((ix >= 0) && (line.charAt(ix--) == '\\'))
slashes++;
return slashes % 2 == 1;
}
/*
* Converts escaped characters to Unicode.
*/
private String convert(String s) {
int l= s.length();
StringBuffer buf= new StringBuffer(l);
int i= 0;
while (i < l) {
char c= s.charAt(i++);
if (c == '\\') {
c= s.charAt(i++);
if (c == 'u') {
int v= 0;
for (int j= 0; j < 4; j++) {
c= s.charAt(i++);
switch (c) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
v= (v << 4) + (c-'0');
break;
case 'a': case 'b': case 'c':
case 'd': case 'e': case 'f':
v= (v << 4) + 10+(c-'a');
break;
case 'A': case 'B': case 'C':
case 'D': case 'E': case 'F':
v= (v << 4) + 10+(c - 'A');
break;
default:
throw new IllegalArgumentException(CompareMessages.getString("PropertyCompareViewer.malformedEncoding")); //$NON-NLS-1$
}
}
buf.append((char)v);
} else {
switch (c) {
case 't':
c= '\t';
break;
case 'r':
c= '\r';
break;
case 'n':
c= '\n';
break;
case 'f':
c= '\f';
break;
}
buf.append(c);
}
} else
buf.append(c);
}
return buf.toString();
}
}
|
46,821 |
Bug 46821 NPE in LinkedPositionUI
|
Build: N-20031116 I'm not sure what provoked this NPE. But I know that I was unable to do anything afterwards. I had to shut down my workbench. Error Nov 17, 2003 23:40:33.872 java.lang.NullPointerException java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.leave (LinkedPositionUI.java:365) at org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.shellClosed (LinkedPositionUI.java:824) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:158) 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.Decorations.WM_CLOSE(Decorations.java:1390) at org.eclipse.swt.widgets.Shell.WM_CLOSE(Shell.java:1282) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2936) at org.eclipse.swt.widgets.Decorations.windowProc(Decorations.java:1334) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2712) at org.eclipse.swt.internal.win32.OS.DefWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.DefWindowProc(OS.java:1355) at org.eclipse.swt.widgets.Shell.callWindowProc(Shell.java:397) at org.eclipse.swt.widgets.Control.windowProc(Control.java:3014) at org.eclipse.swt.widgets.Decorations.windowProc(Decorations.java:1334) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2712) at org.eclipse.swt.internal.win32.OS.DefWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.DefWindowProc(OS.java:1355) at org.eclipse.swt.widgets.Shell.callWindowProc(Shell.java:397) at org.eclipse.swt.widgets.Control.windowProc(Control.java:3014) at org.eclipse.swt.widgets.Decorations.windowProc(Decorations.java:1334) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2712) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1360) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1875) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1402) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1378) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:234) 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(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) 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)
|
verified fixed
|
65aa3b8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-18T09:43:25Z | 2003-11-18T04:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/LinkedPositionUI.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 java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.CoreException;
//import org.eclipse.core.runtime.IStatus;
//import org.eclipse.core.runtime.Status;
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.PaintEvent;
import org.eclipse.swt.events.PaintListener;
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.GC;
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.dialogs.MessageDialog;
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.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.ITextInputListener;
import org.eclipse.jface.text.ITextListener;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension3;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextEvent;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
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;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
/**
* A user interface for <code>LinkedPositionManager</code>, using <code>ITextViewer</code>.
*/
public class LinkedPositionUI implements ILinkedPositionListener,
ITextInputListener, ITextListener, ModifyListener, VerifyListener, VerifyKeyListener, PaintListener, IPropertyChangeListener, ShellListener {
/**
* A listener for notification when the user cancelled the edit operation.
*/
public interface ExitListener {
void exit(boolean accept);
}
public static class ExitFlags {
public int flags;
public boolean doit;
public ExitFlags(int flags, boolean doit) {
this.flags= flags;
this.doit= doit;
}
}
public interface ExitPolicy {
ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, int offset, int length);
}
// leave flags
private static final int UNINSTALL= 1; // uninstall linked position manager
public static final int COMMIT= 2; // commit changes
private static final int DOCUMENT_CHANGED= 4; // document has changed
public static final int UPDATE_CARET= 8; // update caret
private static final IPreferenceStore fgStore= JavaPlugin.getDefault().getPreferenceStore();
private static final String CARET_POSITION_PREFIX= "LinkedPositionUI.caret.position"; //$NON-NLS-1$
private static int fgCounter= 0;
private final ITextViewer fViewer;
private final LinkedPositionManager fManager;
private final IPositionUpdater fUpdater;
private final String fPositionCategoryName;
private Color fFrameColor;
private int fFinalCaretOffset= -1; // no final caret offset
private Position fFinalCaretPosition;
private Position fFramePosition;
private int fInitialOffset= -1;
private int fCaretOffset;
private ExitPolicy fExitPolicy;
private ExitListener fExitListener;
private boolean fNeedRedraw;
private String fContentType;
private Position fPreviousPosition;
private ContentAssistant2 fAssistant;
/**
* Flag that records the state of this ui object. As there are many different entities that may
* call leave or exit, these cannot always be sure whether the linked position infrastructure is
* still active. This is especially true for multithreaded situations.
*/
private boolean fIsActive= false;
/**
* Creates a user interface for <code>LinkedPositionManager</code>.
*
* @param viewer the text viewer.
* @param manager the <code>LinkedPositionManager</code> managing a <code>IDocument</code> of the <code>ITextViewer</code>.
*/
public LinkedPositionUI(ITextViewer viewer, LinkedPositionManager manager) {
Assert.isNotNull(viewer);
Assert.isNotNull(manager);
fViewer= viewer;
fManager= manager;
fPositionCategoryName= CARET_POSITION_PREFIX + (fgCounter++);
fUpdater= new DefaultPositionUpdater(fPositionCategoryName);
fManager.setLinkedPositionListener(this);
initializeHighlightColor(viewer);
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(PreferenceConstants.EDITOR_LINKED_POSITION_COLOR)) {
initializeHighlightColor(fViewer);
redrawRegion();
}
}
private void initializeHighlightColor(ITextViewer viewer) {
if (fFrameColor != null)
fFrameColor.dispose();
StyledText text= viewer.getTextWidget();
if (text != null) {
Display display= text.getDisplay();
fFrameColor= createColor(fgStore, PreferenceConstants.EDITOR_LINKED_POSITION_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;
}
/**
* Sets the initial offset.
* @param offset
*/
public void setInitialOffset(int offset) {
fInitialOffset= offset;
}
/**
* Sets the final position of the caret when the linked mode is exited
* successfully by leaving the last linked position using TAB.
* The set position will be a TAB stop as well as the positions configured in the
* <code>LinkedPositionManager</code>.
*/
public void setFinalCaretOffset(int offset) {
fFinalCaretOffset= offset;
}
/**
* Sets a <code>CancelListener</code> which is notified if the linked mode
* is exited unsuccessfully by hitting ESC.
*/
public void setCancelListener(ExitListener listener) {
fExitListener= listener;
}
/**
* Sets an <code>ExitPolicy</code> which decides when and how
* the linked mode is exited.
*/
public void setExitPolicy(ExitPolicy policy) {
fExitPolicy= policy;
}
/*
* @see LinkedPositionManager.LinkedPositionListener#setCurrentPositions(Position, int)
*/
public void setCurrentPosition(Position position, int caretOffset) {
if (!fIsActive)
;//JavaPlugin.log(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is not active: "+fPositionCategoryName, new IllegalStateException())); //$NON-NLS-1$
if (!fFramePosition.equals(position)) {
fNeedRedraw= true;
fFramePosition= position;
}
fCaretOffset= caretOffset;
}
/**
* Enters the linked mode. The linked mode can be left by calling
* <code>exit</code>.
*
* @see #exit(boolean)
*/
public void enter() {
if (fIsActive)
;//JavaPlugin.log(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is already active: "+fPositionCategoryName, new IllegalStateException())); //$NON-NLS-1$
else {
fIsActive= true;
// JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI activated: "+fPositionCategoryName, new Exception())); //$NON-NLS-1$
}
// track final caret
IDocument document= fViewer.getDocument();
document.addPositionCategory(fPositionCategoryName);
document.addPositionUpdater(fUpdater);
try {
if (fFinalCaretOffset != -1) {
fFinalCaretPosition= new Position(fFinalCaretOffset);
document.addPosition(fPositionCategoryName, fFinalCaretPosition);
}
} catch (BadLocationException e) {
handleException(fViewer.getTextWidget().getShell(), e);
} catch (BadPositionCategoryException e) {
JavaPlugin.log(e);
Assert.isTrue(false);
}
fViewer.addTextInputListener(this);
fViewer.addTextListener(this);
ITextViewerExtension extension= (ITextViewerExtension) fViewer;
extension.prependVerifyKeyListener(this);
StyledText text= fViewer.getTextWidget();
text.addVerifyListener(this);
text.addModifyListener(this);
text.addPaintListener(this);
text.showSelection();
Shell shell= text.getShell();
shell.addShellListener(this);
fFramePosition= (fInitialOffset == -1) ? fManager.getFirstPosition() : fManager.getPosition(fInitialOffset);
if (fFramePosition == null) {
leave(UNINSTALL | COMMIT | UPDATE_CARET);
return;
}
fgStore.addPropertyChangeListener(this);
try {
fContentType= TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, fFramePosition.offset);
if (fViewer instanceof ITextViewerExtension2) {
((ITextViewerExtension2) fViewer).prependAutoEditStrategy(fManager, fContentType);
} else {
Assert.isTrue(false);
}
} catch (BadLocationException e) {
handleException(fViewer.getTextWidget().getShell(), e);
}
selectRegion();
triggerContentAssist();
}
/*
* @see org.eclipse.jdt.internal.ui.text.link.ILinkedPositionListener#exit(boolean)
*/
public void exit(int flags) {
leave(flags);
}
/**
* Returns the cursor selection, after having entered the linked mode.
* <code>enter()</code> must be called prior to a call to this method.
*/
public IRegion getSelectedRegion() {
if (!fIsActive)
;//JavaPlugin.log(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is not active: "+fPositionCategoryName, new IllegalStateException())); //$NON-NLS-1$
if (fFramePosition == null)
return new Region(fFinalCaretOffset, 0);
else
return new Region(fFramePosition.getOffset(), fFramePosition.getLength());
}
private void leave(int flags) {
if (!fIsActive)
;//JavaPlugin.log(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is not active: "+fPositionCategoryName, new IllegalStateException())); //$NON-NLS-1$
else {
fIsActive= false;
//JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI deactivated: "+fPositionCategoryName, new Exception())); //$NON-NLS-1$
}
fInitialOffset= -1;
if ((flags & UNINSTALL) != 0)
fManager.uninstall((flags & COMMIT) != 0);
fgStore.removePropertyChangeListener(this);
if (fFrameColor != null) {
fFrameColor.dispose();
fFrameColor= null;
}
StyledText text= fViewer.getTextWidget();
text.removePaintListener(this);
text.removeModifyListener(this);
text.removeVerifyListener(this);
Shell shell= text.getShell();
shell.removeShellListener(this);
if (fAssistant != null) {
Display display= text.getDisplay();
if (display != null && !display.isDisposed()) {
display.asyncExec(new Runnable() {
public void run() {
if (fAssistant != null) {
fAssistant.uninstall();
fAssistant= null;
}
}
});
}
}
ITextViewerExtension extension= (ITextViewerExtension) fViewer;
extension.removeVerifyKeyListener(this);
IRewriteTarget target= extension.getRewriteTarget();
target.endCompoundChange();
if (fViewer instanceof ITextViewerExtension2 && fContentType != null)
((ITextViewerExtension2) fViewer).removeAutoEditStrategy(fManager, fContentType);
fContentType= null;
fViewer.removeTextListener(this);
fViewer.removeTextInputListener(this);
try {
IDocument document= fViewer.getDocument();
if (((flags & COMMIT) != 0) &&
((flags & DOCUMENT_CHANGED) == 0) &&
((flags & UPDATE_CARET) != 0))
{
Position[] positions= document.getPositions(fPositionCategoryName);
if ((positions != null) && (positions.length != 0)) {
if (fViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension3= (ITextViewerExtension3) fViewer;
int widgetOffset= extension3.modelOffset2WidgetOffset(positions[0].getOffset());
if (widgetOffset >= 0)
text.setSelection(widgetOffset, widgetOffset);
} else {
IRegion region= fViewer.getVisibleRegion();
int offset= positions[0].getOffset() - region.getOffset();
if ((offset >= 0) && (offset <= region.getLength()))
text.setSelection(offset, offset);
}
}
}
document.removePositionUpdater(fUpdater);
document.removePositionCategory(fPositionCategoryName);
if (fExitListener != null)
fExitListener.exit(
((flags & COMMIT) != 0) ||
((flags & DOCUMENT_CHANGED) != 0));
} catch (BadPositionCategoryException e) {
JavaPlugin.log(e);
Assert.isTrue(false);
}
if ((flags & DOCUMENT_CHANGED) == 0)
text.redraw();
}
private void next() {
if (!fIsActive)
;//JavaPlugin.log(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is not active: "+fPositionCategoryName, new IllegalStateException())); //$NON-NLS-1$
redrawRegion();
if (fFramePosition == fFinalCaretPosition)
fFramePosition= fManager.getFirstPosition();
else
fFramePosition= fManager.getNextPosition(fFramePosition.getOffset());
if (fFramePosition == null) {
if (fFinalCaretPosition != null)
fFramePosition= fFinalCaretPosition;
else
fFramePosition= fManager.getFirstPosition();
}
if (fFramePosition == null) {
leave(UNINSTALL | COMMIT | UPDATE_CARET);
} else {
selectRegion();
triggerContentAssist();
redrawRegion();
}
}
private void previous() {
if (!fIsActive)
;//JavaPlugin.log(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is not active: "+fPositionCategoryName, new IllegalStateException())); //$NON-NLS-1$
redrawRegion();
fFramePosition= fManager.getPreviousPosition(fFramePosition.getOffset());
if (fFramePosition == null) {
if (fFinalCaretPosition != null)
fFramePosition= fFinalCaretPosition;
else
fFramePosition= fManager.getLastPosition();
}
if (fFramePosition == null) {
leave(UNINSTALL | COMMIT | UPDATE_CARET);
} else {
selectRegion();
triggerContentAssist();
redrawRegion();
}
}
/** Trigger content assist on choice positions */
private void triggerContentAssist() {
if (fFramePosition instanceof ProposalPosition) {
ProposalPosition pp= (ProposalPosition) fFramePosition;
initializeContentAssistant();
if (fAssistant == null)
return;
fAssistant.setCompletions(pp.getChoices());
fAssistant.showPossibleCompletions();
} else {
if (fAssistant != null)
fAssistant.setCompletions(new ICompletionProposal[0]);
}
}
/** Lazy initialize content assistant for this linked ui */
private void initializeContentAssistant() {
if (fAssistant != null)
return;
fAssistant= new ContentAssistant2();
fAssistant.setDocumentPartitioning(IJavaPartitions.JAVA_PARTITIONING);
fAssistant.install(fViewer);
}
/*
* @see VerifyKeyListener#verifyKey(VerifyEvent)
*/
public void verifyKey(VerifyEvent event) {
if (!event.doit || !fIsActive)
return;
Point selection= fViewer.getSelectedRange();
int offset= selection.x;
int length= selection.y;
ExitFlags exitFlags= fExitPolicy == null ? null : fExitPolicy.doExit(fManager, event, offset, length);
if (exitFlags != null) {
leave(UNINSTALL | exitFlags.flags);
event.doit= exitFlags.doit;
return;
}
switch (event.character) {
// [SHIFT-]TAB = hop between edit boxes
case 0x09:
{
// if tab was treated as a document change, would it exceed variable range?
if (!LinkedPositionManager.includes(fFramePosition, offset, length)) {
leave(UNINSTALL | COMMIT);
return;
}
}
if (event.stateMask == SWT.SHIFT)
previous();
else
next();
event.doit= false;
break;
// ENTER
case 0x0A: // Ctrl+Enter
case 0x0D:
{
if (fAssistant != null && fAssistant.wasProposalChosen()) {
next();
event.doit= false;
break;
}
// if enter was treated as a document change, would it exceed variable range?
if (!LinkedPositionManager.includes(fFramePosition, offset, length)
|| (fFramePosition == fFinalCaretPosition)) {
leave(UNINSTALL | COMMIT);
return;
}
}
leave(UNINSTALL | COMMIT | UPDATE_CARET);
event.doit= false;
break;
// ESC
case 0x1B:
leave(UNINSTALL | COMMIT);
event.doit= false;
break;
case ';':
leave(UNINSTALL | COMMIT);
event.doit= true;
break;
default:
if (event.character != 0) {
if (!controlUndoBehavior(offset, length) || fFramePosition == fFinalCaretPosition) {
leave(UNINSTALL | COMMIT);
break;
}
}
}
}
private boolean controlUndoBehavior(int offset, int length) {
Position position= fManager.getEmbracingPosition(offset, length);
if (position != null) {
ITextViewerExtension extension= (ITextViewerExtension) fViewer;
IRewriteTarget target= extension.getRewriteTarget();
if (fPreviousPosition != null && !fPreviousPosition.equals(position))
target.endCompoundChange();
target.beginCompoundChange();
}
fPreviousPosition= position;
return fPreviousPosition != null;
}
/*
* @see VerifyListener#verifyText(VerifyEvent)
*/
public void verifyText(VerifyEvent event) {
if (!event.doit)
return;
int offset= 0;
int length= 0;
if (fViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) fViewer;
IRegion modelRange= extension.widgetRange2ModelRange(new Region(event.start, event.end - event.start));
if (modelRange == null)
return;
offset= modelRange.getOffset();
length= modelRange.getLength();
} else {
IRegion visibleRegion= fViewer.getVisibleRegion();
offset= event.start + visibleRegion.getOffset();
length= event.end - event.start;
}
// allow changes only within linked positions when coming through UI
if (!fManager.anyPositionIncludes(offset, length))
leave(UNINSTALL | COMMIT);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fFramePosition == null)
return;
IRegion widgetRange= asWidgetRange(fFramePosition);
if (widgetRange == null) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int offset= widgetRange.getOffset();
int length= widgetRange.getLength();
StyledText text= fViewer.getTextWidget();
// 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;
gc.setForeground(fFrameColor);
gc.drawLine(x1, y, x2, y);
}
protected IRegion asWidgetRange(Position position) {
if (fViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) fViewer;
return extension.modelRange2WidgetRange(new Region(position.getOffset(), position.getLength()));
} else {
IRegion region= fViewer.getVisibleRegion();
if (includes(region, position))
return new Region(position.getOffset() - region.getOffset(), position.getLength());
}
return null;
}
private static 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 static 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;
}
private void redrawRegion() {
IRegion widgetRange= asWidgetRange(fFramePosition);
if (widgetRange == null) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
StyledText text= fViewer.getTextWidget();
if (text != null && !text.isDisposed())
text.redrawRange(widgetRange.getOffset(), widgetRange.getLength(), true);
}
private void selectRegion() {
IRegion widgetRange= asWidgetRange(fFramePosition);
if (widgetRange == null) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
StyledText text= fViewer.getTextWidget();
if (text != null && !text.isDisposed()) {
int start= widgetRange.getOffset();
int end= widgetRange.getLength() + start;
text.setSelection(start, end);
}
}
private void updateCaret() {
IRegion widgetRange= asWidgetRange(fFramePosition);
if (widgetRange == null) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int offset= widgetRange.getOffset() + fCaretOffset;
StyledText text= fViewer.getTextWidget();
if (text != null && !text.isDisposed())
text.setCaretOffset(offset);
}
/*
* @see ModifyListener#modifyText(ModifyEvent)
*/
public void modifyText(ModifyEvent e) {
// reposition caret after StyledText
redrawRegion();
updateCaret();
}
private static void handleException(Shell shell, Exception e) {
String title= LinkedPositionMessages.getString("LinkedPositionUI.error.title"); //$NON-NLS-1$
if (e instanceof CoreException)
ExceptionHandler.handle((CoreException)e, shell, title, null);
else if (e instanceof InvocationTargetException)
ExceptionHandler.handle((InvocationTargetException)e, shell, title, null);
else {
MessageDialog.openError(shell, title, e.getMessage());
JavaPlugin.log(e);
}
}
/*
* @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
// 5326: leave linked mode on document change
int flags= UNINSTALL | COMMIT | (oldInput.equals(newInput) ? 0 : DOCUMENT_CHANGED);
leave(flags);
}
/*
* @see ITextInputListener#inputDocumentChanged(IDocument, IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
}
private static boolean includes(IRegion region, Position position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
/*
* @see org.eclipse.jface.text.ITextListener#textChanged(TextEvent)
*/
public void textChanged(TextEvent event) {
if (!fNeedRedraw)
return;
redrawRegion();
fNeedRedraw= false;
}
/*
* @see org.eclipse.swt.events.ShellListener#shellActivated(org.eclipse.swt.events.ShellEvent)
*/
public void shellActivated(ShellEvent event) {
}
/*
* @see org.eclipse.swt.events.ShellListener#shellClosed(org.eclipse.swt.events.ShellEvent)
*/
public void shellClosed(ShellEvent event) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
}
/*
* @see org.eclipse.swt.events.ShellListener#shellDeactivated(org.eclipse.swt.events.ShellEvent)
*/
public void shellDeactivated(ShellEvent event) {
// 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
// TODO check whether we can leave it or uncomment it after debugging
// PS: why DOCUMENT_CHANGED? We want to trigger a redraw! (Shell deactivated does not mean
// it is not visible any longer.
// leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
// 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 || fViewer == null || (text= fViewer.getTextWidget()) == null
|| (display= text.getDisplay()) == null || display.isDisposed()) {
leave(UNINSTALL | COMMIT);
} 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() {
// TODO add isDisposed / isUninstalled / hasLeft check? for now: check for content type,
// since it gets nullified in leave()
if (fIsActive && (fAssistant == null || !fAssistant.hasFocus())) {
leave(UNINSTALL | COMMIT);
}
}
});
}
}
/*
* @see org.eclipse.swt.events.ShellListener#shellDeiconified(org.eclipse.swt.events.ShellEvent)
*/
public void shellDeiconified(ShellEvent event) {
}
/*
* @see org.eclipse.swt.events.ShellListener#shellIconified(org.eclipse.swt.events.ShellEvent)
*/
public void shellIconified(ShellEvent event) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
}
}
|
45,062 |
Bug 45062 Don't filter output folder and class files
|
Create a Java project with source folder src and output folder bin. The bin folder will not be shown in the Packages Explorer. Create a Java project with source folder src and output folder output/bin. The output and bin folders are shown in the Packages Explorer. Implictly filtering out bin is confusing and inconsistent. A better way to do this would be to use a name filter for bin or add "Output folder" to the list of available filters.
|
resolved wontfix
|
5ebdcbb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-18T11:05:34Z | 2003-10-16T21:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filters/OutputFolderFilter.java
| |
45,062 |
Bug 45062 Don't filter output folder and class files
|
Create a Java project with source folder src and output folder bin. The bin folder will not be shown in the Packages Explorer. Create a Java project with source folder src and output folder output/bin. The output and bin folders are shown in the Packages Explorer. Implictly filtering out bin is confusing and inconsistent. A better way to do this would be to use a name filter for bin or add "Output folder" to the list of available filters.
|
resolved wontfix
|
5ebdcbb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-18T11:05:34Z | 2003-10-16T21:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerPart.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.packageview;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IOpenListener;
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.ITreeContentProvider;
import org.eclipse.jface.viewers.ITreeViewerListener;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeExpansionEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.part.ISetSelectionTarget;
import org.eclipse.ui.part.IShowInSource;
import org.eclipse.ui.part.IShowInTarget;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.part.ResourceTransfer;
import org.eclipse.ui.part.ShowInContext;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.JdtViewerDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.ResourceTransferDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.FilterUpdater;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
import org.eclipse.jdt.ui.IPackagesViewPart;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
/**
* The ViewPart for the ProjectExplorer. It listens to part activation events.
* When selection linking with the editor is enabled the view selection tracks
* the active editor page. Similarly when a resource is selected in the packages
* view the corresponding editor is activated.
*/
public class PackageExplorerPart extends ViewPart
implements ISetSelectionTarget, IMenuListener,
IShowInTarget,
IPackagesViewPart, IPropertyChangeListener,
IViewPartInputProvider {
private boolean fIsCurrentLayoutFlat; // true means flat, false means hierachical
private static final int HIERARCHICAL_LAYOUT= 0x1;
private static final int FLAT_LAYOUT= 0x2;
public final static String VIEW_ID= JavaUI.ID_PACKAGES;
// Persistance tags.
static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
static final String TAG_EXPANDED= "expanded"; //$NON-NLS-1$
static final String TAG_ELEMENT= "element"; //$NON-NLS-1$
static final String TAG_PATH= "path"; //$NON-NLS-1$
static final String TAG_VERTICAL_POSITION= "verticalPosition"; //$NON-NLS-1$
static final String TAG_HORIZONTAL_POSITION= "horizontalPosition"; //$NON-NLS-1$
static final String TAG_FILTERS = "filters"; //$NON-NLS-1$
static final String TAG_FILTER = "filter"; //$NON-NLS-1$
static final String TAG_LAYOUT= "layout"; //$NON-NLS-1$
private PackageExplorerContentProvider fContentProvider;
private FilterUpdater fFilterUpdater;
private PackageExplorerActionGroup fActionSet;
private ProblemTreeViewer fViewer;
private Menu fContextMenu;
private IMemento fMemento;
private ISelectionChangedListener fSelectionListener;
private String fWorkingSetName;
private IPartListener fPartListener= new IPartListener() {
public void partActivated(IWorkbenchPart part) {
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partBroughtToTop(IWorkbenchPart part) {
}
public void partClosed(IWorkbenchPart part) {
}
public void partDeactivated(IWorkbenchPart part) {
}
public void partOpened(IWorkbenchPart part) {
}
};
private ITreeViewerListener fExpansionListener= new ITreeViewerListener() {
public void treeCollapsed(TreeExpansionEvent event) {
}
public void treeExpanded(TreeExpansionEvent event) {
Object element= event.getElement();
if (element instanceof ICompilationUnit ||
element instanceof IClassFile)
expandMainType(element);
}
};
private PackageExplorerLabelProvider fLabelProvider;
/* (non-Javadoc)
* Method declared on IViewPart.
*/
private boolean fLinkingEnabled;
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
restoreLayoutState(memento);
}
private void restoreLayoutState(IMemento memento) {
Integer state= null;
if (memento != null)
state= memento.getInteger(TAG_LAYOUT);
// If no memento try an restore from preference store
if(state == null) {
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
state= new Integer(store.getInt(TAG_LAYOUT));
}
if (state.intValue() == FLAT_LAYOUT)
fIsCurrentLayoutFlat= true;
else if (state.intValue() == HIERARCHICAL_LAYOUT)
fIsCurrentLayoutFlat= false;
else
fIsCurrentLayoutFlat= true;
}
/**
* Returns the package explorer part of the active perspective. If
* there isn't any package explorer part <code>null</code> is returned.
*/
public static PackageExplorerPart getFromActivePerspective() {
IWorkbenchPage activePage= JavaPlugin.getActivePage();
if (activePage == null)
return null;
IViewPart view= activePage.findView(VIEW_ID);
if (view instanceof PackageExplorerPart)
return (PackageExplorerPart)view;
return null;
}
/**
* Makes the package explorer part visible in the active perspective. If there
* isn't a package explorer part registered <code>null</code> is returned.
* Otherwise the opened view part is returned.
*/
public static PackageExplorerPart openInActivePerspective() {
try {
return (PackageExplorerPart)JavaPlugin.getActivePage().showView(VIEW_ID);
} catch(PartInitException pe) {
return null;
}
}
public void dispose() {
if (fContextMenu != null && !fContextMenu.isDisposed())
fContextMenu.dispose();
getSite().getPage().removePartListener(fPartListener);
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
if (fViewer != null)
fViewer.removeTreeListener(fExpansionListener);
if (fActionSet != null)
fActionSet.dispose();
if (fFilterUpdater != null)
ResourcesPlugin.getWorkspace().removeResourceChangeListener(fFilterUpdater);
super.dispose();
}
/**
* Implementation of IWorkbenchPart.createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
fViewer= createViewer(parent);
fViewer.setUseHashlookup(true);
if (!JavaPlugin.USE_WORKING_COPY_OWNERS) {
fViewer.setComparer(new PackageExplorerElementComparer());
}
initDragAndDrop();
setProviders();
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
fContextMenu= menuMgr.createContextMenu(fViewer.getTree());
fViewer.getTree().setMenu(fContextMenu);
// Register viewer with site. This must be done before making the actions.
IWorkbenchPartSite site= getSite();
site.registerContextMenu(menuMgr, fViewer);
site.setSelectionProvider(fViewer);
site.getPage().addPartListener(fPartListener);
if (fMemento != null) {
restoreLinkingEnabled(fMemento);
}
makeActions(); // call before registering for selection changes
// Set input after filter and sorter has been set. This avoids resorting and refiltering.
restoreFilterAndSorter();
fViewer.setInput(findInputElement());
initFrameActions();
initKeyListener();
fSelectionListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
handleSelectionChanged(event);
}
};
fViewer.addPostSelectionChangedListener(fSelectionListener);
fViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
fActionSet.handleDoubleClick(event);
}
});
fViewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
fActionSet.handleOpen(event);
}
});
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager));
fViewer.addTreeListener(fExpansionListener);
if (fMemento != null)
restoreUIState(fMemento);
fMemento= null;
// Set help for the view
JavaUIHelp.setHelp(fViewer, IJavaHelpContextIds.PACKAGES_VIEW);
fillActionBars();
updateTitle();
fFilterUpdater= new FilterUpdater(fViewer);
ResourcesPlugin.getWorkspace().addResourceChangeListener(fFilterUpdater);
}
private void initFrameActions() {
fActionSet.getUpAction().update();
fActionSet.getBackAction().update();
fActionSet.getForwardAction().update();
}
/**
* This viewer ensures that non-leaves in the hierarchical
* layout are not removed by any filters.
*
* @since 2.1
*/
private ProblemTreeViewer createViewer(Composite composite) {
return new ProblemTreeViewer(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL) {
/*
* @see org.eclipse.jface.viewers.StructuredViewer#filter(java.lang.Object)
*/
protected Object[] getFilteredChildren(Object parent) {
List list = new ArrayList();
ViewerFilter[] filters = fViewer.getFilters();
Object[] children = ((ITreeContentProvider) fViewer.getContentProvider()).getChildren(parent);
for (int i = 0; i < children.length; i++) {
Object object = children[i];
if (!isEssential(object)) {
object = filter(object, parent, filters);
if (object != null) {
list.add(object);
}
} else
list.add(object);
}
return list.toArray();
}
// Sends the object through the given filters
private Object filter(Object object, Object parent, ViewerFilter[] filters) {
for (int i = 0; i < filters.length; i++) {
ViewerFilter filter = filters[i];
if (!filter.select(fViewer, parent, object))
return null;
}
return object;
}
/* Checks if a filtered object in essential (ie. is a parent that
* should not be removed).
*/
private boolean isEssential(Object object) {
try {
if (!isFlatLayout() && object instanceof IPackageFragment) {
IPackageFragment fragment = (IPackageFragment) object;
return !fragment.isDefaultPackage() && fragment.hasSubpackages();
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return false;
}
protected void handleInvalidSelection(ISelection invalidSelection, ISelection newSelection) {
IStructuredSelection is= (IStructuredSelection)invalidSelection;
List ns= null;
if (newSelection instanceof IStructuredSelection) {
ns= new ArrayList(((IStructuredSelection)newSelection).toList());
} else {
ns= new ArrayList();
}
boolean changed= false;
for (Iterator iter= is.iterator(); iter.hasNext();) {
Object element= iter.next();
if (element instanceof IJavaProject) {
IProject project= ((IJavaProject)element).getProject();
if (!project.isOpen()) {
ns.add(project);
changed= true;
}
} else if (element instanceof IProject) {
IProject project= (IProject)element;
if (project.isOpen()) {
IJavaProject jProject= JavaCore.create(project);
if (jProject != null && jProject.exists())
ns.add(jProject);
changed= true;
}
}
}
if (changed) {
newSelection= new StructuredSelection(ns);
setSelection(newSelection);
}
super.handleInvalidSelection(invalidSelection, newSelection);
}
};
}
/**
* Answers whether this part shows the packages flat or hierarchical.
*
* @since 2.1
*/
boolean isFlatLayout() {
return fIsCurrentLayoutFlat;
}
private void setProviders() {
//content provider must be set before the label provider
fContentProvider= createContentProvider();
fContentProvider.setIsFlatLayout(fIsCurrentLayoutFlat);
fViewer.setContentProvider(fContentProvider);
fLabelProvider= createLabelProvider();
fLabelProvider.setIsFlatLayout(fIsCurrentLayoutFlat);
fViewer.setLabelProvider(new DecoratingJavaLabelProvider(fLabelProvider, false, false));
// problem decoration provided by PackageLabelProvider
}
void toggleLayout() {
// Update current state and inform content and label providers
fIsCurrentLayoutFlat= !fIsCurrentLayoutFlat;
saveLayoutState(null);
fContentProvider.setIsFlatLayout(isFlatLayout());
fLabelProvider.setIsFlatLayout(isFlatLayout());
fViewer.getControl().setRedraw(false);
fViewer.refresh();
fViewer.getControl().setRedraw(true);
}
/**
* This method should only be called inside this class
* and from test cases.
*/
public PackageExplorerContentProvider createContentProvider() {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
boolean showCUChildren= store.getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
boolean reconcile= PreferenceConstants.UPDATE_WHILE_EDITING.equals(store.getString(PreferenceConstants.UPDATE_JAVA_VIEWS));
return new PackageExplorerContentProvider(this, showCUChildren, reconcile);
}
private PackageExplorerLabelProvider createLabelProvider() {
return new PackageExplorerLabelProvider(AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.P_COMPRESSED,
AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS,
fContentProvider);
}
private void fillActionBars() {
IActionBars actionBars= getViewSite().getActionBars();
fActionSet.fillActionBars(actionBars);
}
private Object findInputElement() {
Object input= getSite().getPage().getInput();
if (input instanceof IWorkspace) {
return JavaCore.create(((IWorkspace)input).getRoot());
} else if (input instanceof IContainer) {
IJavaElement element= JavaCore.create((IContainer)input);
if (element != null && element.exists())
return element;
return input;
}
//1GERPRT: ITPJUI:ALL - Packages View is empty when shown in Type Hierarchy Perspective
// we can't handle the input
// fall back to show the workspace
return JavaCore.create(JavaPlugin.getWorkspace().getRoot());
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key.equals(ISelectionProvider.class))
return fViewer;
if (key == IShowInSource.class) {
return getShowInSource();
}
if (key == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { IPageLayout.ID_RES_NAV };
}
};
}
return super.getAdapter(key);
}
/**
* Returns the tool tip text for the given element.
*/
String getToolTipText(Object element) {
String result;
if (!(element instanceof IResource)) {
if (element instanceof IJavaModel)
result= PackagesMessages.getString("PackageExplorerPart.workspace"); //$NON-NLS-1$
else
result= JavaElementLabels.getTextLabel(element, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS);
} else {
IPath path= ((IResource) element).getFullPath();
if (path.isRoot()) {
result= PackagesMessages.getString("PackageExplorer.title"); //$NON-NLS-1$
} else {
result= path.makeRelative().toString();
}
}
if (fWorkingSetName == null)
return result;
String wsstr= PackagesMessages.getFormattedString("PackageExplorer.toolTip", new String[] { fWorkingSetName }); //$NON-NLS-1$
if (result.length() == 0)
return wsstr;
return PackagesMessages.getFormattedString("PackageExplorer.toolTip2", new String[] { result, fWorkingSetName }); //$NON-NLS-1$
}
public String getTitleToolTip() {
if (fViewer == null)
return super.getTitleToolTip();
return getToolTipText(fViewer.getInput());
}
/**
* @see IWorkbenchPart#setFocus()
*/
public void setFocus() {
fViewer.getTree().setFocus();
}
/**
* Returns the current selection.
*/
private ISelection getSelection() {
return fViewer.getSelection();
}
//---- Action handling ----------------------------------------------------------
/**
* Called when the context menu is about to open. Override
* to add your own context dependent menu contributions.
*/
public void menuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
fActionSet.setContext(new ActionContext(getSelection()));
fActionSet.fillContextMenu(menu);
fActionSet.setContext(null);
}
private void makeActions() {
fActionSet= new PackageExplorerActionGroup(this);
}
//---- Event handling ----------------------------------------------------------
private void initDragAndDrop() {
initDrag();
initDrop();
}
private void initDrag() {
int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
Transfer[] transfers= new Transfer[] {
LocalSelectionTransfer.getInstance(),
ResourceTransfer.getInstance(),
FileTransfer.getInstance()};
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fViewer),
new ResourceTransferDragAdapter(fViewer),
new FileTransferDragAdapter(fViewer)
};
fViewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(fViewer, dragListeners));
}
private void initDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK | DND.DROP_DEFAULT;
Transfer[] transfers= new Transfer[] {
LocalSelectionTransfer.getInstance(),
FileTransfer.getInstance()};
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fViewer),
new FileTransferDropAdapter(fViewer)
};
fViewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
}
/**
* Handles selection changed in viewer.
* Updates global actions.
* Links to editor (if option enabled)
*/
private void handleSelectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection= (IStructuredSelection) event.getSelection();
fActionSet.handleSelectionChanged(event);
if (isLinkingEnabled())
linkToEditor(selection);
}
public void selectReveal(ISelection selection) {
selectReveal(selection, 0);
}
private void selectReveal(final ISelection selection, final int count) {
Control ctrl= getViewer().getControl();
if (ctrl == null || ctrl.isDisposed())
return;
ISelection javaSelection= convertSelection(selection);
fViewer.setSelection(javaSelection, true);
PackageExplorerContentProvider provider= (PackageExplorerContentProvider)getViewer().getContentProvider();
ISelection cs= fViewer.getSelection();
// If we have Pending changes and the element could not be selected then
// we try it again on more time by posting the select and reveal asynchronuoulsy
// to the event queue. See PR http://bugs.eclipse.org/bugs/show_bug.cgi?id=30700
// for a discussion of the underlying problem.
if (count == 0 && provider.hasPendingChanges() && !javaSelection.equals(cs)) {
ctrl.getDisplay().asyncExec(new Runnable() {
public void run() {
selectReveal(selection, count + 1);
}
});
}
}
private ISelection convertSelection(ISelection s) {
if (!(s instanceof IStructuredSelection))
return s;
Object[] elements= ((StructuredSelection)s).toArray();
if (!containsResources(elements))
return s;
for (int i= 0; i < elements.length; i++) {
Object o= elements[i];
if (!(o instanceof IJavaElement)) {
if (o instanceof IResource) {
IJavaElement jElement= JavaCore.create((IResource)o);
if (jElement != null && jElement.exists())
elements[i]= jElement;
}
else if (o instanceof IAdaptable) {
IResource r= (IResource)((IAdaptable)o).getAdapter(IResource.class);
if (r != null) {
IJavaElement jElement= JavaCore.create(r);
if (jElement != null && jElement.exists())
elements[i]= jElement;
else
elements[i]= r;
}
}
}
}
return new StructuredSelection(elements);
}
private boolean containsResources(Object[] elements) {
for (int i = 0; i < elements.length; i++) {
Object o= elements[i];
if (!(o instanceof IJavaElement)) {
if (o instanceof IResource)
return true;
if ((o instanceof IAdaptable) && ((IAdaptable)o).getAdapter(IResource.class) != null)
return true;
}
}
return false;
}
public void selectAndReveal(Object element) {
selectReveal(new StructuredSelection(element));
}
boolean isLinkingEnabled() {
return fLinkingEnabled;
}
/**
* Initializes the linking enabled setting from the preference store.
*/
private void initLinkingEnabled() {
fLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_PACKAGES_TO_EDITOR);
}
/**
* Links to editor (if option enabled)
*/
private void linkToEditor(IStructuredSelection selection) {
// ignore selection changes if the package explorer is not the active part.
// In this case the selection change isn't triggered by a user.
if (!isActivePart())
return;
Object obj= selection.getFirstElement();
if (selection.size() == 1) {
IEditorPart part= EditorUtility.isOpenInEditor(obj);
if (part != null) {
IWorkbenchPage page= getSite().getPage();
page.bringToTop(part);
if (obj instanceof IJavaElement)
EditorUtility.revealInEditor(part, (IJavaElement) obj);
}
}
}
private boolean isActivePart() {
return this == getSite().getPage().getActivePart();
}
public void saveState(IMemento memento) {
if (fViewer == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
saveExpansionState(memento);
saveSelectionState(memento);
saveLayoutState(memento);
saveLinkingEnabled(memento);
// commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676
//saveScrollState(memento, fViewer.getTree());
fActionSet.saveFilterAndSorterState(memento);
}
private void saveLinkingEnabled(IMemento memento) {
memento.putInteger(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, fLinkingEnabled ? 1 : 0);
}
/**
* Saves the current layout state.
*
* @param memento the memento to save the state into or
* <code>null</code> to store the state in the preferences
* @since 2.1
*/
private void saveLayoutState(IMemento memento) {
if (memento != null) {
memento.putInteger(TAG_LAYOUT, getLayoutAsInt());
} else {
//if memento is null save in preference store
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(TAG_LAYOUT, getLayoutAsInt());
}
}
private int getLayoutAsInt() {
if (fIsCurrentLayoutFlat)
return FLAT_LAYOUT;
else
return HIERARCHICAL_LAYOUT;
}
protected void saveScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_VERTICAL_POSITION, String.valueOf(position));
//save horizontal position
bar= tree.getHorizontalBar();
position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_HORIZONTAL_POSITION, String.valueOf(position));
}
protected void saveSelectionState(IMemento memento) {
Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray();
if (elements.length > 0) {
IMemento selectionMem= memento.createChild(TAG_SELECTION);
for (int i= 0; i < elements.length; i++) {
IMemento elementMem= selectionMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= elements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) elements[i]).getHandleIdentifier());
}
}
}
protected void saveExpansionState(IMemento memento) {
Object expandedElements[]= fViewer.getVisibleExpandedElements();
if (expandedElements.length > 0) {
IMemento expandedMem= memento.createChild(TAG_EXPANDED);
for (int i= 0; i < expandedElements.length; i++) {
IMemento elementMem= expandedMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= expandedElements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) expandedElements[i]).getHandleIdentifier());
}
}
}
private void restoreFilterAndSorter() {
fViewer.setSorter(new JavaElementSorter());
if (fMemento != null)
fActionSet.restoreFilterAndSorterState(fMemento);
}
private void restoreUIState(IMemento memento) {
restoreExpansionState(memento);
restoreSelectionState(memento);
// commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676
//restoreScrollState(memento, fViewer.getTree());
}
private void restoreLinkingEnabled(IMemento memento) {
Integer val= memento.getInteger(PreferenceConstants.LINK_PACKAGES_TO_EDITOR);
if (val != null) {
fLinkingEnabled= val.intValue() != 0;
}
}
protected void restoreScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_VERTICAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore, don't set scrollposition
}
}
bar= tree.getHorizontalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_HORIZONTAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore don't set scroll position
}
}
}
protected void restoreSelectionState(IMemento memento) {
IMemento childMem;
childMem= memento.getChild(TAG_SELECTION);
if (childMem != null) {
ArrayList list= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
if (element != null)
list.add(element);
}
fViewer.setSelection(new StructuredSelection(list));
}
}
protected void restoreExpansionState(IMemento memento) {
IMemento childMem= memento.getChild(TAG_EXPANDED);
if (childMem != null) {
ArrayList elements= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
if (element != null)
elements.add(element);
}
fViewer.setExpandedElements(elements.toArray());
}
}
/**
* Create the KeyListener for doing the refresh on the viewer.
*/
private void initKeyListener() {
fViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
fActionSet.handleKeyEvent(event);
}
});
}
/**
* An editor has been activated. Set the selection in this Packages Viewer
* to be the editor's input, if linking is enabled.
*/
void editorActivated(IEditorPart editor) {
if (!isLinkingEnabled())
return;
showInput(getElementOfInput(editor.getEditorInput()));
}
boolean showInput(Object input) {
Object element= null;
if (input instanceof IFile && isOnClassPath((IFile)input)) {
element= JavaCore.create((IFile)input);
}
if (element == null) // try a non Java resource
element= input;
if (element != null) {
ISelection newSelection= new StructuredSelection(element);
if (fViewer.getSelection().equals(newSelection)) {
fViewer.reveal(element);
} else {
try {
fViewer.removeSelectionChangedListener(fSelectionListener);
fViewer.setSelection(newSelection, true);
while (element != null && fViewer.getSelection().isEmpty()) {
// Try to select parent in case element is filtered
element= getParent(element);
if (element != null) {
newSelection= new StructuredSelection(element);
fViewer.setSelection(newSelection, true);
}
}
} finally {
fViewer.addSelectionChangedListener(fSelectionListener);
}
}
return true;
}
return false;
}
private boolean isOnClassPath(IFile file) {
IJavaProject jproject= JavaCore.create(file.getProject());
return jproject.isOnClasspath(file);
}
/**
* Returns the element's parent.
*
* @return the parent or <code>null</code> if there's no parent
*/
private Object getParent(Object element) {
if (element instanceof IJavaElement)
return ((IJavaElement)element).getParent();
else if (element instanceof IResource)
return ((IResource)element).getParent();
// else if (element instanceof IStorage) {
// can't get parent - see bug 22376
// }
return null;
}
/**
* A compilation unit or class was expanded, expand
* the main type.
*/
void expandMainType(Object element) {
try {
IType type= null;
if (element instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit)element;
IType[] types= cu.getTypes();
if (types.length > 0)
type= types[0];
}
else if (element instanceof IClassFile) {
IClassFile cf= (IClassFile)element;
type= cf.getType();
}
if (type != null) {
final IType type2= type;
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.getDisplay().asyncExec(new Runnable() {
public void run() {
Control ctrl2= fViewer.getControl();
if (ctrl2 != null && !ctrl2.isDisposed())
fViewer.expandToLevel(type2, 1);
}
});
}
}
} catch(JavaModelException e) {
// no reveal
}
}
/**
* Returns the element contained in the EditorInput
*/
Object getElementOfInput(IEditorInput input) {
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
else if (input instanceof IFileEditorInput)
return ((IFileEditorInput)input).getFile();
else if (input instanceof JarEntryEditorInput)
return ((JarEntryEditorInput)input).getStorage();
return null;
}
/**
* Returns the Viewer.
*/
TreeViewer getViewer() {
return fViewer;
}
/**
* Returns the TreeViewer.
*/
public TreeViewer getTreeViewer() {
return fViewer;
}
boolean isExpandable(Object element) {
if (fViewer == null)
return false;
return fViewer.isExpandable(element);
}
void setWorkingSetName(String workingSetName) {
fWorkingSetName= workingSetName;
}
/**
* Updates the title text and title tool tip.
* Called whenever the input of the viewer changes.
*/
void updateTitle() {
Object input= fViewer.getInput();
String viewName= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$
if (input == null
|| (input instanceof IJavaModel)) {
setTitle(viewName);
setTitleToolTip(""); //$NON-NLS-1$
} else {
String inputText= JavaElementLabels.getTextLabel(input, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS);
String title= PackagesMessages.getFormattedString("PackageExplorer.argTitle", new String[] { viewName, inputText }); //$NON-NLS-1$
setTitle(title);
setTitleToolTip(getToolTipText(input));
}
}
/**
* Sets the decorator for the package explorer.
*
* @param decorator a label decorator or <code>null</code> for no decorations.
* @deprecated To be removed
*/
public void setLabelDecorator(ILabelDecorator decorator) {
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (fViewer == null)
return;
boolean refreshViewer= false;
if (PreferenceConstants.SHOW_CU_CHILDREN.equals(event.getProperty())) {
fActionSet.updateActionBars(getViewSite().getActionBars());
boolean showCUChildren= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
((StandardJavaElementContentProvider)fViewer.getContentProvider()).setProvideMembers(showCUChildren);
refreshViewer= true;
} else if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
refreshViewer= true;
}
if (refreshViewer)
fViewer.refresh();
}
/* (non-Javadoc)
* @see IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
if (fViewer != null) {
return fViewer.getInput();
}
return null;
}
public void collapseAll() {
fViewer.getControl().setRedraw(false);
fViewer.collapseToLevel(getViewPartInput(), AbstractTreeViewer.ALL_LEVELS);
fViewer.getControl().setRedraw(true);
}
public PackageExplorerPart() {
initLinkingEnabled();
}
public boolean show(ShowInContext context) {
Object input= context.getInput();
if (input instanceof IEditorInput) {
Object elementOfInput= getElementOfInput((IEditorInput)context.getInput());
if (elementOfInput == null)
return false;
return showInput(elementOfInput);
}
ISelection selection= context.getSelection();
if (selection != null) {
selectReveal(selection);
return true;
}
return false;
}
/**
* Returns the <code>IShowInSource</code> for this view.
*/
protected IShowInSource getShowInSource() {
return new IShowInSource() {
public ShowInContext getShowInContext() {
return new ShowInContext(
getViewer().getInput(),
getViewer().getSelection());
}
};
}
/*
* @see org.eclipse.ui.views.navigator.IResourceNavigator#setLinkingEnabled(boolean)
* @since 2.1
*/
public void setLinkingEnabled(boolean enabled) {
fLinkingEnabled= enabled;
PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, enabled);
if (enabled) {
IEditorPart editor = getSite().getPage().getActiveEditor();
if (editor != null) {
editorActivated(editor);
}
}
}
/**
* Returns the name for the given element.
* Used as the name for the current frame.
*/
String getFrameName(Object element) {
if (element instanceof IJavaElement) {
return ((IJavaElement) element).getElementName();
} else {
return ((ILabelProvider) getTreeViewer().getLabelProvider()).getText(element);
}
}
void projectStateChanged(Object root) {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
fViewer.refresh(root, true);
// trigger a syntetic selection change so that action refresh their
// enable state.
fViewer.setSelection(fViewer.getSelection());
}
}
}
|
45,444 |
Bug 45444 Open declaration on local variable doesn't select variable name
|
Build 20031023 1. Create the following cu: public class X { void foo() { int var = 1; var++; } } 2. Select 'var' in the 'var++;' statement 3. F3 Observe: The cursor goes to the begining of the 'int var = 1;' statement. I would expect that 'var' is selected in this statement.
|
resolved fixed
|
bffd227
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-18T13:48:19Z | 2003-10-23T14:40:00Z |
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.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.Event;
import org.eclipse.swt.widgets.Listener;
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.IAnnotationAccess;
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.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.IEncodingSupport;
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.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.AddTaskAction;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.DefaultAnnotation;
import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.ExtendedTextEditor;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
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.MarkerAnnotationPreferences;
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.search.ui.SearchUI;
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.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();
updateOccurrences();
}
}
/**
* 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;
}
}
}
static protected class AnnotationAccess extends DefaultMarkerAnnotationAccess {
public AnnotationAccess(MarkerAnnotationPreferences markerAnnotationPreferences) {
super(markerAnnotationPreferences);
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation)
*/
public Object getType(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.getAnnotationType();
return null;
}
return super.getType(annotation);
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation)
*/
public boolean isMultiLine(Annotation annotation) {
return true;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation)
*/
public boolean isTemporary(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.isTemporary();
}
return false;
}
}
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();
}
}
}
}
/** 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;
/**
* 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;
}
/*
* @see org.eclipse.ui.texteditor.ExtendedTextEditor#createAnnotationAccess()
*/
protected IAnnotationAccess createAnnotationAccess() {
return new AnnotationAccess(new MarkerAnnotationPreferences());
}
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= 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 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 (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();
ResourceAction resAction= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$
resAction.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION);
resAction.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK);
setAction(ITextEditorActionConstants.ADD_TASK, resAction);
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});
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().addListener(SWT.Deactivate, new Listener() {
/*
* @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
*/
public void handleEvent(Event event) {
removeOccurrenceAnnotations();
}
});
getEditorSite().getShell().addListener(SWT.Activate, new Listener() {
/*
* @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
*/
public void handleEvent(Event event) {
updateOccurrences();
}
});
}
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());
if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation)annotation).isProblem())
setStatusLineMessage(((IJavaAnnotation)annotation).getMessage());
}
}
}
/**
* 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 DefaultAnnotation(SearchUI.SEARCH_MARKER, IMarker.SEVERITY_INFO, true, 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 updateOccurrences() {
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(((IJavaAnnotation)annotation).getMessage());
}
}
/**
* 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(int offset, 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= 0;
IAnnotationAccess access= getAnnotationAccess();
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true, true);
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
Object type;
if (a instanceof IJavaAnnotation)
type= ((IJavaAnnotation) a).getAnnotationType();
else
type= access.getType(a);
boolean isNavigationTarget= isNavigationTargetType(type);
if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation)a).hasOverlay() || !isNavigationTarget)
continue;
Position p= model.getPosition(a);
if (p == null)
continue;
if (!(p.includes(offset) || (p.getLength() == 0 && offset == p.offset))) {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument - offset + p.getOffset();
} else {
currentDistance= offset - p.getOffset();
if (currentDistance < 0)
currentDistance= offset + endOfDocument - p.getOffset();
}
if (nextAnnotation == null || currentDistance < distance) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
} else {
if (containingAnnotationPosition == null || containingAnnotationPosition.length > p.length) {
containingAnnotation= a;
containingAnnotationPosition= p;
if (length == p.length)
currentAnnotation= true;
}
}
}
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) {
IAnnotationAccess access= getAnnotationAccess();
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 annotation= (IJavaAnnotation) a;
if (annotation.hasOverlay() || !isNavigationTargetType(annotation.getAnnotationType()))
continue;
} else if (!isNavigationTargetType(access.getType(a)))
continue;
Position p= model.getPosition(a);
if (p != null && p.overlapsWith(offset, length))
return a;
}
return null;
}
/**
* Returns whether the given annotation type is configured as a target type
* for the "Go to Next/Previous Annotation" actions
*
* @param type the annotation type
* @return <code>true</code> if this is a target type, <code>false</code>
* otherwise
* @since 3.0
*/
private boolean isNavigationTargetType(Object type) {
Preferences preferences= Platform.getPlugin("org.eclipse.ui.editors").getPluginPreferences(); //$NON-NLS-1$
Iterator i= getAnnotationPreferences().getAnnotationPreferences().iterator();
while (i.hasNext()) {
AnnotationPreference annotationPref= (AnnotationPreference) i.next();
if (annotationPref.getAnnotationType().equals(type)) {
// See bug 41689
// String key= forward ? annotationPref.getIsGoToNextNavigationTargetKey() : annotationPref.getIsGoToPreviousNavigationTargetKey();
String key= annotationPref.getIsGoToNextNavigationTargetKey();
if (key != null && preferences.getBoolean(key))
return true;
}
}
return false;
}
/**
* 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);
}
}
|
44,549 |
Bug 44549 NLS Keys search page element order is confusing [search]
|
I20031008 The tree dialog created by the (Properties) Browse button in the NLS Keys search page is not purely alphabetical. It seems to be ordering based on whether the project is a source or a binary import project, and within those groups further ordered alphabetically. This is confusing. A quick look tells me that there is some kind of alphabetical sorting going on so I head to the bottom of the list thinking th project will be there (based on name) yet it isn't. I have to navigate the entire tree to find my project.
|
resolved fixed
|
3621cdb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-18T15:09:39Z | 2003-10-09T14:33:20Z |
org.eclipse.jdt.ui/ui
| |
44,549 |
Bug 44549 NLS Keys search page element order is confusing [search]
|
I20031008 The tree dialog created by the (Properties) Browse button in the NLS Keys search page is not purely alphabetical. It seems to be ordering based on whether the project is a source or a binary import project, and within those groups further ordered alphabetically. This is confusing. A quick look tells me that there is some kind of alphabetical sorting going on so I head to the bottom of the list thinking th project will be there (based on name) yet it isn't. I have to navigate the entire tree to find my project.
|
resolved fixed
|
3621cdb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-18T15:09:39Z | 2003-10-09T14:33:20Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/nls/search/NLSSearchPage.java
| |
46,886 |
Bug 46886 Build hangs
|
I use autobuild. Happened after pressing Ctrl+S (save) Starting Eclipse N20031114 *************************** The following JRE is used to launch Eclipse: java version "1.4.2" Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2-b28) Java HotSpot(TM) Client VM (build 1.4.2-b28, mixed mode) VM Options=-Xms50M -Xmx350M Target Workspace=c:\eclipse\workspaces\Development_2_2\plugins C:\eclipse\drops\N20031114>C:\JavaSDKs\jdk1.4.2\bin\java -Xms50M -Xmx350M -verify -cp startup.jar org.eclipse.core.launcher.Main -update -application org.eclipse.ui.ide.workbench -showlocation -data c :\eclipse\workspaces\Development_2_2\plugins Full thread dump Java HotSpot(TM) Client VM (1.4.2-b28 mixed mode): "Thread-81" prio=5 tid=0x03ea1730 nid=0xe7c in Object.wait() [46ef000..46efd94] at java.lang.Object.wait(Native Method) - waiting on <0x1030dd38> (a org.eclipse.core.internal.jobs.Semaphore) at org.eclipse.core.internal.jobs.Semaphore.acquire(Semaphore.java:36) - locked <0x1030dd38> (a org.eclipse.core.internal.jobs.Semaphore) at org.eclipse.core.internal.jobs.JobManager.join(JobManager.java:391) at org.eclipse.core.internal.jobs.InternalJob.join(InternalJob.java:175) at org.eclipse.core.runtime.jobs.Job.join(Job.java:286) at org.eclipse.core.internal.events.BuildManager.interrupt(BuildManager.java:309) at org.eclipse.core.internal.resources.Workspace.prepareOperation(Workspace.java:1515) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1549) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1573) at org.eclipse.jdt.internal.debug.core.hcr.JavaHotCodeReplaceManager$3.run(JavaHotCodeReplaceManager.java:1105) at java.lang.Thread.run(Thread.java:534) "Worker-40" prio=5 tid=0x03ea15a0 nid=0x34c in Object.wait() [47cf000..47cfd94] at java.lang.Object.wait(Native Method) - waiting on <0x100bb150> (a org.eclipse.core.internal.jobs.Semaphore) at org.eclipse.core.internal.jobs.Semaphore.acquire(Semaphore.java:36) - locked <0x100bb150> (a org.eclipse.core.internal.jobs.Semaphore) at org.eclipse.core.internal.jobs.OrderedLock.doAcquire(OrderedLock.java:153) at org.eclipse.core.internal.jobs.OrderedLock.acquire(OrderedLock.java:98) at org.eclipse.core.internal.jobs.OrderedLock.acquire(OrderedLock.java:74) at org.eclipse.core.internal.resources.WorkManager.checkIn(WorkManager.java:109) at org.eclipse.core.internal.resources.Workspace.prepareOperation(Workspace.java:1516) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1549) at org.eclipse.core.internal.events.NotificationManager$NotifyJob.run(NotificationManager.java:37) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:62) "Worker-39" prio=5 tid=0x03edcc88 nid=0xee8 in Object.wait() [473f000..473fd94] at java.lang.Object.wait(Native Method) - waiting on <0x11c36c78> (a org.eclipse.core.internal.jobs.WorkerPool) at org.eclipse.core.internal.jobs.WorkerPool.sleep(WorkerPool.java:189) - locked <0x11c36c78> (a org.eclipse.core.internal.jobs.WorkerPool) at org.eclipse.core.internal.jobs.WorkerPool.startJob(WorkerPool.java:215) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) "Worker-38" prio=5 tid=0x03e2b300 nid=0x948 waiting on condition [388f000..388fd94] at java.lang.Thread.sleep(Native Method) at org.eclipse.ui.internal.progress.AnimationManager.animateLoop(AnimationManager.java:318) at org.eclipse.ui.internal.progress.AnimationManager$3.run(AnimationManager.java:467) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:62) "Worker-31" prio=5 tid=0x03e2d448 nid=0x1a0 waiting for monitor entry [454f000..454fd94] at org.eclipse.jdt.internal.ui.javaeditor.filebuffers.CompilationUnitDocumentProvider2$CompilationUnitAnnotationModel.update(CompilationUnitDocumentProvider2.java:413) - waiting to lock <0x122bf510> (a org.eclipse.jdt.internal.core.CompilationUnit) at org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel$ResourceChangeListener.resourceChanged(ResourceMarkerAnnotationModel.java:53) at org.eclipse.core.internal.events.NotificationManager$2.run(NotificationManager.java:251) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:1127) at org.eclipse.core.runtime.Platform.run(Platform.java:464) at org.eclipse.core.internal.events.NotificationManager.notify(NotificationManager.java:244) at org.eclipse.core.internal.events.NotificationManager.broadcastChanges(NotificationManager.java:138) at org.eclipse.core.internal.resources.Workspace.broadcastChanges(Workspace.java:146) at org.eclipse.core.internal.resources.Workspace.endOperation(Workspace.java:847) at org.eclipse.core.internal.resources.File.setContents(File.java:283) at org.eclipse.core.internal.resources.File.setContents(File.java:323) at org.eclipse.jdt.internal.core.builder.IncrementalImageBuilder.writeClassFileBytes(IncrementalImageBuilder.java:581) at org.eclipse.jdt.internal.core.builder.AbstractImageBuilder.writeClassFile(AbstractImageBuilder.java:445) at org.eclipse.jdt.internal.core.builder.AbstractImageBuilder.acceptResult(AbstractImageBuilder.java:117) at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:340) at org.eclipse.jdt.internal.core.builder.AbstractImageBuilder.compile(AbstractImageBuilder.java:205) at org.eclipse.jdt.internal.core.builder.AbstractImageBuilder.compile(AbstractImageBuilder.java:155) at org.eclipse.jdt.internal.core.builder.IncrementalImageBuilder.build(IncrementalImageBuilder.java:113) at org.eclipse.jdt.internal.core.builder.JavaBuilder.buildDeltas(JavaBuilder.java:223) at org.eclipse.jdt.internal.core.builder.JavaBuilder.build(JavaBuilder.java:151) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:482) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:1127) at org.eclipse.core.runtime.Platform.run(Platform.java:464) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:130) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:201) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:156) at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:182) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:1127) at org.eclipse.core.runtime.Platform.run(Platform.java:464) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:185) at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:219) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:247) at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:76) at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:109) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:62) "Thread timer" prio=7 tid=0x03e9fdc0 nid=0xb78 waiting on condition [4a1f000..4a1fd94] at java.lang.Thread.sleep(Native Method) at org.eclipse.debug.internal.ui.views.launch.LaunchViewEventHandler$ThreadTimer.checkTimers(LaunchViewEventHandler.java:435) at org.eclipse.debug.internal.ui.views.launch.LaunchViewEventHandler$ThreadTimer.access$2(LaunchViewEventHandler.java:402) at org.eclipse.debug.internal.ui.views.launch.LaunchViewEventHandler$1.run(LaunchViewEventHandler.java:394) at java.lang.Thread.run(Thread.java:534) "org.eclipse.jdt.debug: JDI Event Dispatcher" prio=5 tid=0x03e2c7a0 nid=0xbe4 in Object.wait() [4b1f000..4b1fd94] at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:429) at org.eclipse.jdi.internal.connect.PacketReceiveManager.waitForPacketAvailable(PacketReceiveManager.java:168) at org.eclipse.jdi.internal.connect.PacketReceiveManager.getCommand(PacketReceiveManager.java:93) - locked <0x157c8c88> (a org.eclipse.jdi.internal.connect.PacketReceiveManager) at org.eclipse.jdi.internal.MirrorImpl.getCommandVM(MirrorImpl.java:276) at org.eclipse.jdi.internal.event.EventQueueImpl.remove(EventQueueImpl.java:63) at org.eclipse.jdi.internal.event.EventQueueImpl.remove(EventQueueImpl.java:48) at org.eclipse.jdt.internal.debug.core.EventDispatcher.run(EventDispatcher.java:206) at java.lang.Thread.run(Thread.java:534) "Packet Send Manager" prio=5 tid=0x03e2a9a0 nid=0xbd8 in Object.wait() [4a9f000..4a9fd94] at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:429) at org.eclipse.jdi.internal.connect.PacketSendManager.sendAvailablePackets(PacketSendManager.java:94) - locked <0x157c8dd0> (a org.eclipse.jdi.internal.connect.PacketSendManager) at org.eclipse.jdi.internal.connect.PacketSendManager.run(PacketSendManager.java:54) at java.lang.Thread.run(Thread.java:534) "Packet Receive Manager" prio=5 tid=0x03e66118 nid=0x310 runnable [4a5f000..4a5fd94] at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(SocketInputStream.java:129) at java.net.SocketInputStream.read(SocketInputStream.java:182) at java.io.DataInputStream.readInt(DataInputStream.java:443) at org.eclipse.jdi.internal.jdwp.JdwpPacket.read(JdwpPacket.java:124) at org.eclipse.jdi.internal.connect.PacketReceiveManager.readAvailablePacket(PacketReceiveManager.java:224) at org.eclipse.jdi.internal.connect.PacketReceiveManager.run(PacketReceiveManager.java:70) at java.lang.Thread.run(Thread.java:534) "Console Polling Thread" prio=7 tid=0x03e66498 nid=0x888 waiting on condition [49df000..49dfd94] at java.lang.Thread.sleep(Native Method) at org.eclipse.debug.internal.ui.views.console.ConsoleDocumentPartitioner.pollAndSleep(ConsoleDocumentPartitioner.java:563) at org.eclipse.debug.internal.ui.views.console.ConsoleDocumentPartitioner$1.run(ConsoleDocumentPartitioner.java:547) at java.lang.Thread.run(Thread.java:534) "Input Stream Monitor" prio=5 tid=0x035c7d48 nid=0xbc4 in Object.wait() [499f000..499fd94] at java.lang.Object.wait(Native Method) - waiting on <0x157b1538> (a java.lang.Object) at java.lang.Object.wait(Object.java:429) at org.eclipse.debug.internal.core.InputStreamMonitor.writeNext(InputStreamMonitor.java:124) - locked <0x157b1538> (a java.lang.Object) at org.eclipse.debug.internal.core.InputStreamMonitor.write(InputStreamMonitor.java:99) at org.eclipse.debug.internal.core.InputStreamMonitor$1.run(InputStreamMonitor.java:75) at java.lang.Thread.run(Thread.java:534) "Output Stream Monitor" prio=5 tid=0x03e8bee8 nid=0xe44 runnable [495f000..495fd94] at java.io.FileInputStream.readBytes(Native Method) at java.io.FileInputStream.read(FileInputStream.java:177) at org.eclipse.debug.internal.core.OutputStreamMonitor.read(OutputStreamMonitor.java:132) at org.eclipse.debug.internal.core.OutputStreamMonitor.access$1(OutputStreamMonitor.java:124) at org.eclipse.debug.internal.core.OutputStreamMonitor$1.run(OutputStreamMonitor.java:177) at java.lang.Thread.run(Thread.java:534) "Output Stream Monitor" prio=5 tid=0x03edc728 nid=0xba8 runnable [491f000..491fd94] at java.io.FileInputStream.readBytes(Native Method) at java.io.FileInputStream.read(FileInputStream.java:194) at java.io.BufferedInputStream.read1(BufferedInputStream.java:220) at java.io.BufferedInputStream.read(BufferedInputStream.java:277) - locked <0x157b0a30> (a java.io.BufferedInputStream) at java.io.FilterInputStream.read(FilterInputStream.java:90) at org.eclipse.debug.internal.core.OutputStreamMonitor.read(OutputStreamMonitor.java:132) at org.eclipse.debug.internal.core.OutputStreamMonitor.access$1(OutputStreamMonitor.java:124) at org.eclipse.debug.internal.core.OutputStreamMonitor$1.run(OutputStreamMonitor.java:177) at java.lang.Thread.run(Thread.java:534) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x03e8c848 nid=0xbe8 in Object.wait() [48cf000..48cfd94] at java.lang.Object.wait(Native Method) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:161) - locked <0x15456b28> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x034f0470 nid=0x890 in Object.wait() [478f000..478fd94] at java.lang.Object.wait(Native Method) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:161) - locked <0x15456b88> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x03e666a8 nid=0xff4 in Object.wait() [463f000..463fd94] at java.lang.Object.wait(Native Method) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:161) - locked <0x15456d18> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x03de28d8 nid=0xbe0 in Object.wait() [458f000..458fd94] at java.lang.Object.wait(Native Method) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:161) - locked <0x153dd118> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x03d86648 nid=0xd1c in Object.wait() [45ff000..45ffd94] at java.lang.Object.wait(Native Method) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:161) - locked <0x14f36df8> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x032a7620 nid=0x838 in Object.wait() [381f000..381fd94] at java.lang.Object.wait(Native Method) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:161) - locked <0x14daa2b0> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "Worker-3" prio=5 tid=0x0354d3e0 nid=0xc30 runnable [443f000..443fd94] at java.lang.Win32Process.waitFor(Native Method) at org.eclipse.debug.core.model.RuntimeProcess$ProcessMonitorJob.run(RuntimeProcess.java:347) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:62) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x03570230 nid=0x2d8 in Object.wait() [3a6f000..3a6fd94] at java.lang.Object.wait(Native Method) - waiting on <0x12c54ec8> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:161) - locked <0x12c54ec8> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x0349ef60 nid=0xfe4 in Object.wait() [38df000..38dfd94] at java.lang.Object.wait(Native Method) - waiting on <0x12ac2500> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:161) - locked <0x12ac2500> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "Java indexing" daemon prio=4 tid=0x00a3d600 nid=0x9f0 in Object.wait() [379f000..379fd94] at java.lang.Object.wait(Native Method) - waiting on <0x121b2348> (a org.eclipse.jdt.internal.core.search.indexing.IndexManager) at java.lang.Object.wait(Object.java:429) at org.eclipse.jdt.internal.core.search.processing.JobManager.run(JobManager.java:325) - locked <0x121b2348> (a org.eclipse.jdt.internal.core.search.indexing.IndexManager) at java.lang.Thread.run(Thread.java:534) "Signal Dispatcher" daemon prio=10 tid=0x00a13e88 nid=0x954 waiting on condition [0..0] "Finalizer" daemon prio=9 tid=0x00a0f0e8 nid=0xfb0 in Object.wait() [2c6f000..2c6fd94] at java.lang.Object.wait(Native Method) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:111) - locked <0x11af0138> (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:127) at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159) "Reference Handler" daemon prio=10 tid=0x009c1a20 nid=0xfac in Object.wait() [2c2f000..2c2fd94] at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:429) at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:115) - locked <0x11af01a0> (a java.lang.ref.Reference$Lock) "main" prio=5 tid=0x000350d8 nid=0xf18 in Object.wait() [7e000..7fc3c] at java.lang.Object.wait(Native Method) - waiting on <0x16b3d468> (a org.eclipse.core.internal.jobs.Semaphore) at org.eclipse.core.internal.jobs.Semaphore.acquire(Semaphore.java:36) - locked <0x16b3d468> (a org.eclipse.core.internal.jobs.Semaphore) at org.eclipse.core.internal.jobs.JobManager.join(JobManager.java:391) at org.eclipse.core.internal.jobs.InternalJob.join(InternalJob.java:175) at org.eclipse.core.runtime.jobs.Job.join(Job.java:286) at org.eclipse.core.internal.events.BuildManager.interrupt(BuildManager.java:309) at org.eclipse.core.internal.resources.Workspace.prepareOperation(Workspace.java:1515) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1549) at org.eclipse.ui.actions.WorkspaceModifyOperation.run(WorkspaceModifyOperation.java:105) - locked <0x16b3d4b8> (a org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation) at org.eclipse.ui.editors.text.WorkspaceOperationRunner.run(WorkspaceOperationRunner.java:72) at org.eclipse.ui.editors.text.WorkspaceOperationRunner.run(WorkspaceOperationRunner.java:62) at org.eclipse.ui.editors.text.TextFileDocumentProvider.executeOperation(TextFileDocumentProvider.java:388) at org.eclipse.ui.editors.text.TextFileDocumentProvider.saveDocument(TextFileDocumentProvider.java:597) at org.eclipse.ui.texteditor.AbstractTextEditor.performSave(AbstractTextEditor.java:3140) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.performSave(CompilationUnitEditor.java:821) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.doSave(CompilationUnitEditor.java:885) - locked <0x122bf510> (a org.eclipse.jdt.internal.core.CompilationUnit) at org.eclipse.ui.internal.EditorManager$10.run(EditorManager.java:1080) at org.eclipse.ui.internal.EditorManager$8.run(EditorManager.java:936) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:302) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jface.window.ApplicationWindow$1.run(ApplicationWindow.java:444) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.jface.window.ApplicationWindow.run(ApplicationWindow.java:441) at org.eclipse.ui.internal.WorkbenchWindow.run(WorkbenchWindow.java:1458) at org.eclipse.ui.internal.EditorManager.runProgressMonitorOperation(EditorManager.java:942) at org.eclipse.ui.internal.EditorManager.savePart(EditorManager.java:1085) at org.eclipse.ui.internal.WorkbenchPage.savePart(WorkbenchPage.java:2267) at org.eclipse.ui.internal.WorkbenchPage.saveEditor(WorkbenchPage.java:2279) at org.eclipse.ui.internal.SaveAction.run(SaveAction.java:72) 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:466) 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:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1413) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1389) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:236) 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: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) "VM Thread" prio=5 tid=0x009bd970 nid=0xf9c runnable "VM Periodic Task Thread" prio=10 tid=0x00a10498 nid=0xfe8 waiting on condition "Suspend Checker Thread" prio=10 tid=0x00a02540 nid=0x960 runnable
|
resolved fixed
|
225900c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-20T11:44:21Z | 2003-11-18T21:13: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.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.IAnnotationExtension;
import org.eclipse.ui.texteditor.MarkerAnnotation;
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, IAnnotationExtension {
private static final String TASK_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.task"; //$NON-NLS-1$
private static final String ERROR_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.error"; //$NON-NLS-1$
private static final String WARNING_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.warning"; //$NON-NLS-1$
private static final String INFO_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.info"; //$NON-NLS-1$
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;
private String fType;
public ProblemAnnotation(IProblem problem, ICompilationUnit cu) {
fProblem= problem;
fCompilationUnit= cu;
if (IProblem.Task == fProblem.getID()) {
fType= TASK_ANNOTATION_TYPE;
setLayer(DefaultAnnotation.TASK_LAYER + 1);
} else if (fProblem.isWarning()) {
fType= WARNING_ANNOTATION_TYPE;
setLayer(DefaultAnnotation.WARNING_LAYER + 1);
} else if (fProblem.isError()) {
fType= ERROR_ANNOTATION_TYPE;
setLayer(DefaultAnnotation.ERROR_LAYER + 1);
} else {
fType= 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 (ERROR_ANNOTATION_TYPE.equals(fType))
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 getMessage() {
return fProblem.getMessage();
}
/*
* @see IJavaAnnotation#isTemporary()
*/
public boolean isTemporary() {
return true;
}
/*
* @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() {
return WARNING_ANNOTATION_TYPE.equals(fType) || ERROR_ANNOTATION_TYPE.equals(fType);
}
/*
* @see IJavaAnnotation#isRelevant()
*/
public boolean isRelevant() {
return true;
}
/*
* @see IJavaAnnotation#hasOverlay()
*/
public boolean hasOverlay() {
return false;
}
/*
* @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;
}
public String getAnnotationType() {
return fType;
}
/*
* @see IAnnotationExtension#getMarkerType()
*/
public String getMarkerType() {
if (isProblem() || INFO_ANNOTATION_TYPE.equals(fType))
return IMarker.PROBLEM;
else
return IMarker.TASK;
}
/*
* @see IAnnotationExtension#getSeverity()
*/
public int getSeverity() {
if (ERROR_ANNOTATION_TYPE.equals(fType))
return IMarker.SEVERITY_ERROR;
if (WARNING_ANNOTATION_TYPE.equals(fType))
return IMarker.SEVERITY_WARNING;
return IMarker.SEVERITY_INFO;
}
/*
* @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 CompilationUnitAnnotationModelEvent fCurrentEvent;
private boolean fIncludesProblemAnnotationChanges= false;
public CompilationUnitAnnotationModel(IFileEditorInput input) {
super(input.getFile());
fInput= input;
fCurrentEvent= new CompilationUnitAnnotationModelEvent(this, getResource());
}
protected MarkerAnnotation createMarkerAnnotation(IMarker marker) {
return new JavaMarkerAnnotation(marker);
}
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) {
synchronized (workingCopy) {
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 AnnotationModel#fireModelChanged()
*/
protected void fireModelChanged() {
fireModelChanged(fCurrentEvent);
fIncludesProblemAnnotationChanges= fCurrentEvent.includesProblemMarkerAnnotationChanges();
fCurrentEvent= new CompilationUnitAnnotationModelEvent(this, getResource());
}
/*
* @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);
fCurrentEvent.annotationAdded(annotation);
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) {
for (Iterator iter= getAnnotationIterator(); iter.hasNext();) {
fCurrentEvent.annotationRemoved((Annotation) iter.next());
}
super.removeAllAnnotations(fireModelChanged);
fReverseMap.clear();
}
/*
* @see AnnotationModel#removeAnnotation(Annotation, boolean)
*/
protected void removeAnnotation(Annotation annotation, boolean fireModelChanged) {
fCurrentEvent.annotationRemoved(annotation);
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);
}
}
|
46,886 |
Bug 46886 Build hangs
|
I use autobuild. Happened after pressing Ctrl+S (save) Starting Eclipse N20031114 *************************** The following JRE is used to launch Eclipse: java version "1.4.2" Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2-b28) Java HotSpot(TM) Client VM (build 1.4.2-b28, mixed mode) VM Options=-Xms50M -Xmx350M Target Workspace=c:\eclipse\workspaces\Development_2_2\plugins C:\eclipse\drops\N20031114>C:\JavaSDKs\jdk1.4.2\bin\java -Xms50M -Xmx350M -verify -cp startup.jar org.eclipse.core.launcher.Main -update -application org.eclipse.ui.ide.workbench -showlocation -data c :\eclipse\workspaces\Development_2_2\plugins Full thread dump Java HotSpot(TM) Client VM (1.4.2-b28 mixed mode): "Thread-81" prio=5 tid=0x03ea1730 nid=0xe7c in Object.wait() [46ef000..46efd94] at java.lang.Object.wait(Native Method) - waiting on <0x1030dd38> (a org.eclipse.core.internal.jobs.Semaphore) at org.eclipse.core.internal.jobs.Semaphore.acquire(Semaphore.java:36) - locked <0x1030dd38> (a org.eclipse.core.internal.jobs.Semaphore) at org.eclipse.core.internal.jobs.JobManager.join(JobManager.java:391) at org.eclipse.core.internal.jobs.InternalJob.join(InternalJob.java:175) at org.eclipse.core.runtime.jobs.Job.join(Job.java:286) at org.eclipse.core.internal.events.BuildManager.interrupt(BuildManager.java:309) at org.eclipse.core.internal.resources.Workspace.prepareOperation(Workspace.java:1515) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1549) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1573) at org.eclipse.jdt.internal.debug.core.hcr.JavaHotCodeReplaceManager$3.run(JavaHotCodeReplaceManager.java:1105) at java.lang.Thread.run(Thread.java:534) "Worker-40" prio=5 tid=0x03ea15a0 nid=0x34c in Object.wait() [47cf000..47cfd94] at java.lang.Object.wait(Native Method) - waiting on <0x100bb150> (a org.eclipse.core.internal.jobs.Semaphore) at org.eclipse.core.internal.jobs.Semaphore.acquire(Semaphore.java:36) - locked <0x100bb150> (a org.eclipse.core.internal.jobs.Semaphore) at org.eclipse.core.internal.jobs.OrderedLock.doAcquire(OrderedLock.java:153) at org.eclipse.core.internal.jobs.OrderedLock.acquire(OrderedLock.java:98) at org.eclipse.core.internal.jobs.OrderedLock.acquire(OrderedLock.java:74) at org.eclipse.core.internal.resources.WorkManager.checkIn(WorkManager.java:109) at org.eclipse.core.internal.resources.Workspace.prepareOperation(Workspace.java:1516) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1549) at org.eclipse.core.internal.events.NotificationManager$NotifyJob.run(NotificationManager.java:37) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:62) "Worker-39" prio=5 tid=0x03edcc88 nid=0xee8 in Object.wait() [473f000..473fd94] at java.lang.Object.wait(Native Method) - waiting on <0x11c36c78> (a org.eclipse.core.internal.jobs.WorkerPool) at org.eclipse.core.internal.jobs.WorkerPool.sleep(WorkerPool.java:189) - locked <0x11c36c78> (a org.eclipse.core.internal.jobs.WorkerPool) at org.eclipse.core.internal.jobs.WorkerPool.startJob(WorkerPool.java:215) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) "Worker-38" prio=5 tid=0x03e2b300 nid=0x948 waiting on condition [388f000..388fd94] at java.lang.Thread.sleep(Native Method) at org.eclipse.ui.internal.progress.AnimationManager.animateLoop(AnimationManager.java:318) at org.eclipse.ui.internal.progress.AnimationManager$3.run(AnimationManager.java:467) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:62) "Worker-31" prio=5 tid=0x03e2d448 nid=0x1a0 waiting for monitor entry [454f000..454fd94] at org.eclipse.jdt.internal.ui.javaeditor.filebuffers.CompilationUnitDocumentProvider2$CompilationUnitAnnotationModel.update(CompilationUnitDocumentProvider2.java:413) - waiting to lock <0x122bf510> (a org.eclipse.jdt.internal.core.CompilationUnit) at org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel$ResourceChangeListener.resourceChanged(ResourceMarkerAnnotationModel.java:53) at org.eclipse.core.internal.events.NotificationManager$2.run(NotificationManager.java:251) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:1127) at org.eclipse.core.runtime.Platform.run(Platform.java:464) at org.eclipse.core.internal.events.NotificationManager.notify(NotificationManager.java:244) at org.eclipse.core.internal.events.NotificationManager.broadcastChanges(NotificationManager.java:138) at org.eclipse.core.internal.resources.Workspace.broadcastChanges(Workspace.java:146) at org.eclipse.core.internal.resources.Workspace.endOperation(Workspace.java:847) at org.eclipse.core.internal.resources.File.setContents(File.java:283) at org.eclipse.core.internal.resources.File.setContents(File.java:323) at org.eclipse.jdt.internal.core.builder.IncrementalImageBuilder.writeClassFileBytes(IncrementalImageBuilder.java:581) at org.eclipse.jdt.internal.core.builder.AbstractImageBuilder.writeClassFile(AbstractImageBuilder.java:445) at org.eclipse.jdt.internal.core.builder.AbstractImageBuilder.acceptResult(AbstractImageBuilder.java:117) at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:340) at org.eclipse.jdt.internal.core.builder.AbstractImageBuilder.compile(AbstractImageBuilder.java:205) at org.eclipse.jdt.internal.core.builder.AbstractImageBuilder.compile(AbstractImageBuilder.java:155) at org.eclipse.jdt.internal.core.builder.IncrementalImageBuilder.build(IncrementalImageBuilder.java:113) at org.eclipse.jdt.internal.core.builder.JavaBuilder.buildDeltas(JavaBuilder.java:223) at org.eclipse.jdt.internal.core.builder.JavaBuilder.build(JavaBuilder.java:151) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:482) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:1127) at org.eclipse.core.runtime.Platform.run(Platform.java:464) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:130) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:201) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:156) at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:182) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:1127) at org.eclipse.core.runtime.Platform.run(Platform.java:464) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:185) at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:219) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:247) at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:76) at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:109) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:62) "Thread timer" prio=7 tid=0x03e9fdc0 nid=0xb78 waiting on condition [4a1f000..4a1fd94] at java.lang.Thread.sleep(Native Method) at org.eclipse.debug.internal.ui.views.launch.LaunchViewEventHandler$ThreadTimer.checkTimers(LaunchViewEventHandler.java:435) at org.eclipse.debug.internal.ui.views.launch.LaunchViewEventHandler$ThreadTimer.access$2(LaunchViewEventHandler.java:402) at org.eclipse.debug.internal.ui.views.launch.LaunchViewEventHandler$1.run(LaunchViewEventHandler.java:394) at java.lang.Thread.run(Thread.java:534) "org.eclipse.jdt.debug: JDI Event Dispatcher" prio=5 tid=0x03e2c7a0 nid=0xbe4 in Object.wait() [4b1f000..4b1fd94] at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:429) at org.eclipse.jdi.internal.connect.PacketReceiveManager.waitForPacketAvailable(PacketReceiveManager.java:168) at org.eclipse.jdi.internal.connect.PacketReceiveManager.getCommand(PacketReceiveManager.java:93) - locked <0x157c8c88> (a org.eclipse.jdi.internal.connect.PacketReceiveManager) at org.eclipse.jdi.internal.MirrorImpl.getCommandVM(MirrorImpl.java:276) at org.eclipse.jdi.internal.event.EventQueueImpl.remove(EventQueueImpl.java:63) at org.eclipse.jdi.internal.event.EventQueueImpl.remove(EventQueueImpl.java:48) at org.eclipse.jdt.internal.debug.core.EventDispatcher.run(EventDispatcher.java:206) at java.lang.Thread.run(Thread.java:534) "Packet Send Manager" prio=5 tid=0x03e2a9a0 nid=0xbd8 in Object.wait() [4a9f000..4a9fd94] at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:429) at org.eclipse.jdi.internal.connect.PacketSendManager.sendAvailablePackets(PacketSendManager.java:94) - locked <0x157c8dd0> (a org.eclipse.jdi.internal.connect.PacketSendManager) at org.eclipse.jdi.internal.connect.PacketSendManager.run(PacketSendManager.java:54) at java.lang.Thread.run(Thread.java:534) "Packet Receive Manager" prio=5 tid=0x03e66118 nid=0x310 runnable [4a5f000..4a5fd94] at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(SocketInputStream.java:129) at java.net.SocketInputStream.read(SocketInputStream.java:182) at java.io.DataInputStream.readInt(DataInputStream.java:443) at org.eclipse.jdi.internal.jdwp.JdwpPacket.read(JdwpPacket.java:124) at org.eclipse.jdi.internal.connect.PacketReceiveManager.readAvailablePacket(PacketReceiveManager.java:224) at org.eclipse.jdi.internal.connect.PacketReceiveManager.run(PacketReceiveManager.java:70) at java.lang.Thread.run(Thread.java:534) "Console Polling Thread" prio=7 tid=0x03e66498 nid=0x888 waiting on condition [49df000..49dfd94] at java.lang.Thread.sleep(Native Method) at org.eclipse.debug.internal.ui.views.console.ConsoleDocumentPartitioner.pollAndSleep(ConsoleDocumentPartitioner.java:563) at org.eclipse.debug.internal.ui.views.console.ConsoleDocumentPartitioner$1.run(ConsoleDocumentPartitioner.java:547) at java.lang.Thread.run(Thread.java:534) "Input Stream Monitor" prio=5 tid=0x035c7d48 nid=0xbc4 in Object.wait() [499f000..499fd94] at java.lang.Object.wait(Native Method) - waiting on <0x157b1538> (a java.lang.Object) at java.lang.Object.wait(Object.java:429) at org.eclipse.debug.internal.core.InputStreamMonitor.writeNext(InputStreamMonitor.java:124) - locked <0x157b1538> (a java.lang.Object) at org.eclipse.debug.internal.core.InputStreamMonitor.write(InputStreamMonitor.java:99) at org.eclipse.debug.internal.core.InputStreamMonitor$1.run(InputStreamMonitor.java:75) at java.lang.Thread.run(Thread.java:534) "Output Stream Monitor" prio=5 tid=0x03e8bee8 nid=0xe44 runnable [495f000..495fd94] at java.io.FileInputStream.readBytes(Native Method) at java.io.FileInputStream.read(FileInputStream.java:177) at org.eclipse.debug.internal.core.OutputStreamMonitor.read(OutputStreamMonitor.java:132) at org.eclipse.debug.internal.core.OutputStreamMonitor.access$1(OutputStreamMonitor.java:124) at org.eclipse.debug.internal.core.OutputStreamMonitor$1.run(OutputStreamMonitor.java:177) at java.lang.Thread.run(Thread.java:534) "Output Stream Monitor" prio=5 tid=0x03edc728 nid=0xba8 runnable [491f000..491fd94] at java.io.FileInputStream.readBytes(Native Method) at java.io.FileInputStream.read(FileInputStream.java:194) at java.io.BufferedInputStream.read1(BufferedInputStream.java:220) at java.io.BufferedInputStream.read(BufferedInputStream.java:277) - locked <0x157b0a30> (a java.io.BufferedInputStream) at java.io.FilterInputStream.read(FilterInputStream.java:90) at org.eclipse.debug.internal.core.OutputStreamMonitor.read(OutputStreamMonitor.java:132) at org.eclipse.debug.internal.core.OutputStreamMonitor.access$1(OutputStreamMonitor.java:124) at org.eclipse.debug.internal.core.OutputStreamMonitor$1.run(OutputStreamMonitor.java:177) at java.lang.Thread.run(Thread.java:534) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x03e8c848 nid=0xbe8 in Object.wait() [48cf000..48cfd94] at java.lang.Object.wait(Native Method) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:161) - locked <0x15456b28> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x034f0470 nid=0x890 in Object.wait() [478f000..478fd94] at java.lang.Object.wait(Native Method) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:161) - locked <0x15456b88> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x03e666a8 nid=0xff4 in Object.wait() [463f000..463fd94] at java.lang.Object.wait(Native Method) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:161) - locked <0x15456d18> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x03de28d8 nid=0xbe0 in Object.wait() [458f000..458fd94] at java.lang.Object.wait(Native Method) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:161) - locked <0x153dd118> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x03d86648 nid=0xd1c in Object.wait() [45ff000..45ffd94] at java.lang.Object.wait(Native Method) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:161) - locked <0x14f36df8> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x032a7620 nid=0x838 in Object.wait() [381f000..381fd94] at java.lang.Object.wait(Native Method) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:161) - locked <0x14daa2b0> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "Worker-3" prio=5 tid=0x0354d3e0 nid=0xc30 runnable [443f000..443fd94] at java.lang.Win32Process.waitFor(Native Method) at org.eclipse.debug.core.model.RuntimeProcess$ProcessMonitorJob.run(RuntimeProcess.java:347) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:62) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x03570230 nid=0x2d8 in Object.wait() [3a6f000..3a6fd94] at java.lang.Object.wait(Native Method) - waiting on <0x12c54ec8> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:161) - locked <0x12c54ec8> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x0349ef60 nid=0xfe4 in Object.wait() [38df000..38dfd94] at java.lang.Object.wait(Native Method) - waiting on <0x12ac2500> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:161) - locked <0x12ac2500> (a org.eclipse.jface.text.reconciler.DirtyRegionQueue) "Java indexing" daemon prio=4 tid=0x00a3d600 nid=0x9f0 in Object.wait() [379f000..379fd94] at java.lang.Object.wait(Native Method) - waiting on <0x121b2348> (a org.eclipse.jdt.internal.core.search.indexing.IndexManager) at java.lang.Object.wait(Object.java:429) at org.eclipse.jdt.internal.core.search.processing.JobManager.run(JobManager.java:325) - locked <0x121b2348> (a org.eclipse.jdt.internal.core.search.indexing.IndexManager) at java.lang.Thread.run(Thread.java:534) "Signal Dispatcher" daemon prio=10 tid=0x00a13e88 nid=0x954 waiting on condition [0..0] "Finalizer" daemon prio=9 tid=0x00a0f0e8 nid=0xfb0 in Object.wait() [2c6f000..2c6fd94] at java.lang.Object.wait(Native Method) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:111) - locked <0x11af0138> (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:127) at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159) "Reference Handler" daemon prio=10 tid=0x009c1a20 nid=0xfac in Object.wait() [2c2f000..2c2fd94] at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:429) at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:115) - locked <0x11af01a0> (a java.lang.ref.Reference$Lock) "main" prio=5 tid=0x000350d8 nid=0xf18 in Object.wait() [7e000..7fc3c] at java.lang.Object.wait(Native Method) - waiting on <0x16b3d468> (a org.eclipse.core.internal.jobs.Semaphore) at org.eclipse.core.internal.jobs.Semaphore.acquire(Semaphore.java:36) - locked <0x16b3d468> (a org.eclipse.core.internal.jobs.Semaphore) at org.eclipse.core.internal.jobs.JobManager.join(JobManager.java:391) at org.eclipse.core.internal.jobs.InternalJob.join(InternalJob.java:175) at org.eclipse.core.runtime.jobs.Job.join(Job.java:286) at org.eclipse.core.internal.events.BuildManager.interrupt(BuildManager.java:309) at org.eclipse.core.internal.resources.Workspace.prepareOperation(Workspace.java:1515) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1549) at org.eclipse.ui.actions.WorkspaceModifyOperation.run(WorkspaceModifyOperation.java:105) - locked <0x16b3d4b8> (a org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation) at org.eclipse.ui.editors.text.WorkspaceOperationRunner.run(WorkspaceOperationRunner.java:72) at org.eclipse.ui.editors.text.WorkspaceOperationRunner.run(WorkspaceOperationRunner.java:62) at org.eclipse.ui.editors.text.TextFileDocumentProvider.executeOperation(TextFileDocumentProvider.java:388) at org.eclipse.ui.editors.text.TextFileDocumentProvider.saveDocument(TextFileDocumentProvider.java:597) at org.eclipse.ui.texteditor.AbstractTextEditor.performSave(AbstractTextEditor.java:3140) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.performSave(CompilationUnitEditor.java:821) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.doSave(CompilationUnitEditor.java:885) - locked <0x122bf510> (a org.eclipse.jdt.internal.core.CompilationUnit) at org.eclipse.ui.internal.EditorManager$10.run(EditorManager.java:1080) at org.eclipse.ui.internal.EditorManager$8.run(EditorManager.java:936) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:302) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jface.window.ApplicationWindow$1.run(ApplicationWindow.java:444) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.jface.window.ApplicationWindow.run(ApplicationWindow.java:441) at org.eclipse.ui.internal.WorkbenchWindow.run(WorkbenchWindow.java:1458) at org.eclipse.ui.internal.EditorManager.runProgressMonitorOperation(EditorManager.java:942) at org.eclipse.ui.internal.EditorManager.savePart(EditorManager.java:1085) at org.eclipse.ui.internal.WorkbenchPage.savePart(WorkbenchPage.java:2267) at org.eclipse.ui.internal.WorkbenchPage.saveEditor(WorkbenchPage.java:2279) at org.eclipse.ui.internal.SaveAction.run(SaveAction.java:72) 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:466) 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:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1413) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1389) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:236) 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: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) "VM Thread" prio=5 tid=0x009bd970 nid=0xf9c runnable "VM Periodic Task Thread" prio=10 tid=0x00a10498 nid=0xfe8 waiting on condition "Suspend Checker Thread" prio=10 tid=0x00a02540 nid=0x960 runnable
|
resolved fixed
|
225900c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-20T11:44:21Z | 2003-11-18T21:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/filebuffers/CompilationUnitDocumentProvider2.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.filebuffers;
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.jobs.ISchedulingRule;
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.Assert;
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.ui.editors.text.TextFileDocumentProvider;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
import org.eclipse.ui.texteditor.DefaultAnnotation;
import org.eclipse.ui.texteditor.IAnnotationExtension;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel;
import org.eclipse.jdt.core.ICompilationUnit;
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.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitAnnotationModelEvent;
import org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider;
import org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation;
import org.eclipse.jdt.internal.ui.javaeditor.ISavePolicy;
import org.eclipse.jdt.internal.ui.javaeditor.JavaMarkerAnnotation;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
import org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension;
public class CompilationUnitDocumentProvider2 extends TextFileDocumentProvider implements ICompilationUnitDocumentProvider {
/**
* Bundle of all required informations to allow working copy management.
*/
static protected class CompilationUnitInfo extends FileInfo {
public ICompilationUnit fCopy;
}
/**
* Annotation representating an <code>IProblem</code>.
*/
static protected class ProblemAnnotation extends Annotation implements IJavaAnnotation, IAnnotationExtension {
private static final String TASK_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.task"; //$NON-NLS-1$
private static final String ERROR_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.error"; //$NON-NLS-1$
private static final String WARNING_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.warning"; //$NON-NLS-1$
private static final String INFO_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.info"; //$NON-NLS-1$
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;
private String fType;
public ProblemAnnotation(IProblem problem, ICompilationUnit cu) {
fProblem= problem;
fCompilationUnit= cu;
if (IProblem.Task == fProblem.getID()) {
fType= TASK_ANNOTATION_TYPE;
setLayer(DefaultAnnotation.TASK_LAYER + 1);
} else if (fProblem.isWarning()) {
fType= WARNING_ANNOTATION_TYPE;
setLayer(DefaultAnnotation.WARNING_LAYER + 1);
} else if (fProblem.isError()) {
fType= ERROR_ANNOTATION_TYPE;
setLayer(DefaultAnnotation.ERROR_LAYER + 1);
} else {
fType= 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 (ERROR_ANNOTATION_TYPE.equals(fType))
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 getMessage() {
return fProblem.getMessage();
}
/*
* @see IJavaAnnotation#isTemporary()
*/
public boolean isTemporary() {
return true;
}
/*
* @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() {
return WARNING_ANNOTATION_TYPE.equals(fType) || ERROR_ANNOTATION_TYPE.equals(fType);
}
/*
* @see IJavaAnnotation#isRelevant()
*/
public boolean isRelevant() {
return true;
}
/*
* @see IJavaAnnotation#hasOverlay()
*/
public boolean hasOverlay() {
return false;
}
/*
* @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;
}
public String getAnnotationType() {
return fType;
}
/*
* @see IAnnotationExtension#getMarkerType()
*/
public String getMarkerType() {
if (isProblem() || INFO_ANNOTATION_TYPE.equals(fType))
return IMarker.PROBLEM;
else
return IMarker.TASK;
}
/*
* @see IAnnotationExtension#getSeverity()
*/
public int getSeverity() {
if (ERROR_ANNOTATION_TYPE.equals(fType))
return IMarker.SEVERITY_ERROR;
if (WARNING_ANNOTATION_TYPE.equals(fType))
return IMarker.SEVERITY_WARNING;
return IMarker.SEVERITY_INFO;
}
/*
* @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 static class CompilationUnitAnnotationModel extends ResourceMarkerAnnotationModel implements IProblemRequestor, IProblemRequestorExtension {
private ICompilationUnit fCompilationUnit;
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 CompilationUnitAnnotationModelEvent fCurrentEvent;
private boolean fIncludesProblemAnnotationChanges= false;
public CompilationUnitAnnotationModel(IResource resource) {
super(resource);
fCurrentEvent= new CompilationUnitAnnotationModelEvent(this, getResource());
}
public void setCompilationUnit(ICompilationUnit unit) {
fCompilationUnit= unit;
}
protected MarkerAnnotation createMarkerAnnotation(IMarker marker) {
return new JavaMarkerAnnotation(marker);
}
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 {
if (fCompilationUnit != null) {
synchronized (fCompilationUnit) {
fCompilationUnit.reconcile(true, null);
}
}
} catch (JavaModelException ex) {
if (!ex.isDoesNotExist())
handleCoreException(ex, ex.getMessage());
}
}
}
/*
* @see IProblemRequestor#beginReporting()
*/
public void beginReporting() {
if (fCompilationUnit != null && fCompilationUnit.getJavaProject().isOnClasspath(fCompilationUnit))
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) {
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, fCompilationUnit);
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 AnnotationModel#fireModelChanged()
*/
protected void fireModelChanged() {
fireModelChanged(fCurrentEvent);
fIncludesProblemAnnotationChanges= fCurrentEvent.includesProblemMarkerAnnotationChanges();
fCurrentEvent= new CompilationUnitAnnotationModelEvent(this, getResource());
}
/*
* @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);
fCurrentEvent.annotationAdded(annotation);
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) {
for (Iterator iter= getAnnotationIterator(); iter.hasNext();) {
fCurrentEvent.annotationRemoved((Annotation) iter.next());
}
super.removeAllAnnotations(fireModelChanged);
fReverseMap.clear();
}
/*
* @see AnnotationModel#removeAnnotation(Annotation, boolean)
*/
protected void removeAnnotation(Annotation annotation, boolean fireModelChanged) {
fCurrentEvent.annotationRemoved(annotation);
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 CompilationUnitDocumentProvider2() {
setParentDocumentProvider(new TextFileDocumentProvider(new JavaStorageDocumentProvider()));
fGlobalAnnotationModelListener= new GlobalAnnotationModelListener();
fPropertyListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty()))
enableHandlingTemporaryProblems();
}
};
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 org.eclipse.ui.editors.text.TextFileDocumentProvider#createEmptyFileInfo()
*/
protected FileInfo createEmptyFileInfo() {
return new CompilationUnitInfo();
}
/*
* @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createAnnotationModel(org.eclipse.core.resources.IFile)
*/
protected IAnnotationModel createAnnotationModel(IFile file) {
return new CompilationUnitAnnotationModel(file);
}
/*
* @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createFileInfo(java.lang.Object)
*/
protected FileInfo createFileInfo(Object element) throws CoreException {
if (!(element instanceof IFileEditorInput))
return null;
IFileEditorInput input= (IFileEditorInput) element;
ICompilationUnit original= createCompilationUnit(input.getFile());
if (original == null)
return null;
FileInfo info= super.createFileInfo(element);
if (!(info instanceof CompilationUnitInfo))
return null;
CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
IProblemRequestor requestor= cuInfo.fModel instanceof IProblemRequestor ? (IProblemRequestor) cuInfo.fModel : null;
if (JavaPlugin.USE_WORKING_COPY_OWNERS) {
original.becomeWorkingCopy(requestor, getProgressMonitor());
cuInfo.fCopy= original;
} else {
cuInfo.fCopy= (ICompilationUnit) original.getSharedWorkingCopy(getProgressMonitor(), JavaPlugin.getDefault().getBufferFactory(), requestor);
}
if (cuInfo.fModel instanceof CompilationUnitAnnotationModel) {
CompilationUnitAnnotationModel model= (CompilationUnitAnnotationModel) cuInfo.fModel;
model.setCompilationUnit(cuInfo.fCopy);
}
if (cuInfo.fModel != null)
cuInfo.fModel.addAnnotationModelListener(fGlobalAnnotationModelListener);
if (requestor instanceof IProblemRequestorExtension) {
IProblemRequestorExtension extension= (IProblemRequestorExtension) requestor;
extension.setIsActive(isHandlingTemporaryProblems());
}
return cuInfo;
}
/*
* @see org.eclipse.ui.editors.text.TextFileDocumentProvider#disposeFileInfo(java.lang.Object, org.eclipse.ui.editors.text.TextFileDocumentProvider.FileInfo)
*/
protected void disposeFileInfo(Object element, FileInfo 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();
}
if (cuInfo.fModel != null)
cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener);
}
super.disposeFileInfo(element, info);
}
protected void commitWorkingCopy(IProgressMonitor monitor, Object element, CompilationUnitInfo info, boolean overwrite) throws CoreException {
synchronized (info.fCopy) {
info.fCopy.reconcile();
}
IDocument document= info.fTextFileBuffer.getDocument();
ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement();
IResource resource= original.getResource();
Assert.isTrue(resource instanceof IFile);
if (!resource.exists()) {
// underlying resource has been deleted, just recreate file, ignore the rest
createFileFromDocument(monitor, (IFile) resource, document);
return;
}
if (fSavePolicy != null)
fSavePolicy.preSave(info.fCopy);
try {
fIsAboutToSave= true;
// commit working copy
if (JavaPlugin.USE_WORKING_COPY_OWNERS) {
info.fCopy.commitWorkingCopy(overwrite, monitor);
} else {
info.fCopy.commit(overwrite, monitor);
// next call required as commiting working copies changed to no longer walk through the right buffer
saveDocumentContent(monitor, element, document, overwrite);
}
} 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.
if (info.fModel instanceof AbstractMarkerAnnotationModel) {
AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel;
model.updateMarkers(document);
}
if (fSavePolicy != null) {
ICompilationUnit unit= fSavePolicy.postSave(original);
if (unit != null && info.fModel instanceof AbstractMarkerAnnotationModel) {
IResource r= unit.getResource();
IMarker[] markers= r.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO);
if (markers != null && markers.length > 0) {
AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel;
for (int i= 0; i < markers.length; i++)
model.updateMarker(markers[i], document, null);
}
}
}
}
/*
* @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createSaveOperation(java.lang.Object, org.eclipse.jface.text.IDocument, boolean)
*/
protected DocumentProviderOperation createSaveOperation(final Object element, final IDocument document, final boolean overwrite) throws CoreException {
final FileInfo info= getFileInfo(element);
if (info instanceof CompilationUnitInfo) {
return new DocumentProviderOperation() {
protected void execute(IProgressMonitor monitor) throws CoreException {
commitWorkingCopy(monitor, element, (CompilationUnitInfo) info, overwrite);
}
/*
* @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule()
*/
public ISchedulingRule getSchedulingRule() {
if (info.fElement instanceof IFileEditorInput)
// FIXME: waiting for J Core to support scheduling rules (see bug 46332)
// return ((IFileEditorInput)info.fElement).getFile().getParent();
return ResourcesPlugin.getWorkspace().getRoot();
else
return null;
}
};
}
return null;
}
/**
* 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= getFileInfosIterator(); iter.hasNext();) {
FileInfo info= (FileInfo) iter.next();
if (info.fModel instanceof IProblemRequestorExtension) {
IProblemRequestorExtension extension= (IProblemRequestorExtension) info.fModel;
extension.setIsActive(enable);
}
}
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#setSavePolicy(org.eclipse.jdt.internal.ui.javaeditor.ISavePolicy)
*/
public void setSavePolicy(ISavePolicy savePolicy) {
fSavePolicy= savePolicy;
}
/*
* @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) {
FileInfo fileInfo= getFileInfo(element);
if (fileInfo instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo) fileInfo;
return info.fCopy;
}
return null;
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#shutdown()
*/
public void shutdown() {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyListener);
Iterator e= getConnectedElementsIterator();
while (e.hasNext())
disconnect(e.next());
}
/*
* @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;
super.saveDocument(monitor, element, document, overwrite);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#createLineTracker(java.lang.Object)
*/
public ILineTracker createLineTracker(Object element) {
return new DefaultLineTracker();
}
}
|
46,946 |
Bug 46946 quick type hiearchy: affordance caption is swapped [type hierarchy]
|
I20031119 (M5 test pass) 1. Open ContextBasedFormattingStrategy.java (or another type of your liking) 2. Press Ctrl+T to open the type hierarchy 3. Repeatedly pressing Ctrl+T toggles between super- and subtype hierarchy -> The caption of the affordance shown at the bottom needs to be swapped Right now, when displaying the supertype hierarchy, it reads "Press Ctrl+T to display the supertype hierarchy".
|
resolved fixed
|
2df2bf9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-20T16:17:35Z | 2003-11-19T11: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 class HierarchyInformationControlLabelProvider extends HierarchyLabelProvider {
public HierarchyInformationControlLabelProvider(TypeHierarchyLifeCycle lifeCycle) {
super(lifeCycle);
}
protected boolean isDifferentScope(IType type) {
if (fFocus == null) {
return super.isDifferentScope(type);
}
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 false;
}
}
} catch (JavaModelException e) {
// ignore
JavaPlugin.log(e);
}
}
return true;
}
}
private TypeHierarchyLifeCycle fLifeCycle;
private HierarchyInformationControlLabelProvider 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 HierarchyInformationControlLabelProvider(fLifeCycle);
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;
}
/* (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();
}
fStatusTextLabel.setText(getInfoLabel());
fOtherContentProvider= contentProvider;
fOtherExpandedElements= expandedElements;
}
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);
}
}
|
45,187 |
Bug 45187 Double clicking in Package Explorer highlights class name [package explorer]
|
Rurn on "Show members in Package Explorer" Using EclipsePlugin as an example class name, when double clicking on a method in that class, like getDefault, getDefault is selected in the editor, but the highlight in the package explorer jumps to EclipsePlugin instead of remaining on getDefault. This is the behavior if "Link with editor" is turned on. If it is turned off, the highlight doesn't jump.
|
resolved fixed
|
dca60a3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-21T23:06:49Z | 2003-10-20T03:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerPart.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.packageview;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IOpenListener;
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.ITreeContentProvider;
import org.eclipse.jface.viewers.ITreeViewerListener;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeExpansionEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.part.ISetSelectionTarget;
import org.eclipse.ui.part.IShowInSource;
import org.eclipse.ui.part.IShowInTarget;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.part.ResourceTransfer;
import org.eclipse.ui.part.ShowInContext;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.JdtViewerDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.ResourceTransferDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.filters.OutputFolderFilter;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.FilterUpdater;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
import org.eclipse.jdt.ui.IPackagesViewPart;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
/**
* The ViewPart for the ProjectExplorer. It listens to part activation events.
* When selection linking with the editor is enabled the view selection tracks
* the active editor page. Similarly when a resource is selected in the packages
* view the corresponding editor is activated.
*/
public class PackageExplorerPart extends ViewPart
implements ISetSelectionTarget, IMenuListener,
IShowInTarget,
IPackagesViewPart, IPropertyChangeListener,
IViewPartInputProvider {
private boolean fIsCurrentLayoutFlat; // true means flat, false means hierachical
private static final int HIERARCHICAL_LAYOUT= 0x1;
private static final int FLAT_LAYOUT= 0x2;
public final static String VIEW_ID= JavaUI.ID_PACKAGES;
// Persistance tags.
static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
static final String TAG_EXPANDED= "expanded"; //$NON-NLS-1$
static final String TAG_ELEMENT= "element"; //$NON-NLS-1$
static final String TAG_PATH= "path"; //$NON-NLS-1$
static final String TAG_VERTICAL_POSITION= "verticalPosition"; //$NON-NLS-1$
static final String TAG_HORIZONTAL_POSITION= "horizontalPosition"; //$NON-NLS-1$
static final String TAG_FILTERS = "filters"; //$NON-NLS-1$
static final String TAG_FILTER = "filter"; //$NON-NLS-1$
static final String TAG_LAYOUT= "layout"; //$NON-NLS-1$
private PackageExplorerContentProvider fContentProvider;
private FilterUpdater fFilterUpdater;
private PackageExplorerActionGroup fActionSet;
private ProblemTreeViewer fViewer;
private Menu fContextMenu;
private IMemento fMemento;
private ISelectionChangedListener fSelectionListener;
private String fWorkingSetName;
private IPartListener fPartListener= new IPartListener() {
public void partActivated(IWorkbenchPart part) {
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partBroughtToTop(IWorkbenchPart part) {
}
public void partClosed(IWorkbenchPart part) {
}
public void partDeactivated(IWorkbenchPart part) {
}
public void partOpened(IWorkbenchPart part) {
}
};
private ITreeViewerListener fExpansionListener= new ITreeViewerListener() {
public void treeCollapsed(TreeExpansionEvent event) {
}
public void treeExpanded(TreeExpansionEvent event) {
Object element= event.getElement();
if (element instanceof ICompilationUnit ||
element instanceof IClassFile)
expandMainType(element);
}
};
private PackageExplorerLabelProvider fLabelProvider;
/* (non-Javadoc)
* Method declared on IViewPart.
*/
private boolean fLinkingEnabled;
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
restoreLayoutState(memento);
}
private void restoreLayoutState(IMemento memento) {
Integer state= null;
if (memento != null)
state= memento.getInteger(TAG_LAYOUT);
// If no memento try an restore from preference store
if(state == null) {
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
state= new Integer(store.getInt(TAG_LAYOUT));
}
if (state.intValue() == FLAT_LAYOUT)
fIsCurrentLayoutFlat= true;
else if (state.intValue() == HIERARCHICAL_LAYOUT)
fIsCurrentLayoutFlat= false;
else
fIsCurrentLayoutFlat= true;
}
/**
* Returns the package explorer part of the active perspective. If
* there isn't any package explorer part <code>null</code> is returned.
*/
public static PackageExplorerPart getFromActivePerspective() {
IWorkbenchPage activePage= JavaPlugin.getActivePage();
if (activePage == null)
return null;
IViewPart view= activePage.findView(VIEW_ID);
if (view instanceof PackageExplorerPart)
return (PackageExplorerPart)view;
return null;
}
/**
* Makes the package explorer part visible in the active perspective. If there
* isn't a package explorer part registered <code>null</code> is returned.
* Otherwise the opened view part is returned.
*/
public static PackageExplorerPart openInActivePerspective() {
try {
return (PackageExplorerPart)JavaPlugin.getActivePage().showView(VIEW_ID);
} catch(PartInitException pe) {
return null;
}
}
public void dispose() {
if (fContextMenu != null && !fContextMenu.isDisposed())
fContextMenu.dispose();
getSite().getPage().removePartListener(fPartListener);
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
if (fViewer != null)
fViewer.removeTreeListener(fExpansionListener);
if (fActionSet != null)
fActionSet.dispose();
if (fFilterUpdater != null)
ResourcesPlugin.getWorkspace().removeResourceChangeListener(fFilterUpdater);
super.dispose();
}
/**
* Implementation of IWorkbenchPart.createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
fViewer= createViewer(parent);
fViewer.setUseHashlookup(true);
if (!JavaPlugin.USE_WORKING_COPY_OWNERS) {
fViewer.setComparer(new PackageExplorerElementComparer());
}
initDragAndDrop();
setProviders();
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
fContextMenu= menuMgr.createContextMenu(fViewer.getTree());
fViewer.getTree().setMenu(fContextMenu);
// Register viewer with site. This must be done before making the actions.
IWorkbenchPartSite site= getSite();
site.registerContextMenu(menuMgr, fViewer);
site.setSelectionProvider(fViewer);
site.getPage().addPartListener(fPartListener);
if (fMemento != null) {
restoreLinkingEnabled(fMemento);
}
makeActions(); // call before registering for selection changes
// Set input after filter and sorter has been set. This avoids resorting and refiltering.
restoreFilterAndSorter();
fViewer.setInput(findInputElement());
initFrameActions();
initKeyListener();
fSelectionListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
handleSelectionChanged(event);
}
};
fViewer.addPostSelectionChangedListener(fSelectionListener);
fViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
fActionSet.handleDoubleClick(event);
}
});
fViewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
fActionSet.handleOpen(event);
}
});
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager));
fViewer.addTreeListener(fExpansionListener);
if (fMemento != null)
restoreUIState(fMemento);
fMemento= null;
// Set help for the view
JavaUIHelp.setHelp(fViewer, IJavaHelpContextIds.PACKAGES_VIEW);
fillActionBars();
updateTitle();
fFilterUpdater= new FilterUpdater(fViewer);
ResourcesPlugin.getWorkspace().addResourceChangeListener(fFilterUpdater);
}
private void initFrameActions() {
fActionSet.getUpAction().update();
fActionSet.getBackAction().update();
fActionSet.getForwardAction().update();
}
/**
* This viewer ensures that non-leaves in the hierarchical
* layout are not removed by any filters.
*
* @since 2.1
*/
private ProblemTreeViewer createViewer(Composite composite) {
return new ProblemTreeViewer(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL) {
/*
* @see org.eclipse.jface.viewers.StructuredViewer#filter(java.lang.Object)
*/
protected Object[] getFilteredChildren(Object parent) {
List list = new ArrayList();
ViewerFilter[] filters = fViewer.getFilters();
Object[] children = ((ITreeContentProvider) fViewer.getContentProvider()).getChildren(parent);
for (int i = 0; i < children.length; i++) {
Object object = children[i];
if (!isEssential(object)) {
object = filter(object, parent, filters);
if (object != null) {
list.add(object);
}
} else
list.add(object);
}
return list.toArray();
}
// Sends the object through the given filters
private Object filter(Object object, Object parent, ViewerFilter[] filters) {
for (int i = 0; i < filters.length; i++) {
ViewerFilter filter = filters[i];
if (!filter.select(fViewer, parent, object))
return null;
}
return object;
}
/* Checks if a filtered object in essential (ie. is a parent that
* should not be removed).
*/
private boolean isEssential(Object object) {
try {
if (!isFlatLayout() && object instanceof IPackageFragment) {
IPackageFragment fragment = (IPackageFragment) object;
return !fragment.isDefaultPackage() && fragment.hasSubpackages();
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return false;
}
protected void handleInvalidSelection(ISelection invalidSelection, ISelection newSelection) {
IStructuredSelection is= (IStructuredSelection)invalidSelection;
List ns= null;
if (newSelection instanceof IStructuredSelection) {
ns= new ArrayList(((IStructuredSelection)newSelection).toList());
} else {
ns= new ArrayList();
}
boolean changed= false;
for (Iterator iter= is.iterator(); iter.hasNext();) {
Object element= iter.next();
if (element instanceof IJavaProject) {
IProject project= ((IJavaProject)element).getProject();
if (!project.isOpen()) {
ns.add(project);
changed= true;
}
} else if (element instanceof IProject) {
IProject project= (IProject)element;
if (project.isOpen()) {
IJavaProject jProject= JavaCore.create(project);
if (jProject != null && jProject.exists())
ns.add(jProject);
changed= true;
}
}
}
if (changed) {
newSelection= new StructuredSelection(ns);
setSelection(newSelection);
}
super.handleInvalidSelection(invalidSelection, newSelection);
}
};
}
/**
* Answers whether this part shows the packages flat or hierarchical.
*
* @since 2.1
*/
boolean isFlatLayout() {
return fIsCurrentLayoutFlat;
}
private void setProviders() {
//content provider must be set before the label provider
fContentProvider= createContentProvider();
fContentProvider.setIsFlatLayout(fIsCurrentLayoutFlat);
fViewer.setContentProvider(fContentProvider);
fLabelProvider= createLabelProvider();
fLabelProvider.setIsFlatLayout(fIsCurrentLayoutFlat);
fViewer.setLabelProvider(new DecoratingJavaLabelProvider(fLabelProvider, false, false));
// problem decoration provided by PackageLabelProvider
}
void toggleLayout() {
// Update current state and inform content and label providers
fIsCurrentLayoutFlat= !fIsCurrentLayoutFlat;
saveLayoutState(null);
fContentProvider.setIsFlatLayout(isFlatLayout());
fLabelProvider.setIsFlatLayout(isFlatLayout());
fViewer.getControl().setRedraw(false);
fViewer.refresh();
fViewer.getControl().setRedraw(true);
}
/**
* This method should only be called inside this class
* and from test cases.
*/
public PackageExplorerContentProvider createContentProvider() {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
boolean showCUChildren= store.getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
boolean reconcile= PreferenceConstants.UPDATE_WHILE_EDITING.equals(store.getString(PreferenceConstants.UPDATE_JAVA_VIEWS));
return new PackageExplorerContentProvider(this, showCUChildren, reconcile);
}
private PackageExplorerLabelProvider createLabelProvider() {
return new PackageExplorerLabelProvider(AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.P_COMPRESSED,
AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS,
fContentProvider);
}
private void fillActionBars() {
IActionBars actionBars= getViewSite().getActionBars();
fActionSet.fillActionBars(actionBars);
}
private Object findInputElement() {
Object input= getSite().getPage().getInput();
if (input instanceof IWorkspace) {
return JavaCore.create(((IWorkspace)input).getRoot());
} else if (input instanceof IContainer) {
IJavaElement element= JavaCore.create((IContainer)input);
if (element != null && element.exists())
return element;
return input;
}
//1GERPRT: ITPJUI:ALL - Packages View is empty when shown in Type Hierarchy Perspective
// we can't handle the input
// fall back to show the workspace
return JavaCore.create(JavaPlugin.getWorkspace().getRoot());
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key.equals(ISelectionProvider.class))
return fViewer;
if (key == IShowInSource.class) {
return getShowInSource();
}
if (key == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { IPageLayout.ID_RES_NAV };
}
};
}
return super.getAdapter(key);
}
/**
* Returns the tool tip text for the given element.
*/
String getToolTipText(Object element) {
String result;
if (!(element instanceof IResource)) {
if (element instanceof IJavaModel)
result= PackagesMessages.getString("PackageExplorerPart.workspace"); //$NON-NLS-1$
else
result= JavaElementLabels.getTextLabel(element, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS);
} else {
IPath path= ((IResource) element).getFullPath();
if (path.isRoot()) {
result= PackagesMessages.getString("PackageExplorer.title"); //$NON-NLS-1$
} else {
result= path.makeRelative().toString();
}
}
if (fWorkingSetName == null)
return result;
String wsstr= PackagesMessages.getFormattedString("PackageExplorer.toolTip", new String[] { fWorkingSetName }); //$NON-NLS-1$
if (result.length() == 0)
return wsstr;
return PackagesMessages.getFormattedString("PackageExplorer.toolTip2", new String[] { result, fWorkingSetName }); //$NON-NLS-1$
}
public String getTitleToolTip() {
if (fViewer == null)
return super.getTitleToolTip();
return getToolTipText(fViewer.getInput());
}
/**
* @see IWorkbenchPart#setFocus()
*/
public void setFocus() {
fViewer.getTree().setFocus();
}
/**
* Returns the current selection.
*/
private ISelection getSelection() {
return fViewer.getSelection();
}
//---- Action handling ----------------------------------------------------------
/**
* Called when the context menu is about to open. Override
* to add your own context dependent menu contributions.
*/
public void menuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
fActionSet.setContext(new ActionContext(getSelection()));
fActionSet.fillContextMenu(menu);
fActionSet.setContext(null);
}
private void makeActions() {
fActionSet= new PackageExplorerActionGroup(this);
}
//---- Event handling ----------------------------------------------------------
private void initDragAndDrop() {
initDrag();
initDrop();
}
private void initDrag() {
int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
Transfer[] transfers= new Transfer[] {
LocalSelectionTransfer.getInstance(),
ResourceTransfer.getInstance(),
FileTransfer.getInstance()};
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fViewer),
new ResourceTransferDragAdapter(fViewer),
new FileTransferDragAdapter(fViewer)
};
fViewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(fViewer, dragListeners));
}
private void initDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK | DND.DROP_DEFAULT;
Transfer[] transfers= new Transfer[] {
LocalSelectionTransfer.getInstance(),
FileTransfer.getInstance()};
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fViewer),
new FileTransferDropAdapter(fViewer)
};
fViewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
}
/**
* Handles selection changed in viewer.
* Updates global actions.
* Links to editor (if option enabled)
*/
private void handleSelectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection= (IStructuredSelection) event.getSelection();
fActionSet.handleSelectionChanged(event);
if (isLinkingEnabled())
linkToEditor(selection);
}
public void selectReveal(ISelection selection) {
selectReveal(selection, 0);
}
private void selectReveal(final ISelection selection, final int count) {
Control ctrl= getViewer().getControl();
if (ctrl == null || ctrl.isDisposed())
return;
ISelection javaSelection= convertSelection(selection);
fViewer.setSelection(javaSelection, true);
PackageExplorerContentProvider provider= (PackageExplorerContentProvider)getViewer().getContentProvider();
ISelection cs= fViewer.getSelection();
// If we have Pending changes and the element could not be selected then
// we try it again on more time by posting the select and reveal asynchronuoulsy
// to the event queue. See PR http://bugs.eclipse.org/bugs/show_bug.cgi?id=30700
// for a discussion of the underlying problem.
if (count == 0 && provider.hasPendingChanges() && !javaSelection.equals(cs)) {
ctrl.getDisplay().asyncExec(new Runnable() {
public void run() {
selectReveal(selection, count + 1);
}
});
}
}
private ISelection convertSelection(ISelection s) {
if (!(s instanceof IStructuredSelection))
return s;
Object[] elements= ((StructuredSelection)s).toArray();
if (!containsResources(elements))
return s;
for (int i= 0; i < elements.length; i++) {
Object o= elements[i];
if (!(o instanceof IJavaElement)) {
if (o instanceof IResource) {
IJavaElement jElement= JavaCore.create((IResource)o);
if (jElement != null && jElement.exists())
elements[i]= jElement;
}
else if (o instanceof IAdaptable) {
IResource r= (IResource)((IAdaptable)o).getAdapter(IResource.class);
if (r != null) {
IJavaElement jElement= JavaCore.create(r);
if (jElement != null && jElement.exists())
elements[i]= jElement;
else
elements[i]= r;
}
}
}
}
return new StructuredSelection(elements);
}
private boolean containsResources(Object[] elements) {
for (int i = 0; i < elements.length; i++) {
Object o= elements[i];
if (!(o instanceof IJavaElement)) {
if (o instanceof IResource)
return true;
if ((o instanceof IAdaptable) && ((IAdaptable)o).getAdapter(IResource.class) != null)
return true;
}
}
return false;
}
public void selectAndReveal(Object element) {
selectReveal(new StructuredSelection(element));
}
boolean isLinkingEnabled() {
return fLinkingEnabled;
}
/**
* Initializes the linking enabled setting from the preference store.
*/
private void initLinkingEnabled() {
fLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_PACKAGES_TO_EDITOR);
}
/**
* Links to editor (if option enabled)
*/
private void linkToEditor(IStructuredSelection selection) {
// ignore selection changes if the package explorer is not the active part.
// In this case the selection change isn't triggered by a user.
if (!isActivePart())
return;
Object obj= selection.getFirstElement();
if (selection.size() == 1) {
IEditorPart part= EditorUtility.isOpenInEditor(obj);
if (part != null) {
IWorkbenchPage page= getSite().getPage();
page.bringToTop(part);
if (obj instanceof IJavaElement)
EditorUtility.revealInEditor(part, (IJavaElement) obj);
}
}
}
private boolean isActivePart() {
return this == getSite().getPage().getActivePart();
}
public void saveState(IMemento memento) {
if (fViewer == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
saveExpansionState(memento);
saveSelectionState(memento);
saveLayoutState(memento);
saveLinkingEnabled(memento);
// commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676
//saveScrollState(memento, fViewer.getTree());
fActionSet.saveFilterAndSorterState(memento);
}
private void saveLinkingEnabled(IMemento memento) {
memento.putInteger(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, fLinkingEnabled ? 1 : 0);
}
/**
* Saves the current layout state.
*
* @param memento the memento to save the state into or
* <code>null</code> to store the state in the preferences
* @since 2.1
*/
private void saveLayoutState(IMemento memento) {
if (memento != null) {
memento.putInteger(TAG_LAYOUT, getLayoutAsInt());
} else {
//if memento is null save in preference store
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(TAG_LAYOUT, getLayoutAsInt());
}
}
private int getLayoutAsInt() {
if (fIsCurrentLayoutFlat)
return FLAT_LAYOUT;
else
return HIERARCHICAL_LAYOUT;
}
protected void saveScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_VERTICAL_POSITION, String.valueOf(position));
//save horizontal position
bar= tree.getHorizontalBar();
position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_HORIZONTAL_POSITION, String.valueOf(position));
}
protected void saveSelectionState(IMemento memento) {
Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray();
if (elements.length > 0) {
IMemento selectionMem= memento.createChild(TAG_SELECTION);
for (int i= 0; i < elements.length; i++) {
IMemento elementMem= selectionMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= elements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) elements[i]).getHandleIdentifier());
}
}
}
protected void saveExpansionState(IMemento memento) {
Object expandedElements[]= fViewer.getVisibleExpandedElements();
if (expandedElements.length > 0) {
IMemento expandedMem= memento.createChild(TAG_EXPANDED);
for (int i= 0; i < expandedElements.length; i++) {
IMemento elementMem= expandedMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= expandedElements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) expandedElements[i]).getHandleIdentifier());
}
}
}
private void restoreFilterAndSorter() {
fViewer.addFilter(new OutputFolderFilter());
fViewer.setSorter(new JavaElementSorter());
if (fMemento != null)
fActionSet.restoreFilterAndSorterState(fMemento);
}
private void restoreUIState(IMemento memento) {
restoreExpansionState(memento);
restoreSelectionState(memento);
// commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676
//restoreScrollState(memento, fViewer.getTree());
}
private void restoreLinkingEnabled(IMemento memento) {
Integer val= memento.getInteger(PreferenceConstants.LINK_PACKAGES_TO_EDITOR);
if (val != null) {
fLinkingEnabled= val.intValue() != 0;
}
}
protected void restoreScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_VERTICAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore, don't set scrollposition
}
}
bar= tree.getHorizontalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_HORIZONTAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore don't set scroll position
}
}
}
protected void restoreSelectionState(IMemento memento) {
IMemento childMem;
childMem= memento.getChild(TAG_SELECTION);
if (childMem != null) {
ArrayList list= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
if (element != null)
list.add(element);
}
fViewer.setSelection(new StructuredSelection(list));
}
}
protected void restoreExpansionState(IMemento memento) {
IMemento childMem= memento.getChild(TAG_EXPANDED);
if (childMem != null) {
ArrayList elements= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
if (element != null)
elements.add(element);
}
fViewer.setExpandedElements(elements.toArray());
}
}
/**
* Create the KeyListener for doing the refresh on the viewer.
*/
private void initKeyListener() {
fViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
fActionSet.handleKeyEvent(event);
}
});
}
/**
* An editor has been activated. Set the selection in this Packages Viewer
* to be the editor's input, if linking is enabled.
*/
void editorActivated(IEditorPart editor) {
if (!isLinkingEnabled())
return;
showInput(getElementOfInput(editor.getEditorInput()));
}
boolean showInput(Object input) {
Object element= null;
if (input instanceof IFile && isOnClassPath((IFile)input)) {
element= JavaCore.create((IFile)input);
}
if (element == null) // try a non Java resource
element= input;
if (element != null) {
ISelection newSelection= new StructuredSelection(element);
if (fViewer.getSelection().equals(newSelection)) {
fViewer.reveal(element);
} else {
try {
fViewer.removeSelectionChangedListener(fSelectionListener);
fViewer.setSelection(newSelection, true);
while (element != null && fViewer.getSelection().isEmpty()) {
// Try to select parent in case element is filtered
element= getParent(element);
if (element != null) {
newSelection= new StructuredSelection(element);
fViewer.setSelection(newSelection, true);
}
}
} finally {
fViewer.addSelectionChangedListener(fSelectionListener);
}
}
return true;
}
return false;
}
private boolean isOnClassPath(IFile file) {
IJavaProject jproject= JavaCore.create(file.getProject());
return jproject.isOnClasspath(file);
}
/**
* Returns the element's parent.
*
* @return the parent or <code>null</code> if there's no parent
*/
private Object getParent(Object element) {
if (element instanceof IJavaElement)
return ((IJavaElement)element).getParent();
else if (element instanceof IResource)
return ((IResource)element).getParent();
// else if (element instanceof IStorage) {
// can't get parent - see bug 22376
// }
return null;
}
/**
* A compilation unit or class was expanded, expand
* the main type.
*/
void expandMainType(Object element) {
try {
IType type= null;
if (element instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit)element;
IType[] types= cu.getTypes();
if (types.length > 0)
type= types[0];
}
else if (element instanceof IClassFile) {
IClassFile cf= (IClassFile)element;
type= cf.getType();
}
if (type != null) {
final IType type2= type;
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.getDisplay().asyncExec(new Runnable() {
public void run() {
Control ctrl2= fViewer.getControl();
if (ctrl2 != null && !ctrl2.isDisposed())
fViewer.expandToLevel(type2, 1);
}
});
}
}
} catch(JavaModelException e) {
// no reveal
}
}
/**
* Returns the element contained in the EditorInput
*/
Object getElementOfInput(IEditorInput input) {
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
else if (input instanceof IFileEditorInput)
return ((IFileEditorInput)input).getFile();
else if (input instanceof JarEntryEditorInput)
return ((JarEntryEditorInput)input).getStorage();
return null;
}
/**
* Returns the Viewer.
*/
TreeViewer getViewer() {
return fViewer;
}
/**
* Returns the TreeViewer.
*/
public TreeViewer getTreeViewer() {
return fViewer;
}
boolean isExpandable(Object element) {
if (fViewer == null)
return false;
return fViewer.isExpandable(element);
}
void setWorkingSetName(String workingSetName) {
fWorkingSetName= workingSetName;
}
/**
* Updates the title text and title tool tip.
* Called whenever the input of the viewer changes.
*/
void updateTitle() {
Object input= fViewer.getInput();
String viewName= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$
if (input == null
|| (input instanceof IJavaModel)) {
setTitle(viewName);
setTitleToolTip(""); //$NON-NLS-1$
} else {
String inputText= JavaElementLabels.getTextLabel(input, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS);
String title= PackagesMessages.getFormattedString("PackageExplorer.argTitle", new String[] { viewName, inputText }); //$NON-NLS-1$
setTitle(title);
setTitleToolTip(getToolTipText(input));
}
}
/**
* Sets the decorator for the package explorer.
*
* @param decorator a label decorator or <code>null</code> for no decorations.
* @deprecated To be removed
*/
public void setLabelDecorator(ILabelDecorator decorator) {
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (fViewer == null)
return;
boolean refreshViewer= false;
if (PreferenceConstants.SHOW_CU_CHILDREN.equals(event.getProperty())) {
fActionSet.updateActionBars(getViewSite().getActionBars());
boolean showCUChildren= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
((StandardJavaElementContentProvider)fViewer.getContentProvider()).setProvideMembers(showCUChildren);
refreshViewer= true;
} else if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
refreshViewer= true;
}
if (refreshViewer)
fViewer.refresh();
}
/* (non-Javadoc)
* @see IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
if (fViewer != null) {
return fViewer.getInput();
}
return null;
}
public void collapseAll() {
fViewer.getControl().setRedraw(false);
fViewer.collapseToLevel(getViewPartInput(), AbstractTreeViewer.ALL_LEVELS);
fViewer.getControl().setRedraw(true);
}
public PackageExplorerPart() {
initLinkingEnabled();
}
public boolean show(ShowInContext context) {
Object input= context.getInput();
if (input instanceof IEditorInput) {
Object elementOfInput= getElementOfInput((IEditorInput)context.getInput());
if (elementOfInput == null)
return false;
return showInput(elementOfInput);
}
ISelection selection= context.getSelection();
if (selection != null) {
selectReveal(selection);
return true;
}
return false;
}
/**
* Returns the <code>IShowInSource</code> for this view.
*/
protected IShowInSource getShowInSource() {
return new IShowInSource() {
public ShowInContext getShowInContext() {
return new ShowInContext(
getViewer().getInput(),
getViewer().getSelection());
}
};
}
/*
* @see org.eclipse.ui.views.navigator.IResourceNavigator#setLinkingEnabled(boolean)
* @since 2.1
*/
public void setLinkingEnabled(boolean enabled) {
fLinkingEnabled= enabled;
PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, enabled);
if (enabled) {
IEditorPart editor = getSite().getPage().getActiveEditor();
if (editor != null) {
editorActivated(editor);
}
}
}
/**
* Returns the name for the given element.
* Used as the name for the current frame.
*/
String getFrameName(Object element) {
if (element instanceof IJavaElement) {
return ((IJavaElement) element).getElementName();
} else {
return ((ILabelProvider) getTreeViewer().getLabelProvider()).getText(element);
}
}
void projectStateChanged(Object root) {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
fViewer.refresh(root, true);
// trigger a syntetic selection change so that action refresh their
// enable state.
fViewer.setSelection(fViewer.getSelection());
}
}
}
|
45,227 |
Bug 45227 Pullup incorrectly reports errors [refactoring]
|
I have a heirachy C derives from B derives from A. A contains protected member variable foo. C contains a method bar() which references foo. If I attempt to pull-up bar() to B, the refactoring preview incorrectly informs me that foo cannot be access from B. If I proceed, there are in fact no problems.
|
resolved fixed
|
fd3cd8b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T08:54:29Z | 2003-10-20T17:13:20Z |
org.eclipse.jdt.ui/core
| |
45,227 |
Bug 45227 Pullup incorrectly reports errors [refactoring]
|
I have a heirachy C derives from B derives from A. A contains protected member variable foo. C contains a method bar() which references foo. If I attempt to pull-up bar() to B, the refactoring preview incorrectly informs me that foo cannot be access from B. If I proceed, there are in fact no problems.
|
resolved fixed
|
fd3cd8b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T08:54:29Z | 2003-10-20T17:13:20Z |
extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java
| |
45,227 |
Bug 45227 Pullup incorrectly reports errors [refactoring]
|
I have a heirachy C derives from B derives from A. A contains protected member variable foo. C contains a method bar() which references foo. If I attempt to pull-up bar() to B, the refactoring preview incorrectly informs me that foo cannot be access from B. If I proceed, there are in fact no problems.
|
resolved fixed
|
fd3cd8b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T08:54:29Z | 2003-10-20T17:13:20Z |
org.eclipse.jdt.ui/core
| |
45,227 |
Bug 45227 Pullup incorrectly reports errors [refactoring]
|
I have a heirachy C derives from B derives from A. A contains protected member variable foo. C contains a method bar() which references foo. If I attempt to pull-up bar() to B, the refactoring preview incorrectly informs me that foo cannot be access from B. If I proceed, there are in fact no problems.
|
resolved fixed
|
fd3cd8b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T08:54:29Z | 2003-10-20T17:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/MoveStaticMembersRefactoring.java
| |
45,227 |
Bug 45227 Pullup incorrectly reports errors [refactoring]
|
I have a heirachy C derives from B derives from A. A contains protected member variable foo. C contains a method bar() which references foo. If I attempt to pull-up bar() to B, the refactoring preview incorrectly informs me that foo cannot be access from B. If I proceed, there are in fact no problems.
|
resolved fixed
|
fd3cd8b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T08:54:29Z | 2003-10-20T17:13:20Z |
org.eclipse.jdt.ui/core
| |
45,227 |
Bug 45227 Pullup incorrectly reports errors [refactoring]
|
I have a heirachy C derives from B derives from A. A contains protected member variable foo. C contains a method bar() which references foo. If I attempt to pull-up bar() to B, the refactoring preview incorrectly informs me that foo cannot be access from B. If I proceed, there are in fact no problems.
|
resolved fixed
|
fd3cd8b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T08:54:29Z | 2003-10-20T17:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PullUpRefactoring.java
| |
45,227 |
Bug 45227 Pullup incorrectly reports errors [refactoring]
|
I have a heirachy C derives from B derives from A. A contains protected member variable foo. C contains a method bar() which references foo. If I attempt to pull-up bar() to B, the refactoring preview incorrectly informs me that foo cannot be access from B. If I proceed, there are in fact no problems.
|
resolved fixed
|
fd3cd8b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T08:54:29Z | 2003-10-20T17:13:20Z |
org.eclipse.jdt.ui/core
| |
45,227 |
Bug 45227 Pullup incorrectly reports errors [refactoring]
|
I have a heirachy C derives from B derives from A. A contains protected member variable foo. C contains a method bar() which references foo. If I attempt to pull-up bar() to B, the refactoring preview incorrectly informs me that foo cannot be access from B. If I proceed, there are in fact no problems.
|
resolved fixed
|
fd3cd8b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T08:54:29Z | 2003-10-20T17:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PushDownRefactoring.java
| |
38,110 |
Bug 38110 Move Static Member(s); should have combo box [refactoring]
|
The Dialog "Move Static Member(s)" should feature a MRU combobox instead of a simple text field for destination type.
|
closed fixed
|
d599e00
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T09:19:36Z | 2003-05-26T14:40:00Z |
org.eclipse.jdt.ui/ui
| |
38,110 |
Bug 38110 Move Static Member(s); should have combo box [refactoring]
|
The Dialog "Move Static Member(s)" should feature a MRU combobox instead of a simple text field for destination type.
|
closed fixed
|
d599e00
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T09:19:36Z | 2003-05-26T14:40:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/MoveMembersWizard.java
| |
46,394 |
Bug 46394 RCP: Add marker action disabled for Java editor
|
N20031111 Start fresh workspace and create a class in a Java project. The following actions are disabled: Edit > Add Bookmark... Edit > Add Task... It works in the standard text editor.
|
verified fixed
|
0aa7aae
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T09:28:20Z | 2003-11-11T08:40:00Z |
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.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.editors.text.EncodingActionGroup;
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 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);
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);
}
}
/*
* @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$
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$
// 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);
}
}
|
46,394 |
Bug 46394 RCP: Add marker action disabled for Java editor
|
N20031111 Start fresh workspace and create a class in a Java project. The following actions are disabled: Edit > Add Bookmark... Edit > Add Task... It works in the standard text editor.
|
verified fixed
|
0aa7aae
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T09:28:20Z | 2003-11-11T08:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/ClassFileEditor.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.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.text.IWidgetTokenKeeper;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModelStatusConstants;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.util.IClassFileDisassembler;
import org.eclipse.jdt.core.util.IClassFileReader;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIStatus;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.SourceAttachmentDialog;
/**
* Java specific text editor.
*/
public class ClassFileEditor extends JavaEditor implements ClassFileDocumentProvider.InputChangeListener {
/** The horizontal scroll increment. */
private static final int HORIZONTAL_SCROLL_INCREMENT= 10;
/** The vertical scroll increment. */
private static final int VERTICAL_SCROLL_INCREMENT= 10;
/**
* A form to attach source to a class file.
*/
private class SourceAttachmentForm implements IPropertyChangeListener {
private final IClassFile fFile;
private ScrolledComposite fScrolledComposite;
private Color fBackgroundColor;
private Color fForegroundColor;
private Color fSeparatorColor;
private List fBannerLabels= new ArrayList();
private List fHeaderLabels= new ArrayList();
private Font fFont;
/**
* Creates a source attachment form for a class file.
*/
public SourceAttachmentForm(IClassFile file) {
fFile= file;
}
/**
* Returns the package fragment root of this file.
*/
private IPackageFragmentRoot getPackageFragmentRoot(IClassFile file) {
IJavaElement element= file.getParent();
while (element != null && element.getElementType() != IJavaElement.PACKAGE_FRAGMENT_ROOT)
element= element.getParent();
return (IPackageFragmentRoot) element;
}
/**
* Creates the control of the source attachment form.
*/
public Control createControl(Composite parent) {
Display display= parent.getDisplay();
fBackgroundColor= display.getSystemColor(SWT.COLOR_LIST_BACKGROUND);
fForegroundColor= display.getSystemColor(SWT.COLOR_LIST_FOREGROUND);
fSeparatorColor= new Color(display, 152, 170, 203);
JFaceResources.getFontRegistry().addListener(this);
fScrolledComposite= new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL);
fScrolledComposite.setAlwaysShowScrollBars(false);
fScrolledComposite.setExpandHorizontal(true);
fScrolledComposite.setExpandVertical(true);
fScrolledComposite.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
JFaceResources.getFontRegistry().removeListener(SourceAttachmentForm.this);
fScrolledComposite= null;
fSeparatorColor.dispose();
fSeparatorColor= null;
fBannerLabels.clear();
fHeaderLabels.clear();
if (fFont != null) {
fFont.dispose();
fFont= null;
}
}
});
fScrolledComposite.addControlListener(new ControlListener() {
public void controlMoved(ControlEvent e) {}
public void controlResized(ControlEvent e) {
Rectangle clientArea = fScrolledComposite.getClientArea();
ScrollBar verticalBar= fScrolledComposite.getVerticalBar();
verticalBar.setIncrement(VERTICAL_SCROLL_INCREMENT);
verticalBar.setPageIncrement(clientArea.height - verticalBar.getIncrement());
ScrollBar horizontalBar= fScrolledComposite.getHorizontalBar();
horizontalBar.setIncrement(HORIZONTAL_SCROLL_INCREMENT);
horizontalBar.setPageIncrement(clientArea.width - horizontalBar.getIncrement());
}
});
Composite composite= createComposite(fScrolledComposite);
composite.setLayout(new GridLayout());
createTitleLabel(composite, JavaEditorMessages.getString("SourceAttachmentForm.title")); //$NON-NLS-1$
createLabel(composite, null);
createLabel(composite, null);
createHeadingLabel(composite, JavaEditorMessages.getString("SourceAttachmentForm.heading")); //$NON-NLS-1$
Composite separator= createCompositeSeparator(composite);
GridData data= new GridData(GridData.FILL_HORIZONTAL);
data.heightHint= 2;
separator.setLayoutData(data);
try {
IPackageFragmentRoot root= getPackageFragmentRoot(fFile);
if (root != null) {
createSourceAttachmentControls(composite, root);
}
} catch (JavaModelException e) {
String title= JavaEditorMessages.getString("SourceAttachmentForm.error.title"); //$NON-NLS-1$
String message= JavaEditorMessages.getString("SourceAttachmentForm.error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, fScrolledComposite.getShell(), title, message);
}
separator= createCompositeSeparator(composite);
data= new GridData(GridData.FILL_HORIZONTAL);
data.heightHint= 2;
separator.setLayoutData(data);
StyledText styledText= createCodeView(composite);
data= new GridData(GridData.FILL_BOTH);
styledText.setLayoutData(data);
updateCodeView(styledText, fFile);
fScrolledComposite.setContent(composite);
fScrolledComposite.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
return fScrolledComposite;
}
private void createSourceAttachmentControls(Composite composite, IPackageFragmentRoot root) throws JavaModelException {
IClasspathEntry entry= root.getRawClasspathEntry();
IPath containerPath= null;
IJavaProject jproject= root.getJavaProject();
if (entry == null || !root.isArchive()) {
createLabel(composite, JavaEditorMessages.getFormattedString("SourceAttachmentForm.message.noSource", fFile.getElementName())); //$NON-NLS-1$
return;
}
if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
containerPath= entry.getPath();
IClasspathEntry entry2= SourceAttachmentDialog.getClasspathEntryToEdit(jproject, containerPath, root.getPath());
if (entry2 == null) {
IClasspathContainer container= JavaCore.getClasspathContainer(entry.getPath(), root.getJavaProject());
String containerName= container == null ? entry.getPath().toString() : container.getDescription();
createLabel(composite, JavaEditorMessages.getFormattedString("SourceAttachmentForm.message.containerEntry", containerName)); //$NON-NLS-1$
return;
}
entry= entry2;
}
Button button;
IPath path= entry.getSourceAttachmentPath();
if (path == null || path.isEmpty()) {
createLabel(composite, JavaEditorMessages.getFormattedString("SourceAttachmentForm.message.noSourceAttachment", root.getElementName())); //$NON-NLS-1$
createLabel(composite, JavaEditorMessages.getString("SourceAttachmentForm.message.pressButtonToAttach")); //$NON-NLS-1$
createLabel(composite, null);
button= createButton(composite, JavaEditorMessages.getString("SourceAttachmentForm.button.attachSource")); //$NON-NLS-1$
} else {
createLabel(composite, JavaEditorMessages.getFormattedString("SourceAttachmentForm.message.noSourceInAttachment", fFile.getElementName())); //$NON-NLS-1$
createLabel(composite, JavaEditorMessages.getString("SourceAttachmentForm.message.pressButtonToChange")); //$NON-NLS-1$
createLabel(composite, null);
button= createButton(composite, JavaEditorMessages.getString("SourceAttachmentForm.button.changeAttachedSource")); //$NON-NLS-1$
}
button.addSelectionListener(getButtonListener(entry, containerPath, jproject));
}
private SelectionListener getButtonListener(final IClasspathEntry entry, final IPath containerPath, final IJavaProject jproject) {
return new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
try {
SourceAttachmentDialog dialog= new SourceAttachmentDialog(fScrolledComposite.getShell(), entry, containerPath, jproject, true);
if (dialog.open() == Window.OK)
verifyInput(getEditorInput());
} catch (CoreException e) {
String title= JavaEditorMessages.getString("SourceAttachmentForm.error.title"); //$NON-NLS-1$
String message= JavaEditorMessages.getString("SourceAttachmentForm.error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, fScrolledComposite.getShell(), title, message);
}
}
public void widgetDefaultSelected(SelectionEvent e) {}
};
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
for (Iterator iterator = fBannerLabels.iterator(); iterator.hasNext();) {
Label label = (Label) iterator.next();
label.setFont(JFaceResources.getBannerFont());
}
for (Iterator iterator = fHeaderLabels.iterator(); iterator.hasNext();) {
Label label = (Label) iterator.next();
label.setFont(JFaceResources.getHeaderFont());
}
Control control= fScrolledComposite.getContent();
fScrolledComposite.setMinSize(control.computeSize(SWT.DEFAULT, SWT.DEFAULT));
fScrolledComposite.setContent(control);
fScrolledComposite.layout(true);
fScrolledComposite.redraw();
}
// --- copied from org.eclipse.update.ui.forms.internal.FormWidgetFactory
private Composite createComposite(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setBackground(fBackgroundColor);
// composite.addMouseListener(new MouseAdapter() {
// public void mousePressed(MouseEvent e) {
// ((Control) e.widget).setFocus();
// }
// });
return composite;
}
private Composite createCompositeSeparator(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setBackground(fSeparatorColor);
return composite;
}
private StyledText createCodeView(Composite parent) {
int styles= SWT.MULTI | SWT.FULL_SELECTION;
StyledText styledText= new StyledText(parent, styles);
styledText.setBackground(fBackgroundColor);
styledText.setForeground(fForegroundColor);
styledText.setEditable(false);
return styledText;
}
private Label createLabel(Composite parent, String text) {
Label label = new Label(parent, SWT.NONE);
if (text != null)
label.setText(text);
label.setBackground(fBackgroundColor);
label.setForeground(fForegroundColor);
return label;
}
private Label createTitleLabel(Composite parent, String text) {
Label label = new Label(parent, SWT.NONE);
if (text != null)
label.setText(text);
label.setBackground(fBackgroundColor);
label.setForeground(fForegroundColor);
label.setFont(JFaceResources.getHeaderFont());
fHeaderLabels.add(label);
return label;
}
private Label createHeadingLabel(Composite parent, String text) {
Label label = new Label(parent, SWT.NONE);
if (text != null)
label.setText(text);
label.setBackground(fBackgroundColor);
label.setForeground(fForegroundColor);
label.setFont(JFaceResources.getBannerFont());
fBannerLabels.add(label);
return label;
}
private Button createButton(Composite parent, String text) {
Button button = new Button(parent, SWT.FLAT);
button.setBackground(fBackgroundColor);
button.setForeground(fForegroundColor);
if (text != null)
button.setText(text);
// button.addFocusListener(visibilityHandler);
return button;
}
private void updateCodeView(StyledText styledText, IClassFile classFile) {
String content= null;
int flags= IClassFileReader.FIELD_INFOS | IClassFileReader.METHOD_INFOS | IClassFileReader.SUPER_INTERFACES;
IClassFileReader classFileReader= ToolFactory.createDefaultClassFileReader(classFile, flags);
if (classFileReader != null) {
IClassFileDisassembler disassembler= ToolFactory.createDefaultClassFileDisassembler();
content= disassembler.disassemble(classFileReader, "\n"); //$NON-NLS-1$
}
styledText.setText(content == null ? "" : content); //$NON-NLS-1$
}
}
/**
* Updater that takes care of minimizing changes of the editor input.
*/
private class InputUpdater implements Runnable {
/** Has the runnable already been posted? */
private boolean fPosted= false;
/** Editor input */
private IClassFileEditorInput fClassFileEditorInput;
public InputUpdater() {
}
/*
* @see Runnable#run()
*/
public void run() {
IClassFileEditorInput input;
synchronized (this) {
input= fClassFileEditorInput;
}
try {
if (getSourceViewer() != null)
setInput(input);
} finally {
synchronized (this) {
fPosted= false;
}
}
}
/**
* Posts this runnable into the event queue if not already there.
*
* @param input the input to be set when executed
*/
public void post(IClassFileEditorInput input) {
synchronized(this) {
if (fPosted) {
if (input != null && input.equals(fClassFileEditorInput))
fClassFileEditorInput= input;
return;
}
}
if (input != null && input.equals(getEditorInput())) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
StyledText textWidget= viewer.getTextWidget();
if (textWidget != null && !textWidget.isDisposed()) {
synchronized (this) {
fPosted= true;
fClassFileEditorInput= input;
}
textWidget.getDisplay().asyncExec(this);
}
}
}
}
}
private StackLayout fStackLayout;
private Composite fParent;
private Composite fViewerComposite;
private Control fSourceAttachmentForm;
private InputUpdater fInputUpdater= new InputUpdater();
/**
* Default constructor.
*/
public ClassFileEditor() {
super();
setDocumentProvider(JavaPlugin.getDefault().getClassFileDocumentProvider());
setEditorContextMenuId("#ClassFileEditorContext"); //$NON-NLS-1$
setRulerContextMenuId("#ClassFileRulerContext"); //$NON-NLS-1$
setOutlinerContextMenuId("#ClassFileOutlinerContext"); //$NON-NLS-1$
// don't set help contextId, we install our own help context
}
/*
* @see AbstractTextEditor#createActions()
*/
protected void createActions() {
super.createActions();
setAction(ITextEditorActionConstants.SAVE, null);
setAction(ITextEditorActionConstants.REVERT_TO_SAVED, null);
/*
* 1GF82PL: ITPJUI:ALL - Need to be able to add bookmark to classfile
*
* // replace default action with class file specific ones
*
* setAction(ITextEditorActionConstants.BOOKMARK, new AddClassFileMarkerAction("AddBookmark.", this, IMarker.BOOKMARK, true)); //$NON-NLS-1$
* setAction(ITextEditorActionConstants.ADD_TASK, new AddClassFileMarkerAction("AddTask.", this, IMarker.TASK, false)); //$NON-NLS-1$
* setAction(ITextEditorActionConstants.RULER_MANAGE_BOOKMARKS, new ClassFileMarkerRulerAction("ManageBookmarks.", getVerticalRuler(), this, IMarker.BOOKMARK, true)); //$NON-NLS-1$
* setAction(ITextEditorActionConstants.RULER_MANAGE_TASKS, new ClassFileMarkerRulerAction("ManageTasks.", getVerticalRuler(), this, IMarker.TASK, true)); //$NON-NLS-1$
*/
setAction(ITextEditorActionConstants.BOOKMARK, null);
setAction(ITextEditorActionConstants.ADD_TASK, null);
}
/*
* @see JavaEditor#getElementAt(int)
*/
protected IJavaElement getElementAt(int offset) {
if (getEditorInput() instanceof IClassFileEditorInput) {
try {
IClassFileEditorInput input= (IClassFileEditorInput) getEditorInput();
return input.getClassFile().getElementAt(offset);
} catch (JavaModelException x) {
}
}
return null;
}
/*
* @see JavaEditor#getCorrespondingElement(IJavaElement)
*/
protected IJavaElement getCorrespondingElement(IJavaElement element) {
if (getEditorInput() instanceof IClassFileEditorInput) {
IClassFileEditorInput input= (IClassFileEditorInput) getEditorInput();
IJavaElement parent= element.getAncestor(IJavaElement.CLASS_FILE);
if (input.getClassFile().equals(parent))
return element;
}
return null;
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#getInputElement()
*/
protected IJavaElement getInputJavaElement() {
return ((IClassFileEditorInput)getEditorInput()).getClassFile();
}
/*
* @see IEditorPart#saveState(IMemento)
*/
public void saveState(IMemento memento) {
}
/*
* @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
*/
protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
if (page != null && input instanceof IClassFileEditorInput) {
IClassFileEditorInput cfi= (IClassFileEditorInput) input;
page.setInput(cfi.getClassFile());
}
}
/*
* 1GEPKT5: ITPJUI:Linux - Source in editor for external classes is editable
* Removed methods isSaveOnClosedNeeded and isDirty.
* Added method isEditable.
*/
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#isEditable()
*/
public boolean isEditable() {
return false;
}
/**
* Translates the given editor input into an <code>ExternalClassFileEditorInput</code>
* if it is a file editor input representing an external class file.
*
* @param input the editor input to be transformed if necessary
* @return the transformed editor input
*/
protected IEditorInput transformEditorInput(IEditorInput input) {
if (input instanceof IFileEditorInput) {
IFile file= ((IFileEditorInput) input).getFile();
IClassFileEditorInput classFileInput= new ExternalClassFileEditorInput(file);
if (classFileInput.getClassFile() != null)
input= classFileInput;
}
return input;
}
/*
* @see AbstractTextEditor#doSetInput(IEditorInput)
*/
protected void doSetInput(IEditorInput input) throws CoreException {
input= transformEditorInput(input);
if (!(input instanceof IClassFileEditorInput))
throw new CoreException(JavaUIStatus.createError(
IJavaModelStatusConstants.INVALID_RESOURCE_TYPE,
JavaEditorMessages.getString("ClassFileEditor.error.invalid_input_message"), //$NON-NLS-1$
null)); //$NON-NLS-1$
JavaModelException e= probeInputForSource(input);
if (e != null) {
IClassFileEditorInput classFileEditorInput= (IClassFileEditorInput) input;
IClassFile file= classFileEditorInput.getClassFile();
if (!file.getJavaProject().exists() || !file.getJavaProject().isOnClasspath(file)) {
throw new CoreException(JavaUIStatus.createError(
IJavaModelStatusConstants.INVALID_RESOURCE,
JavaEditorMessages.getString("ClassFileEditor.error.classfile_not_on_classpath"), //$NON-NLS-1$
null)); //$NON-NLS-1$
} else {
throw e;
}
}
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider instanceof ClassFileDocumentProvider)
((ClassFileDocumentProvider) documentProvider).removeInputChangeListener(this);
super.doSetInput(input);
documentProvider= getDocumentProvider();
if (documentProvider instanceof ClassFileDocumentProvider)
((ClassFileDocumentProvider) documentProvider).addInputChangeListener(this);
verifyInput(getEditorInput());
}
/*
* @see IWorkbenchPart#createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
fParent= new Composite(parent, SWT.NONE);
fStackLayout= new StackLayout();
fParent.setLayout(fStackLayout);
fViewerComposite= new Composite(fParent, SWT.NONE);
fViewerComposite.setLayout(new FillLayout());
super.createPartControl(fViewerComposite);
fStackLayout.topControl= fViewerComposite;
fParent.layout();
try {
verifyInput(getEditorInput());
} catch (CoreException e) {
String title= JavaEditorMessages.getString("ClassFileEditor.error.title"); //$NON-NLS-1$
String message= JavaEditorMessages.getString("ClassFileEditor.error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, fParent.getShell(), title, message);
}
}
private JavaModelException probeInputForSource(IEditorInput input) {
if (input == null)
return null;
IClassFileEditorInput classFileEditorInput= (IClassFileEditorInput) input;
IClassFile file= classFileEditorInput.getClassFile();
try {
file.getSourceRange();
} catch (JavaModelException e) {
return e;
}
return null;
}
/**
* Checks if the class file input has no source attached. If so, a source attachment form is shown.
*/
private void verifyInput(IEditorInput input) throws CoreException {
if (fParent == null || input == null)
return;
IClassFileEditorInput classFileEditorInput= (IClassFileEditorInput) input;
IClassFile file= classFileEditorInput.getClassFile();
// show source attachment form if no source found
if (file.getSourceRange() == null) {
// dispose old source attachment form
if (fSourceAttachmentForm != null)
fSourceAttachmentForm.dispose();
SourceAttachmentForm form= new SourceAttachmentForm(file);
fSourceAttachmentForm= form.createControl(fParent);
fStackLayout.topControl= fSourceAttachmentForm;
fParent.layout();
// show source viewer
} else {
if (fSourceAttachmentForm != null) {
fSourceAttachmentForm.dispose();
fSourceAttachmentForm= null;
fStackLayout.topControl= fViewerComposite;
fParent.layout();
}
}
}
/*
* @see ClassFileDocumentProvider.InputChangeListener#inputChanged(IClassFileEditorInput)
*/
public void inputChanged(IClassFileEditorInput input) {
fInputUpdater.post(input);
}
/*
* @see JavaEditor#createJavaSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
return new JavaSourceViewer(parent, ruler, null, false, styles) {
public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
if (WorkbenchHelp.isContextHelpDisplayed())
return false;
return super.requestWidgetToken(requester);
}
public boolean requestWidgetToken(IWidgetTokenKeeper requester, int priority) {
if (WorkbenchHelp.isContextHelpDisplayed())
return false;
return super.requestWidgetToken(requester, priority);
}
};
}
/*
* @see org.eclipse.ui.IWorkbenchPart#dispose()
*/
public void dispose() {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=18510
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider instanceof ClassFileDocumentProvider)
((ClassFileDocumentProvider) documentProvider).removeInputChangeListener(this);
super.dispose();
}
/*
* @see org.eclipse.ui.IWorkbenchPart#setFocus()
*/
public void setFocus() {
super.setFocus();
if (fSourceAttachmentForm != null && !fSourceAttachmentForm.isDisposed())
fSourceAttachmentForm.setFocus();
}
}
|
46,394 |
Bug 46394 RCP: Add marker action disabled for Java editor
|
N20031111 Start fresh workspace and create a class in a Java project. The following actions are disabled: Edit > Add Bookmark... Edit > Add Task... It works in the standard text editor.
|
verified fixed
|
0aa7aae
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T09:28:20Z | 2003-11-11T08:40:00Z |
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.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.Event;
import org.eclipse.swt.widgets.Listener;
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.IAnnotationAccess;
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.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.IEncodingSupport;
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.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.AddTaskAction;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.DefaultAnnotation;
import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.ExtendedTextEditor;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
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.MarkerAnnotationPreferences;
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.search.ui.SearchUI;
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();
updateOccurrences();
}
}
/**
* 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;
}
}
}
static protected class AnnotationAccess extends DefaultMarkerAnnotationAccess {
public AnnotationAccess(MarkerAnnotationPreferences markerAnnotationPreferences) {
super(markerAnnotationPreferences);
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation)
*/
public Object getType(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.getAnnotationType();
return null;
}
return super.getType(annotation);
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation)
*/
public boolean isMultiLine(Annotation annotation) {
return true;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation)
*/
public boolean isTemporary(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.isTemporary();
}
return false;
}
}
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();
}
}
}
}
/** 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;
/**
* 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;
}
/*
* @see org.eclipse.ui.texteditor.ExtendedTextEditor#createAnnotationAccess()
*/
protected IAnnotationAccess createAnnotationAccess() {
return new AnnotationAccess(new MarkerAnnotationPreferences());
}
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 (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();
ResourceAction resAction= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$
resAction.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION);
resAction.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK);
setAction(ITextEditorActionConstants.ADD_TASK, resAction);
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});
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().addListener(SWT.Deactivate, new Listener() {
/*
* @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
*/
public void handleEvent(Event event) {
removeOccurrenceAnnotations();
}
});
getEditorSite().getShell().addListener(SWT.Activate, new Listener() {
/*
* @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
*/
public void handleEvent(Event event) {
updateOccurrences();
}
});
}
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());
if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation)annotation).isProblem())
setStatusLineMessage(((IJavaAnnotation)annotation).getMessage());
}
}
}
/**
* 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 DefaultAnnotation(SearchUI.SEARCH_MARKER, IMarker.SEVERITY_INFO, true, 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 updateOccurrences() {
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(((IJavaAnnotation)annotation).getMessage());
}
}
/**
* 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(int offset, 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= 0;
IAnnotationAccess access= getAnnotationAccess();
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true, true);
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
Object type;
if (a instanceof IJavaAnnotation)
type= ((IJavaAnnotation) a).getAnnotationType();
else
type= access.getType(a);
boolean isNavigationTarget= isNavigationTargetType(type);
if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation)a).hasOverlay() || !isNavigationTarget)
continue;
Position p= model.getPosition(a);
if (p == null)
continue;
if (!(p.includes(offset) || (p.getLength() == 0 && offset == p.offset))) {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument - offset + p.getOffset();
} else {
currentDistance= offset - p.getOffset();
if (currentDistance < 0)
currentDistance= offset + endOfDocument - p.getOffset();
}
if (nextAnnotation == null || currentDistance < distance) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
} else {
if (containingAnnotationPosition == null || containingAnnotationPosition.length > p.length) {
containingAnnotation= a;
containingAnnotationPosition= p;
if (length == p.length)
currentAnnotation= true;
}
}
}
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) {
IAnnotationAccess access= getAnnotationAccess();
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 annotation= (IJavaAnnotation) a;
if (annotation.hasOverlay() || !isNavigationTargetType(annotation.getAnnotationType()))
continue;
} else if (!isNavigationTargetType(access.getType(a)))
continue;
Position p= model.getPosition(a);
if (p != null && p.overlapsWith(offset, length))
return a;
}
return null;
}
/**
* Returns whether the given annotation type is configured as a target type
* for the "Go to Next/Previous Annotation" actions
*
* @param type the annotation type
* @return <code>true</code> if this is a target type, <code>false</code>
* otherwise
* @since 3.0
*/
private boolean isNavigationTargetType(Object type) {
Preferences preferences= Platform.getPlugin("org.eclipse.ui.editors").getPluginPreferences(); //$NON-NLS-1$
Iterator i= getAnnotationPreferences().getAnnotationPreferences().iterator();
while (i.hasNext()) {
AnnotationPreference annotationPref= (AnnotationPreference) i.next();
if (annotationPref.getAnnotationType().equals(type)) {
// See bug 41689
// String key= forward ? annotationPref.getIsGoToNextNavigationTargetKey() : annotationPref.getIsGoToPreviousNavigationTargetKey();
String key= annotationPref.getIsGoToNextNavigationTargetKey();
if (key != null && preferences.getBoolean(key))
return true;
}
}
return false;
}
/**
* 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);
}
}
|
46,394 |
Bug 46394 RCP: Add marker action disabled for Java editor
|
N20031111 Start fresh workspace and create a class in a Java project. The following actions are disabled: Edit > Add Bookmark... Edit > Add Task... It works in the standard text editor.
|
verified fixed
|
0aa7aae
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T09:28:20Z | 2003-11-11T08:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/GenerateActionGroup.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.AddBookmarkAction;
import org.eclipse.ui.editors.text.ITextEditorHelpContextIds;
import org.eclipse.ui.part.Page;
import org.eclipse.ui.texteditor.ConvertLineDelimitersAction;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.AddTaskAction;
import org.eclipse.jdt.internal.ui.javaeditor.AddImportOnSelectionAction;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
/**
* Action group that adds the source and generate actions to a part's context
* menu and installs handlers for the corresponding global menu actions.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class GenerateActionGroup extends ActionGroup {
private CompilationUnitEditor fEditor;
private IWorkbenchSite fSite;
private String fGroupName= IContextMenuConstants.GROUP_REORGANIZE;
private List fRegisteredSelectionListeners;
private AddImportOnSelectionAction fAddImport;
private OverrideMethodsAction fOverrideMethods;
private AddGetterSetterAction fAddGetterSetter;
private AddDelegateMethodsAction fAddDelegateMethods;
private AddUnimplementedConstructorsAction fAddUnimplementedConstructors;
private GenerateNewConstructorUsingFieldsAction fGenerateConstructorUsingFields;
private AddJavaDocStubAction fAddJavaDocStub;
private AddBookmarkAction fAddBookmark;
private AddTaskAction fAddTaskAction;
private ExternalizeStringsAction fExternalizeStrings;
private FindStringsToExternalizeAction fFindStringsToExternalize;
private SurroundWithTryCatchAction fSurroundWithTryCatch;
private AddToClasspathAction fAddToClasspathAction;
private RemoveFromClasspathAction fRemoveFromClasspathAction;
private OrganizeImportsAction fOrganizeImports;
private SortMembersAction fSortMembers;
private ConvertLineDelimitersAction fConvertToWindows;
private ConvertLineDelimitersAction fConvertToUNIX;
private ConvertLineDelimitersAction fConvertToMac;
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public GenerateActionGroup(CompilationUnitEditor editor, String groupName) {
fSite= editor.getSite();
fEditor= editor;
fGroupName= groupName;
ISelectionProvider provider= fSite.getSelectionProvider();
ISelection selection= provider.getSelection();
fAddImport= new AddImportOnSelectionAction(editor);
fAddImport.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_IMPORT);
fAddImport.update();
editor.setAction("AddImport", fAddImport); //$NON-NLS-1$
fOrganizeImports= new OrganizeImportsAction(editor);
fOrganizeImports.setActionDefinitionId(IJavaEditorActionDefinitionIds.ORGANIZE_IMPORTS);
editor.setAction("OrganizeImports", fOrganizeImports); //$NON-NLS-1$
fSortMembers= new SortMembersAction(editor);
fSortMembers.setActionDefinitionId(IJavaEditorActionDefinitionIds.SORT_MEMBERS);
editor.setAction("SortMembers", fSortMembers); //$NON-NLS-1$
fOverrideMethods= new OverrideMethodsAction(editor);
fOverrideMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.OVERRIDE_METHODS);
editor.setAction("OverrideMethods", fOverrideMethods); //$NON-NLS-1$
fAddGetterSetter= new AddGetterSetterAction(editor);
fAddGetterSetter.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_GETTER_SETTER);
editor.setAction("AddGetterSetter", fAddGetterSetter); //$NON-NLS-1$
fAddDelegateMethods= new AddDelegateMethodsAction(editor);
fAddDelegateMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_DELEGATE_METHODS);
editor.setAction("AddDelegateMethods", fAddDelegateMethods); //$NON-NLS-1$
fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(editor);
fAddUnimplementedConstructors.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_UNIMPLEMENTED_CONTRUCTORS);
editor.setAction("AddUnimplementedConstructors", fAddUnimplementedConstructors); //$NON-NLS-1$
fGenerateConstructorUsingFields= new GenerateNewConstructorUsingFieldsAction(editor);
fGenerateConstructorUsingFields.setActionDefinitionId(IJavaEditorActionDefinitionIds.GENERATE_CONSTRUCTOR_USING_FIELDS);
editor.setAction("GenerateConstructorUsingFields", fGenerateConstructorUsingFields); //$NON-NLS-1$
fAddJavaDocStub= new AddJavaDocStubAction(editor);
fAddJavaDocStub.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_JAVADOC_COMMENT);
editor.setAction("AddJavadocComment", fAddJavaDocStub); //$NON-NLS-1$
fSurroundWithTryCatch= new SurroundWithTryCatchAction(editor);
fSurroundWithTryCatch.setActionDefinitionId(IJavaEditorActionDefinitionIds.SURROUND_WITH_TRY_CATCH);
fSurroundWithTryCatch.update(selection);
provider.addSelectionChangedListener(fSurroundWithTryCatch);
editor.setAction("SurroundWithTryCatch", fSurroundWithTryCatch); //$NON-NLS-1$
fExternalizeStrings= new ExternalizeStringsAction(editor);
fExternalizeStrings.setActionDefinitionId(IJavaEditorActionDefinitionIds.EXTERNALIZE_STRINGS);
editor.setAction("ExternalizeStrings", fExternalizeStrings); //$NON-NLS-1$
fConvertToWindows= new ConvertLineDelimitersAction(editor, "\r\n"); //$NON-NLS-1$
fConvertToWindows.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_WINDOWS);
fConvertToWindows.setHelpContextId(ITextEditorHelpContextIds.CONVERT_LINE_DELIMITERS_TO_WINDOWS);
editor.setAction("ConvertLineDelimitersToWindows", fConvertToWindows); //$NON-NLS-1$
fConvertToUNIX= new ConvertLineDelimitersAction(editor, "\n"); //$NON-NLS-1$
fConvertToUNIX.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_UNIX);
fConvertToUNIX.setHelpContextId(ITextEditorHelpContextIds.CONVERT_LINE_DELIMITERS_TO_UNIX);
editor.setAction("ConvertLineDelimitersToUNIX", fConvertToUNIX); //$NON-NLS-1$
fConvertToMac= new ConvertLineDelimitersAction(editor, "\r"); //$NON-NLS-1$
fConvertToMac.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_MAC);
fConvertToMac.setHelpContextId(ITextEditorHelpContextIds.CONVERT_LINE_DELIMITERS_TO_MAC);
editor.setAction("ConvertLineDelimitersToMac", fConvertToMac); //$NON-NLS-1$
}
/**
* Creates a new <code>GenerateActionGroup</code>. The group
* requires that the selection provided by the page's selection provider
* is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param page the page that owns this action group
*/
public GenerateActionGroup(Page page) {
this(page.getSite());
}
/**
* Creates a new <code>GenerateActionGroup</code>. The group
* requires that the selection provided by the part's selection provider
* is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param part the view part that owns this action group
*/
public GenerateActionGroup(IViewPart part) {
this(part.getSite());
}
private GenerateActionGroup(IWorkbenchSite site) {
fSite= site;
ISelectionProvider provider= fSite.getSelectionProvider();
ISelection selection= provider.getSelection();
fOverrideMethods= new OverrideMethodsAction(site);
fAddGetterSetter= new AddGetterSetterAction(site);
fAddDelegateMethods= new AddDelegateMethodsAction(site);
fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(site);
fGenerateConstructorUsingFields= new GenerateNewConstructorUsingFieldsAction(site);
fAddJavaDocStub= new AddJavaDocStubAction(site);
fAddBookmark= new AddBookmarkAction(site.getShell());
fAddToClasspathAction= new AddToClasspathAction(site);
fRemoveFromClasspathAction= new RemoveFromClasspathAction(site);
fAddTaskAction= new AddTaskAction(site);
fExternalizeStrings= new ExternalizeStringsAction(site);
fFindStringsToExternalize= new FindStringsToExternalizeAction(site);
fOrganizeImports= new OrganizeImportsAction(site);
fSortMembers= new SortMembersAction(site);
fOverrideMethods.update(selection);
fAddGetterSetter.update(selection);
fAddDelegateMethods.update(selection);
fAddUnimplementedConstructors.update(selection);
fGenerateConstructorUsingFields.update(selection);
fAddJavaDocStub.update(selection);
fAddToClasspathAction.update(selection);
fRemoveFromClasspathAction.update(selection);
fExternalizeStrings.update(selection);
fFindStringsToExternalize.update(selection);
fAddTaskAction.update(selection);
fOrganizeImports.update(selection);
fSortMembers.update(selection);
if (selection instanceof IStructuredSelection) {
IStructuredSelection ss= (IStructuredSelection)selection;
fAddBookmark.selectionChanged(ss);
} else {
fAddBookmark.setEnabled(false);
}
registerSelectionListener(provider, fOverrideMethods);
registerSelectionListener(provider, fAddGetterSetter);
registerSelectionListener(provider, fAddDelegateMethods);
registerSelectionListener(provider, fAddUnimplementedConstructors);
registerSelectionListener(provider, fGenerateConstructorUsingFields);
registerSelectionListener(provider, fAddJavaDocStub);
registerSelectionListener(provider, fAddBookmark);
registerSelectionListener(provider, fAddToClasspathAction);
registerSelectionListener(provider, fRemoveFromClasspathAction);
registerSelectionListener(provider, fExternalizeStrings);
registerSelectionListener(provider, fFindStringsToExternalize);
registerSelectionListener(provider, fOrganizeImports);
registerSelectionListener(provider, fSortMembers);
registerSelectionListener(provider, fAddTaskAction);
}
private void registerSelectionListener(ISelectionProvider provider, ISelectionChangedListener listener) {
if (fRegisteredSelectionListeners == null)
fRegisteredSelectionListeners= new ArrayList(20);
provider.addSelectionChangedListener(listener);
fRegisteredSelectionListeners.add(listener);
}
/*
* The state of the editor owning this action group has changed.
* This method does nothing if the group's owner isn't an
* editor.
*/
/**
* Note: This method is for internal use only. Clients should not call this method.
*/
public void editorStateChanged() {
Assert.isTrue(isEditorOwner());
// http://dev.eclipse.org/bugs/show_bug.cgi?id=17709
fConvertToMac.update();
fConvertToUNIX.update();
fConvertToWindows.update();
}
/* (non-Javadoc)
* Method declared in ActionGroup
*/
public void fillActionBars(IActionBars actionBar) {
super.fillActionBars(actionBar);
setGlobalActionHandlers(actionBar);
}
/* (non-Javadoc)
* Method declared in ActionGroup
*/
public void fillContextMenu(IMenuManager menu) {
super.fillContextMenu(menu);
IMenuManager subMenu= null;
if (isEditorOwner()) {
subMenu= createEditorSubMenu(menu);
} else {
subMenu= createViewSubMenu(menu);
}
if (subMenu != null)
menu.appendToGroup(fGroupName, subMenu);
}
private IMenuManager createEditorSubMenu(IMenuManager mainMenu) {
IMenuManager result= new MenuManager(ActionMessages.getString("SourceMenu.label")); //$NON-NLS-1$
int added= 0;
added+= addEditorAction(result, "Comment"); //$NON-NLS-1$
added+= addEditorAction(result, "Uncomment"); //$NON-NLS-1$
added+= addEditorAction(result, "AddBlockComment"); //$NON-NLS-1$
added+= addEditorAction(result, "RemoveBlockComment"); //$NON-NLS-1$
added+= addEditorAction(result, "Format"); //$NON-NLS-1$
added+= addEditorAction(result, "Indent"); //$NON-NLS-1$
result.add(new Separator());
added+= addAction(result, fOrganizeImports);
added+= addAction(result, fAddImport);
result.add(new Separator());
added+= addAction(result, fOverrideMethods);
added+= addAction(result, fAddGetterSetter);
added+= addAction(result, fAddDelegateMethods);
added+= addAction(result, fAddUnimplementedConstructors);
added+= addAction(result, fGenerateConstructorUsingFields);
added+= addAction(result, fAddJavaDocStub);
result.add(new Separator());
added+= addAction(result, fSurroundWithTryCatch);
if (added == 0)
result= null;
return result;
}
private IMenuManager createViewSubMenu(IMenuManager mainMenu) {
IMenuManager result= new MenuManager(ActionMessages.getString("SourceMenu.label")); //$NON-NLS-1$
int added= 0;
added+= addAction(result, fSortMembers);
result.add(new Separator());
added+= addAction(result, fOrganizeImports);
added+= addAction(result, fAddImport);
result.add(new Separator());
added+= addAction(result, fOverrideMethods);
added+= addAction(result, fAddGetterSetter);
added+= addAction(result, fAddDelegateMethods);
added+= addAction(result, fAddUnimplementedConstructors);
added+= addAction(result, fGenerateConstructorUsingFields);
added+= addAction(result, fAddJavaDocStub);
added+= addAction(result, fAddToClasspathAction);
added+= addAction(result, fRemoveFromClasspathAction);
result.add(new Separator());
added+= addAction(result, fSurroundWithTryCatch);
added+= addAction(result, fExternalizeStrings);
added+= addAction(result, fFindStringsToExternalize);
if (added == 0)
result= null;
return result;
}
/* (non-Javadoc)
* Method declared in ActionGroup
*/
public void dispose() {
if (fRegisteredSelectionListeners != null) {
ISelectionProvider provider= fSite.getSelectionProvider();
for (Iterator iter= fRegisteredSelectionListeners.iterator(); iter.hasNext();) {
ISelectionChangedListener listener= (ISelectionChangedListener) iter.next();
provider.removeSelectionChangedListener(listener);
}
}
fEditor= null;
super.dispose();
}
private void setGlobalActionHandlers(IActionBars actionBar) {
actionBar.setGlobalActionHandler(JdtActionConstants.ADD_IMPORT, fAddImport);
actionBar.setGlobalActionHandler(JdtActionConstants.SURROUND_WITH_TRY_CATCH, fSurroundWithTryCatch);
actionBar.setGlobalActionHandler(JdtActionConstants.OVERRIDE_METHODS, fOverrideMethods);
actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_GETTER_SETTER, fAddGetterSetter);
actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_DELEGATE_METHODS, fAddDelegateMethods);
actionBar.setGlobalActionHandler(JdtActionConstants.ADD_CONSTRUCTOR_FROM_SUPERCLASS, fAddUnimplementedConstructors);
actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_CONSTRUCTOR_USING_FIELDS, fGenerateConstructorUsingFields);
actionBar.setGlobalActionHandler(JdtActionConstants.ADD_JAVA_DOC_COMMENT, fAddJavaDocStub);
actionBar.setGlobalActionHandler(JdtActionConstants.EXTERNALIZE_STRINGS, fExternalizeStrings);
actionBar.setGlobalActionHandler(JdtActionConstants.FIND_STRINGS_TO_EXTERNALIZE, fFindStringsToExternalize);
actionBar.setGlobalActionHandler(JdtActionConstants.ORGANIZE_IMPORTS, fOrganizeImports);
actionBar.setGlobalActionHandler(JdtActionConstants.SORT_MEMBERS, fSortMembers);
actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_WINDOWS, fConvertToWindows);
actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_UNIX, fConvertToUNIX);
actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_MAC, fConvertToMac);
if (!isEditorOwner()) {
// editor provides its own implementation of these actions.
actionBar.setGlobalActionHandler(IWorkbenchActionConstants.BOOKMARK, fAddBookmark);
actionBar.setGlobalActionHandler(IWorkbenchActionConstants.ADD_TASK, fAddTaskAction);
}
}
private int addAction(IMenuManager menu, IAction action) {
if (action != null && action.isEnabled()) {
menu.add(action);
return 1;
}
return 0;
}
private int addEditorAction(IMenuManager menu, String actionID) {
if (fEditor == null)
return 0;
IAction action= fEditor.getAction(actionID);
if (action == null)
return 0;
if (action instanceof IUpdate)
((IUpdate)action).update();
if (action.isEnabled()) {
menu.add(action);
return 1;
}
return 0;
}
private boolean isEditorOwner() {
return fEditor != null;
}
}
|
47,332 |
Bug 47332 Assertion failed in GetterSetter
|
20011121 1. create getter on this code public class InstanceCount { private String fName; private int fValue; /** * @param name * @param package1 * @param value */ public InstanceCount(String typeName, int value) { super(); fName= typeName; fValue= value; } public static InstanceCount[] deserialize(String str) { ArrayList entries= new ArrayList(); StringTokenizer tok= new StringTokenizer(str, ":\n"); //$NON-NLS-1$ while (tok.hasMoreTokens()) { String name= tok.nextToken(); String count= tok.nextToken(); InstanceCount entry= new InstanceCount(name, Integer.parseInt(count)); entries.add(entry); } return (InstanceCount[]) entries.toArray(new InstanceCount[entries.size()]); } } org.eclipse.jface.util.Assert$AssertionFailedException: null argument; at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.jface.util.Assert$AssertionFailedException.<init>(Assert.java:54) at org.eclipse.jface.util.Assert.isNotNull(Assert.java:139) at org.eclipse.jface.util.Assert.isNotNull(Assert.java) at org.eclipse.jface.viewers.AbstractTreeViewer.reveal(AbstractTreeViewer.java:1233) at org.eclipse.jdt.ui.actions.AddGetterSetterAction$GetterSetterTreeSelectionDialog.createDialogArea(AddGetterSetterAction.java:972) at org.eclipse.jface.dialogs.Dialog.createContents(Dialog.java:573) at org.eclipse.jface.window.Window.create(Window.java:305) at org.eclipse.jface.dialogs.Dialog.create(Dialog.java:883) at org.eclipse.ui.dialogs.SelectionStatusDialog.create(SelectionStatusDialog.java:143) at org.eclipse.ui.dialogs.CheckedTreeSelectionDialog.access$superCreate(CheckedTreeSelectionDialog.java:215) at org.eclipse.ui.dialogs.CheckedTreeSelectionDialog.access$0(CheckedTreeSelectionDialog.java:214) at org.eclipse.ui.dialogs.CheckedTreeSelectionDialog$1.run(CheckedTreeSelectionDialog.java:240) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java) at org.eclipse.ui.dialogs.CheckedTreeSelectionDialog.create(CheckedTreeSelectionDialog.java:238) at org.eclipse.jface.window.Window.open(Window.java:555) at org.eclipse.ui.dialogs.CheckedTreeSelectionDialog.open(CheckedTreeSelectionDialog.java:209) at org.eclipse.jdt.ui.actions.AddGetterSetterAction.run(AddGetterSetterAction.java:255) at org.eclipse.jdt.ui.actions.AddGetterSetterAction.run(AddGetterSetterAction.java:175) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:194) 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:466) 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
|
781af08
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T11:02:10Z | 2003-11-24T10:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/AddGetterSetterAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
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.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.text.IRewriteTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.internal.corext.codemanipulation.AddGetterSetterOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil;
import org.eclipse.jdt.internal.corext.codemanipulation.IRequestQuery;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.dialogs.SourceActionDialog;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
* Creates getter and setter methods for a type's fields. Opens a dialog
* with a list of fields for which a setter or getter can be generated.
* User is able to check or uncheck items before setters or getters
* are generated.
* <p>
* Will open the parent compilation unit in a Java editor. The result is
* unsaved, so the user can decide if the changes are acceptable.
* <p>
* The action is applicable to structured selections containing elements
* of type <code>IField</code> or <code>IType</code>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class AddGetterSetterAction extends SelectionDispatchAction {
private boolean fSort;
private boolean fSynchronized;
private boolean fFinal;
private int fVisibility;
private boolean fGenerateComment;
private int fNumEntries;
private CompilationUnitEditor fEditor;
private static final String DIALOG_TITLE= ActionMessages.getString("AddGetterSetterAction.error.title"); //$NON-NLS-1$
/**
* Creates a new <code>AddGetterSetterAction</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 AddGetterSetterAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("AddGetterSetterAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("AddGetterSetterAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("AddGetterSetterAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GETTERSETTER_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public AddGetterSetterAction(CompilationUnitEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
setEnabled(SelectionConverter.getInputAsCompilationUnit(editor) != null);
fEditor.getEditorSite();
}
//---- Structured Viewer -----------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
public void selectionChanged(IStructuredSelection selection) {
try {
setEnabled(canEnable(selection));
} catch (JavaModelException e) {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
if (JavaModelUtil.filterNotPresentException(e))
JavaPlugin.log(e);
setEnabled(false);
}
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
public void run(IStructuredSelection selection) {
try {
IField[] selectedFields= getSelectedFields(selection);
if (canRunOn(selectedFields)){
run(selectedFields[0].getDeclaringType(), selectedFields, false);
return;
}
Object firstElement= selection.getFirstElement();
if (firstElement instanceof IType)
run((IType)firstElement, new IField[0], false);
else if (firstElement instanceof ICompilationUnit) {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=38500
IType type= ((ICompilationUnit) firstElement).findPrimaryType();
if (type.isInterface()) {
MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.getString("AddGetterSetterAction.interface_not_applicable")); //$NON-NLS-1$
return;
}
else
run(((ICompilationUnit) firstElement).findPrimaryType(), new IField[0], false);
}
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, ActionMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$
}
}
private boolean canEnable(IStructuredSelection selection) throws JavaModelException {
if (getSelectedFields(selection) != null)
return true;
if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType)) {
IType type= (IType) selection.getFirstElement();
// look if class: not cheap but done by all source generation actions
// disable locals until create method is supported by jdt.core (bug 44395)
return type.getCompilationUnit() != null && type.isClass() && !type.isLocal();
}
if ((selection.size() == 1) && (selection.getFirstElement() instanceof ICompilationUnit))
return true;
return false;
}
private static boolean canRunOn(IField[] fields) {
return fields != null && fields.length > 0;
}
private void resetNumEntries() {
fNumEntries= 0;
}
private void incNumEntries() {
fNumEntries++;
}
private void run(IType type, IField[] preselected, boolean editor) throws CoreException {
if (type.isInterface()) {
MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.getString("AddGetterSetterAction.interface_not_applicable")); //$NON-NLS-1$
return;
}
if (!ElementValidator.check(type, getShell(), DIALOG_TITLE, editor))
return;
if (!ActionUtil.isProcessable(getShell(), type))
return;
ILabelProvider lp= new AddGetterSetterLabelProvider();
resetNumEntries();
Map entries= createGetterSetterMapping(type);
if (entries.isEmpty()){
MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.getString("AddGettSetterAction.typeContainsNoFields.message")); //$NON-NLS-1$
return;
}
AddGetterSetterContentProvider cp= new AddGetterSetterContentProvider(entries);
GetterSetterTreeSelectionDialog dialog= new GetterSetterTreeSelectionDialog(getShell(), lp, cp, fEditor, type);
dialog.setSorter(new JavaElementSorter());
dialog.setTitle(DIALOG_TITLE);
String message= ActionMessages.getString("AddGetterSetterAction.dialog.label");//$NON-NLS-1$
dialog.setMessage(message);
dialog.setValidator(createValidator(fNumEntries));
dialog.setContainerMode(true);
dialog.setSize(60, 18);
dialog.setInput(type);
if (preselected.length > 0) {
dialog.setInitialSelections(preselected);
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=38400
cp.setPreselected(preselected[0]);
}
int dialogResult= dialog.open();
if (dialogResult == Window.OK) {
Object[] result= dialog.getResult();
if (result == null)
return;
fSort= dialog.getSortOrder();
fSynchronized= dialog.getSynchronized();
fFinal= dialog.getFinal();
fVisibility= dialog.getVisibilityModifier();
fGenerateComment= dialog.getGenerateComment();
IField[] getterFields, setterFields, getterSetterFields;
if (fSort) {
getterFields= getGetterFields(result);
setterFields= getSetterFields(result);
getterSetterFields= new IField[0];
}
else {
getterFields= getGetterOnlyFields(result);
setterFields= getSetterOnlyFields(result);
getterSetterFields= getGetterSetterFields(result);
}
IJavaElement elementPosition= dialog.getElementPosition();
generate(getterFields, setterFields, getterSetterFields, elementPosition);
}
}
private static class AddGetterSetterSelectionStatusValidator implements ISelectionStatusValidator {
private static int fEntries;
AddGetterSetterSelectionStatusValidator(int entries) {
fEntries= entries;
}
public IStatus validate(Object[] selection) {
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=38478
HashSet map= null;
if ((selection != null) && (selection.length > 1)) {
map= new HashSet(selection.length);
}
int count= 0;
for (int i = 0; i < selection.length; i++) {
try {
if (selection[i] instanceof GetterSetterEntry) {
Object key = selection[i];
IField getsetField= ((GetterSetterEntry) selection[i]).fField;
if (((GetterSetterEntry) selection[i]).fGetterEntry) {
if (!map.add(GetterSetterUtil.getGetterName(getsetField, null)))
return new StatusInfo(IStatus.WARNING, ActionMessages.getString("AddGetterSetterAction.error.duplicate_methods")); //$NON-NLS-1$
}
else {
key= createSignatureKey(GetterSetterUtil.getSetterName(getsetField, null), getsetField);
if (!map.add(key))
return new StatusInfo(IStatus.WARNING, ActionMessages.getString("AddGetterSetterAction.error.duplicate_methods")); //$NON-NLS-1$ }
}
count++;
}
} catch (JavaModelException e) {
}
}
if (count == 0)
return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
String message= ActionMessages.getFormattedString("AddGetterSetterAction.methods_selected", //$NON-NLS-1$
new Object[] { String.valueOf(count), String.valueOf(fEntries)} );
return new StatusInfo(IStatus.INFO, message);
}
}
/***
* Creates a key used for hashmaps for a method signature (gettersettername+arguments(fqn))
*/
private static String createSignatureKey(String methodName, IField field) throws JavaModelException {
StringBuffer buffer = new StringBuffer();
buffer.append(methodName);
String fieldType= field.getTypeSignature();
String signature= Signature.getSimpleName(Signature.toString(fieldType));
buffer.append("#"); //$NON-NLS-1$
buffer.append(signature);
return buffer.toString();
}
private static ISelectionStatusValidator createValidator(int entries) {
AddGetterSetterSelectionStatusValidator validator= new AddGetterSetterSelectionStatusValidator(entries);
return validator;
}
// returns a list of fields with setter entries checked
private static IField[] getSetterFields(Object[] result){
Collection list= new ArrayList(0);
Object each= null;
GetterSetterEntry entry= null;
for (int i = 0; i < result.length; i++) {
each= result[i];
if ((each instanceof GetterSetterEntry)){
entry= (GetterSetterEntry)each;
if (! entry.fGetterEntry) {
list.add(entry.fField);
}
}
}
return (IField[]) list.toArray(new IField[list.size()]);
}
// returns a list of fields with getter entries checked
private static IField[] getGetterFields(Object[] result){
Collection list= new ArrayList(0);
Object each= null;
GetterSetterEntry entry= null;
for (int i = 0; i < result.length; i++) {
each= result[i];
if ((each instanceof GetterSetterEntry)){
entry= (GetterSetterEntry)each;
if (entry.fGetterEntry) {
list.add(entry.fField);
}
}
}
return (IField[]) list.toArray(new IField[list.size()]);
}
// returns a list of fields with only getter entires checked
private static IField[] getGetterOnlyFields(Object[] result){
Collection list= new ArrayList(0);
Object each= null;
GetterSetterEntry entry= null;
boolean getterSet= false;
for (int i = 0; i < result.length; i++) {
each= result[i];
if ((each instanceof GetterSetterEntry)){
entry= (GetterSetterEntry)each;
if (entry.fGetterEntry) {
list.add(entry.fField);
getterSet= true;
}
if ((! entry.fGetterEntry) && (getterSet == true)) {
list.remove(entry.fField);
getterSet= false;
}
}
else
getterSet= false;
}
return (IField[]) list.toArray(new IField[list.size()]);
}
// returns a list of fields with only setter entries checked
private static IField[] getSetterOnlyFields(Object[] result){
Collection list= new ArrayList(0);
Object each= null;
GetterSetterEntry entry= null;
boolean getterSet= false;
for (int i = 0; i < result.length; i++) {
each= result[i];
if ((each instanceof GetterSetterEntry)){
entry= (GetterSetterEntry)each;
if (entry.fGetterEntry) {
getterSet= true;
}
if ((! entry.fGetterEntry) && (getterSet != true)) {
list.add(entry.fField);
getterSet= false;
}
}
else
getterSet= false;
}
return (IField[]) list.toArray(new IField[list.size()]);
}
// returns a list of fields with both entries checked
private static IField[] getGetterSetterFields(Object[] result){
Collection list= new ArrayList(0);
Object each= null;
GetterSetterEntry entry= null;
boolean getterSet= false;
for (int i = 0; i < result.length; i++) {
each= result[i];
if ((each instanceof GetterSetterEntry)){
entry= (GetterSetterEntry)each;
if (entry.fGetterEntry) {
getterSet= true;
}
if ((! entry.fGetterEntry) && (getterSet == true)) {
list.add(entry.fField);
getterSet= false;
}
}
else
getterSet= false;
}
return (IField[]) list.toArray(new IField[list.size()]);
}
private void generate(IField[] getterFields, IField[] setterFields, IField[] getterSetterFields, IJavaElement elementPosition) throws CoreException{
if (getterFields.length == 0 && setterFields.length == 0 && getterSetterFields.length == 0)
return;
ICompilationUnit cu= null;
if (getterFields.length != 0)
cu= getterFields[0].getCompilationUnit();
else if (setterFields.length != 0)
cu= setterFields[0].getCompilationUnit();
else
cu= getterSetterFields[0].getCompilationUnit();
//open the editor, forces the creation of a working copy
IEditorPart editor= EditorUtility.openInEditor(cu);
IField[] workingCopyGetterFields= getWorkingCopyFields(getterFields);
IField[] workingCopySetterFields= getWorkingCopyFields(setterFields);
IField[] workingCopyGetterSetterFields= getWorkingCopyFields(getterSetterFields);
if (elementPosition != null)
elementPosition= JavaModelUtil.toWorkingCopy(elementPosition);
if (workingCopyGetterFields != null && workingCopySetterFields != null && workingCopyGetterSetterFields != null)
run(workingCopyGetterFields, workingCopySetterFields, workingCopyGetterSetterFields, editor, elementPosition);
}
//---- Java Editior --------------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
public void selectionChanged(ITextSelection selection) {
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
public void run(ITextSelection selection) {
try {
IJavaElement input= SelectionConverter.getInput(fEditor);
if (!ActionUtil.isProcessable(getShell(), input))
return;
IJavaElement[] elements= SelectionConverter.codeResolve(fEditor);
if (elements.length == 1 && (elements[0] instanceof IField)) {
IField field= (IField)elements[0];
run(field.getDeclaringType(), new IField[] {field}, true);
return;
}
IJavaElement element= SelectionConverter.getElementAtOffset(fEditor);
if (element != null){
IType type= (IType)element.getAncestor(IJavaElement.TYPE);
if (type != null) {
if (type.getFields().length > 0){
run(type, new IField[0], true);
return;
}
}
}
MessageDialog.openInformation(getShell(), DIALOG_TITLE,
ActionMessages.getString("AddGetterSetterAction.not_applicable")); //$NON-NLS-1$
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, ActionMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$
}
}
//---- Helpers -------------------------------------------------------------------
private void run(IField[] getterFields, IField[] setterFields, IField[] getterSetterFields, IEditorPart editor, IJavaElement elementPosition) {
IRewriteTarget target= (IRewriteTarget) editor.getAdapter(IRewriteTarget.class);
if (target != null) {
target.beginCompoundChange();
}
try {
AddGetterSetterOperation op= createAddGetterSetterOperation(getterFields, setterFields, getterSetterFields, elementPosition);
setOperationStatusFields(op);
IRunnableContext context= JavaPlugin.getActiveWorkbenchWindow();
if (context == null) {
context= new BusyIndicatorRunnableContext();
}
context.run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] createdMethods= op.getCreatedAccessors();
if (createdMethods.length > 0) {
EditorUtility.revealInEditor(editor, createdMethods[0]);
}
} catch (InvocationTargetException e) {
String message= ActionMessages.getString("AddGetterSetterAction.error.actionfailed"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, message);
} catch (InterruptedException e) {
// operation cancelled
} finally {
if (target != null) {
target.endCompoundChange();
}
}
}
private void setOperationStatusFields(AddGetterSetterOperation op) {
// Set the status fields corresponding to the visibility and modifiers set
op.setSort(fSort);
op.setVisibility(fVisibility);
op.setSynchronized(fSynchronized);
op.setFinal(fFinal);
}
private AddGetterSetterOperation createAddGetterSetterOperation(IField[] getterFields, IField[] setterFields, IField[] getterSetterFields, IJavaElement elementPosition) {
IRequestQuery skipSetterForFinalQuery= skipSetterForFinalQuery();
IRequestQuery skipReplaceQuery= skipReplaceQuery();
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
settings.createComments= fGenerateComment;
return new AddGetterSetterOperation(getterFields, setterFields, getterSetterFields, settings, skipSetterForFinalQuery, skipReplaceQuery, elementPosition);
}
private IRequestQuery skipSetterForFinalQuery() {
return new IRequestQuery() {
public int doQuery(IMember field) {
// Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=19367
int[] returnCodes= {IRequestQuery.YES, IRequestQuery.YES_ALL, IRequestQuery.NO, IRequestQuery.CANCEL};
String[] options= {IDialogConstants.YES_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL};
String fieldName= JavaElementLabels.getElementLabel(field, 0);
String formattedMessage= ActionMessages.getFormattedString("AddGetterSetterAction.SkipSetterForFinalDialog.message", fieldName); //$NON-NLS-1$
return showQueryDialog(formattedMessage, options, returnCodes);
}
};
}
private IRequestQuery skipReplaceQuery() {
return new IRequestQuery() {
public int doQuery(IMember method) {
int[] returnCodes= {IRequestQuery.YES, IRequestQuery.NO, IRequestQuery.YES_ALL, IRequestQuery.CANCEL};
String skipLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.skip.label"); //$NON-NLS-1$
String replaceLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.replace.label"); //$NON-NLS-1$
String skipAllLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.skipAll.label"); //$NON-NLS-1$
String[] options= { skipLabel, replaceLabel, skipAllLabel, IDialogConstants.CANCEL_LABEL};
String methodName= JavaElementLabels.getElementLabel(method, JavaElementLabels.M_PARAMETER_TYPES);
String formattedMessage= ActionMessages.getFormattedString("AddGetterSetterAction.SkipExistingDialog.message", methodName); //$NON-NLS-1$
return showQueryDialog(formattedMessage, options, returnCodes);
}
};
}
private int showQueryDialog(final String message, final String[] buttonLabels, int[] returnCodes) {
final Shell shell= getShell();
if (shell == null) {
JavaPlugin.logErrorMessage("AddGetterSetterAction.showQueryDialog: No active shell found"); //$NON-NLS-1$
return IRequestQuery.CANCEL;
}
final int[] result= { Window.CANCEL };
shell.getDisplay().syncExec(new Runnable() {
public void run() {
String title= ActionMessages.getString("AddGetterSetterAction.QueryDialog.title"); //$NON-NLS-1$
MessageDialog dialog= new MessageDialog(shell, title, null, message, MessageDialog.QUESTION, buttonLabels, 0);
result[0]= dialog.open();
}
});
int returnVal= result[0];
return returnVal < 0 ? IRequestQuery.CANCEL : returnCodes[returnVal];
}
/*
* Returns fields in the selection or <code>null</code> if the selection is
* empty or not valid.
*/
private IField[] getSelectedFields(IStructuredSelection selection) {
List elements= selection.toList();
int nElements= elements.size();
if (nElements > 0) {
IField[] res= new IField[nElements];
ICompilationUnit cu= null;
for (int i= 0; i < nElements; i++) {
Object curr= elements.get(i);
if (curr instanceof IField) {
IField fld= (IField)curr;
if (i == 0) {
// remember the cu of the first element
cu= fld.getCompilationUnit();
if (cu == null) {
return null;
}
} else if (!cu.equals(fld.getCompilationUnit())) {
// all fields must be in the same CU
return null;
}
try {
if (fld.getDeclaringType().isInterface()) {
// no setters/getters for interfaces
return null;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
return null;
}
res[i]= fld;
} else {
return null;
}
}
return res;
}
return null;
}
private static class AddGetterSetterLabelProvider extends JavaElementLabelProvider {
AddGetterSetterLabelProvider() {
}
/*
* @see ILabelProvider#getText(Object)
*/
public String getText(Object element) {
if (element instanceof GetterSetterEntry) {
GetterSetterEntry entry= (GetterSetterEntry) element;
try {
if (entry.fGetterEntry) {
return GetterSetterUtil.getGetterName(entry.fField, null) + "()"; //$NON-NLS-1$
} else {
return GetterSetterUtil.getSetterName(entry.fField, null) + '(' + Signature.getSimpleName(Signature.toString(entry.fField.getTypeSignature())) + ')';
}
} catch (JavaModelException e) {
return ""; //$NON-NLS-1$
}
}
return super.getText(element);
}
/*
* @see ILabelProvider#getImage(Object)
*/
public Image getImage(Object element) {
if (element instanceof GetterSetterEntry) {
int flags= 0;
try {
flags= ((GetterSetterEntry) element).fField.getFlags();
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
ImageDescriptor desc= JavaElementImageProvider.getFieldImageDescriptor(false, Flags.AccPublic);
int adornmentFlags= Flags.isStatic(flags) ? JavaElementImageDescriptor.STATIC : 0;
desc= new JavaElementImageDescriptor(desc, adornmentFlags, JavaElementImageProvider.BIG_SIZE);
return JavaPlugin.getImageDescriptorRegistry().get(desc);
}
return super.getImage(element);
}
}
/**
* @return map IField -> GetterSetterEntry[]
*/
private Map createGetterSetterMapping(IType type) throws JavaModelException{
IField[] fields= type.getFields();
Map result= new HashMap();
for (int i= 0; i < fields.length; i++) {
List l= new ArrayList(2);
if (GetterSetterUtil.getGetter(fields[i]) == null) {
l.add(new GetterSetterEntry(fields[i], true));
incNumEntries();
}
if (GetterSetterUtil.getSetter(fields[i]) == null) {
l.add(new GetterSetterEntry(fields[i], false));
incNumEntries();
}
if (! l.isEmpty())
result.put(fields[i], l.toArray(new GetterSetterEntry[l.size()]));
}
return result;
}
private void showError(String title, String message) {
MessageDialog.openError(getShell(), title, message);
}
private IField[] getWorkingCopyFields(IField[] fields) {
if (fields.length == 0)
return new IField[0];
ICompilationUnit cu= fields[0].getCompilationUnit();
ICompilationUnit workingCopyCU;
IField[] workingCopyFields;
if (cu.isWorkingCopy()) {
workingCopyCU= cu;
workingCopyFields= fields;
} else {
workingCopyCU= EditorUtility.getWorkingCopy(cu);
if (workingCopyCU == null) {
showError(ActionMessages.getString("JavaSourceAction.error.actionfailed"), DIALOG_TITLE); //$NON-NLS-1$
return null;
}
workingCopyFields= new IField[fields.length];
for (int i= 0; i < fields.length; i++) {
IField field= fields[i];
IField workingCopyField= (IField) JavaModelUtil.findMemberInCompilationUnit(workingCopyCU, field);
if (workingCopyField == null) {
showError(ActionMessages.getFormattedString("JavaSourceAction.error.fieldNotExisting", field.getElementName()), DIALOG_TITLE); //$NON-NLS-1$
return null;
}
workingCopyFields[i]= workingCopyField;
}
}
return workingCopyFields;
}
private static class AddGetterSetterContentProvider implements ITreeContentProvider {
private static final Object[] EMPTY= new Object[0];
private Viewer fViewer;
private Map fGetterSetterEntries; //IField -> Object[] (with 0 to 2 elements of type GetterSetterEntry)
private IField fPreselected;
public AddGetterSetterContentProvider(Map entries) {
fGetterSetterEntries= entries;
}
public IField getPreselected() {
return fPreselected;
}
public void setPreselected(IField preselected) {
fPreselected= preselected;
}
/*
* @see IContentProvider#inputChanged(Viewer, Object, Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
fViewer= viewer;
}
public Viewer getViewer() {
return fViewer;
}
/*
* @see ITreeContentProvider#getChildren(Object)
*/
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof IField)
return (Object[])fGetterSetterEntries.get(parentElement);
return EMPTY;
}
/*
* @see ITreeContentProvider#getParent(Object)
*/
public Object getParent(Object element) {
if (element instanceof IMember)
return ((IMember)element).getDeclaringType();
if (element instanceof GetterSetterEntry)
return ((GetterSetterEntry)element).fField;
return null;
}
/*
* @see ITreeContentProvider#hasChildren(Object)
*/
public boolean hasChildren(Object element) {
return getChildren(element).length > 0;
}
/*
* @see IStructuredContentProvider#getElements(Object)
*/
public Object[] getElements(Object inputElement) {
return fGetterSetterEntries.keySet().toArray();
}
/*
* @see IContentProvider#dispose()
*/
public void dispose() {
fGetterSetterEntries.clear();
fGetterSetterEntries= null;
}
}
private static class GetterSetterTreeSelectionDialog extends SourceActionDialog {
private IType fType;
private AddGetterSetterContentProvider fContentProvider;
private static final int SELECT_GETTERS_ID= IDialogConstants.CLIENT_ID + 1;
private static final int SELECT_SETTERS_ID= IDialogConstants.CLIENT_ID + 2;
private IDialogSettings fSettings;
private boolean fSortOrder;
private final String SETTINGS_SECTION= "AddGetterSetterDialog"; //$NON-NLS-1$
private final String SORT_ORDER= "SortOrdering"; //$NON-NLS-1$
public GetterSetterTreeSelectionDialog(Shell parent, ILabelProvider labelProvider, AddGetterSetterContentProvider contentProvider, CompilationUnitEditor editor, IType type) {
super(parent, labelProvider, contentProvider, editor, type);
fContentProvider= contentProvider;
fType= type;
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
IDialogSettings dialogSettings= JavaPlugin.getDefault().getDialogSettings();
fSettings= dialogSettings.getSection(SETTINGS_SECTION);
if (fSettings == null) {
fSettings= dialogSettings.addNewSection(SETTINGS_SECTION);
fSettings.put(SORT_ORDER, false); //$NON-NLS-1$
}
fSortOrder= fSettings.getBoolean(SORT_ORDER);
}
public boolean getSortOrder() {
return fSortOrder;
}
public void setSortOrder(boolean sort) {
if (fSortOrder != sort) {
fSortOrder= sort;
fSettings.put(SORT_ORDER, sort);
if (fContentProvider.fViewer != null) {
fContentProvider.fViewer.refresh();
}
}
}
private void createGetterSetterButtons(Composite buttonComposite) {
createButton(buttonComposite, SELECT_GETTERS_ID, ActionMessages.getString("GetterSetterTreeSelectionDialog.select_getters"), false); //$NON-NLS-1$
createButton(buttonComposite, SELECT_SETTERS_ID, ActionMessages.getString("GetterSetterTreeSelectionDialog.select_setters"), false); //$NON-NLS-1$
}
protected void buttonPressed(int buttonId) {
super.buttonPressed(buttonId);
switch(buttonId) {
case SELECT_GETTERS_ID: {
getTreeViewer().setCheckedElements(getGetterSetterElements(true));
updateOKStatus();
break;
}
case SELECT_SETTERS_ID: {
getTreeViewer().setCheckedElements(getGetterSetterElements(false));
updateOKStatus();
break;
}
}
}
protected Composite createEntryPtCombo(Composite composite) {
Composite entryComposite= super.createEntryPtCombo(composite);
addSortOrder(entryComposite);
addVisibilityAndModifiersChoices(entryComposite);
return entryComposite;
}
private Composite addSortOrder(Composite composite) {
Label label= new Label(composite, SWT.NONE);
label.setText(ActionMessages.getString("GetterSetterTreeSelectionDialog.sort_label")); //$NON-NLS-1$
GridData gd= new GridData(GridData.FILL_BOTH);
label.setLayoutData(gd);
final Combo combo= new Combo(composite, SWT.READ_ONLY);
combo.setItems(new String[]{ActionMessages.getString("GetterSetterTreeSelectionDialog.alpha_pair_sort"), //$NON-NLS-1$
ActionMessages.getString("GetterSetterTreeSelectionDialog.alpha_method_sort")}); //$NON-NLS-1$
final int methodIndex= 1; // Hard-coded. Change this if the list gets more complicated.
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=38400
int sort= getSortOrder() ? 1 : 0;
combo.setText(combo.getItem(sort));
gd= new GridData(GridData.FILL_BOTH);
combo.setLayoutData(gd);
combo.addSelectionListener(new SelectionAdapter(){
public void widgetSelected(SelectionEvent e) {
setSortOrder(combo.getSelectionIndex() == methodIndex);
}
});
return composite;
}
private Object[] getGetterSetterElements(boolean isGetter){
Object[] allFields= fContentProvider.getElements(null);
Set result= new HashSet();
for (int i = 0; i < allFields.length; i++) {
IField field= (IField)allFields[i];
GetterSetterEntry[] entries= getEntries(field);
for (int j = 0; j < entries.length; j++) {
AddGetterSetterAction.GetterSetterEntry entry= entries[j];
if (entry.fGetterEntry == isGetter)
result.add(entry);
}
}
return result.toArray();
}
private GetterSetterEntry[] getEntries(IField field) {
List result= Arrays.asList(fContentProvider.getChildren(field));
return (GetterSetterEntry[]) result.toArray(new GetterSetterEntry[result.size()]);
}
protected Composite createSelectionButtons(Composite composite) {
Composite buttonComposite= super.createSelectionButtons(composite);
GridLayout layout = new GridLayout();
buttonComposite.setLayout(layout);
createGetterSetterButtons(buttonComposite);
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 1;
return buttonComposite;
}
/*
* @see Dialog#createDialogArea(Composite)
*/
protected Control createDialogArea(Composite parent) {
Control control= super.createDialogArea(parent);
applyDialogFont(control);
try {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=38400
getTreeViewer().setExpandedElements(fType.getFields());
getTreeViewer().reveal(fContentProvider.getPreselected());
getTreeViewer().refresh();
} catch (JavaModelException e) {
}
return control;
}
}
private static class GetterSetterEntry {
public final IField fField;
public final boolean fGetterEntry;
GetterSetterEntry(IField field, boolean isGetterEntry){
fField= field;
fGetterEntry= isGetterEntry;
}
}
}
|
46,875 |
Bug 46875 [typing] Tabs are messed up
|
When I type code that has string literals in it, and press enter to move the string literal to the next line, the tab logic seems strange. e.g. String twoLines = "System Contains Many Defects,Systemet innehaller manga fel\n"+"Stories Are Too Complicated,Stories ar for komplicerade"; Move the cursor after + and press enter. It somehow moves the new line to column 0, while I'd expect it to align with the first line. If you try this with a single string, the bug will still be seen. Interestingly, when I am within a method's parantheses, the behavior is different. e.g. assertEquals( "converted data", "Systemet+innehaller+manga+fel|Stories+ar+for+komplicerade",convertedData .toString() ); Note, the two lines within have a single tab each. Now position the cursor on convertedData and press enter - while I'd expect it to line up with the previous line (two tabs), the IDE adds three tabs. Now here's the one which really annoys me: assertEquals( There is one tab before assertEquals. Press enter after the paranthesis. Three tabs are inexplicably put in. I would expect only two. I am assuming these are bugs as previous releases had the right behavior. Regards, Somik
|
resolved fixed
|
ee1aa7e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T11:05:01Z | 2003-11-18T21:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaStringAutoIndentStrategy.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultAutoIndentStrategy;
import org.eclipse.jface.text.DocumentCommand;
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.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.texteditor.ITextEditorExtension3;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Auto indent strategy for java strings
*/
public class JavaStringAutoIndentStrategy extends DefaultAutoIndentStrategy {
private String fPartitioning;
/**
* The input string doesn't contain any line delimiter.
*
* @param inputString the given input string
* @return the displayable string.
*/
private String displayString(String inputString, String indentation, String delimiter) {
int length = inputString.length();
StringBuffer buffer = new StringBuffer(length);
java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(inputString, "\n\r", true); //$NON-NLS-1$
while (tokenizer.hasMoreTokens()){
String token = tokenizer.nextToken();
if (token.equals("\r")) { //$NON-NLS-1$
buffer.append("\\r"); //$NON-NLS-1$
if (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();
if (token.equals("\n")) { //$NON-NLS-1$
buffer.append("\\n"); //$NON-NLS-1$
buffer.append("\" + " + delimiter); //$NON-NLS-1$
buffer.append(indentation);
buffer.append("\""); //$NON-NLS-1$
continue;
} else {
buffer.append("\" + " + delimiter); //$NON-NLS-1$
buffer.append(indentation);
buffer.append("\""); //$NON-NLS-1$
}
} else {
continue;
}
} else if (token.equals("\n")) { //$NON-NLS-1$
buffer.append("\\n"); //$NON-NLS-1$
buffer.append("\" + " + delimiter); //$NON-NLS-1$
buffer.append(indentation);
buffer.append("\""); //$NON-NLS-1$
continue;
}
StringBuffer tokenBuffer = new StringBuffer();
for (int i = 0; i < token.length(); i++){
char c = token.charAt(i);
switch (c) {
case '\r' :
tokenBuffer.append("\\r"); //$NON-NLS-1$
break;
case '\n' :
tokenBuffer.append("\\n"); //$NON-NLS-1$
break;
case '\b' :
tokenBuffer.append("\\b"); //$NON-NLS-1$
break;
case '\t' :
// keep tabs verbatim
tokenBuffer.append("\t"); //$NON-NLS-1$
break;
case '\f' :
tokenBuffer.append("\\f"); //$NON-NLS-1$
break;
case '\"' :
tokenBuffer.append("\\\""); //$NON-NLS-1$
break;
case '\'' :
tokenBuffer.append("\\'"); //$NON-NLS-1$
break;
case '\\' :
tokenBuffer.append("\\\\"); //$NON-NLS-1$
break;
default :
tokenBuffer.append(c);
}
}
buffer.append(tokenBuffer);
}
return buffer.toString();
}
/**
* Creates a new Java string auto indent strategy for the given document partitioning.
*
* @param partitioning the document partitioning
*/
public JavaStringAutoIndentStrategy(String partitioning) {
super();
fPartitioning= partitioning;
}
private boolean isLineDelimiter(IDocument document, String text) {
String[] delimiters= document.getLegalLineDelimiters();
if (delimiters != null)
return TextUtilities.equals(delimiters, text) > -1;
return false;
}
private String getLineIndentation(IDocument document, int offset) throws BadLocationException {
// find start of line
int adjustedOffset= (offset == document.getLength() ? offset - 1 : offset);
IRegion line= document.getLineInformationOfOffset(adjustedOffset);
int start= line.getOffset();
// find white spaces
int end= findEndOfWhiteSpace(document, start, offset);
return document.get(start, end - start);
}
private String getModifiedText(String string, String indentation, String delimiter) throws BadLocationException {
return displayString(string, indentation, delimiter);
}
private void javaStringIndentAfterNewLine(IDocument document, DocumentCommand command) throws BadLocationException {
ITypedRegion partition= TextUtilities.getPartition(document, fPartitioning, command.offset);
int offset= partition.getOffset();
int length= partition.getLength();
if (command.offset == offset)
return;
if (command.offset == offset + length && document.getChar(offset + length - 1) == '\"')
return;
String indentation= getLineIndentation(document, command.offset);
String delimiter= TextUtilities.getDefaultLineDelimiter(document);
IRegion line= document.getLineInformationOfOffset(offset);
String string= document.get(line.getOffset(), offset - line.getOffset());
if (string.trim().length() != 0)
indentation += String.valueOf("\t\t"); //$NON-NLS-1$
IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore();
if (isLineDelimiter(document, command.text))
command.text= "\" +" + command.text + indentation + "\""; //$NON-NLS-1$//$NON-NLS-2$
else if (command.text.length() > 1 && preferenceStore.getBoolean(PreferenceConstants.EDITOR_ESCAPE_STRINGS))
command.text= getModifiedText(command.text, indentation, delimiter);
}
private boolean isSmartMode() {
IWorkbenchPage page= JavaPlugin.getActivePage();
if (page != null) {
IEditorPart part= page.getActiveEditor();
if (part instanceof ITextEditorExtension3) {
ITextEditorExtension3 extension= (ITextEditorExtension3) part;
return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT;
}
}
return false;
}
/*
* @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(IDocument, DocumentCommand)
*/
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
try {
if (command.length != 0 || command.text == null)
return;
IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore();
if (preferenceStore.getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS) && isSmartMode())
javaStringIndentAfterNewLine(document, command);
} catch (BadLocationException e) {
}
}
}
|
46,763 |
Bug 46763 Introduce Factory: uses NLS key that doesn't exist
|
N20031114 Key use: Refactoring.syntax_error Please use the NLS search facility to make sure your NLS stuff is correct. To enable NLS search go to Search Dialog->Customize and check NLS page.
|
resolved fixed
|
a45c3e5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T17:02:12Z | 2003-11-17T11:53:20Z |
org.eclipse.jdt.ui/core
| |
46,763 |
Bug 46763 Introduce Factory: uses NLS key that doesn't exist
|
N20031114 Key use: Refactoring.syntax_error Please use the NLS search facility to make sure your NLS stuff is correct. To enable NLS search go to Search Dialog->Customize and check NLS page.
|
resolved fixed
|
a45c3e5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T17:02:12Z | 2003-11-17T11:53:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/IntroduceFactoryRefactoring.java
| |
46,763 |
Bug 46763 Introduce Factory: uses NLS key that doesn't exist
|
N20031114 Key use: Refactoring.syntax_error Please use the NLS search facility to make sure your NLS stuff is correct. To enable NLS search go to Search Dialog->Customize and check NLS page.
|
resolved fixed
|
a45c3e5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T17:02:12Z | 2003-11-17T11:53:20Z |
org.eclipse.jdt.ui/ui
| |
46,763 |
Bug 46763 Introduce Factory: uses NLS key that doesn't exist
|
N20031114 Key use: Refactoring.syntax_error Please use the NLS search facility to make sure your NLS stuff is correct. To enable NLS search go to Search Dialog->Customize and check NLS page.
|
resolved fixed
|
a45c3e5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T17:02:12Z | 2003-11-17T11:53:20Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/IntroduceFactoryWizard.java
| |
46,763 |
Bug 46763 Introduce Factory: uses NLS key that doesn't exist
|
N20031114 Key use: Refactoring.syntax_error Please use the NLS search facility to make sure your NLS stuff is correct. To enable NLS search go to Search Dialog->Customize and check NLS page.
|
resolved fixed
|
a45c3e5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-24T17:02:12Z | 2003-11-17T11:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/ChangeTypeAction.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.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.internal.corext.refactoring.base.Refactoring;
import org.eclipse.jdt.internal.corext.refactoring.structure.ChangeTypeRefactoring;
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.refactoring.ChangeTypeWizard;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
/**
* @author tip
*/
public class ChangeTypeAction extends SelectionDispatchAction {
private CompilationUnitEditor fEditor;
private String fDialogMessageTitle;
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public ChangeTypeAction(CompilationUnitEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
setEnabled(SelectionConverter.getInputAsCompilationUnit(fEditor) != null);
}
/**
* Creates a new <code>ChangeTypeAction</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 ChangeTypeAction(IWorkbenchSite site) {
super(site);
setText(RefactoringMessages.getString("ChangeTypeAction.label")); //$NON-NLS-1$
setToolTipText(RefactoringMessages.getString("ChangeTypeAction.tooltipText")); //$NON-NLS-1$
setDescription(RefactoringMessages.getString("ChangeTypeAction.description")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.CHANGE_TYPE_ACTION);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
public void run(ITextSelection selection) {
if (!ActionUtil.isProcessable(getShell(), fEditor))
return;
try{
ChangeTypeRefactoring refactoring= createRefactoring(SelectionConverter.getInputAsCompilationUnit(fEditor), selection);
if (refactoring == null)
return;
new RefactoringStarter().activate(refactoring, createWizard(refactoring), getShell(), fDialogMessageTitle, false);
} catch (CoreException e){
ExceptionHandler.handle(e, fDialogMessageTitle, RefactoringMessages.getString("ChangeTypeAction.exception")); //$NON-NLS-1$
}
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
public void selectionChanged(ITextSelection selection) {
setEnabled(checkEnabled(selection));
}
public void selectionChanged(IStructuredSelection selection) {
if (canEnable(selection)){
setEnabled(true);
}
}
private boolean canEnable(IStructuredSelection selection) {
if (selection.size() == 1){
Object element= selection.getFirstElement();
if (element instanceof IMember){
return true;
}
}
return false;
}
public void run(IStructuredSelection selection) {
if (canEnable(selection)){
Object element= selection.getFirstElement();
if (element instanceof IMember){
IMember member= (IMember)element;
try {
ISourceRange range= member.getNameRange();
ICompilationUnit icu= member.getCompilationUnit();
ITextSelection textSelection= new TextSelection(range.getOffset(), range.getLength());
ChangeTypeRefactoring refactoring= createRefactoring(icu, textSelection);
if (refactoring == null)
return;
new RefactoringStarter().activate(refactoring, createWizard(refactoring), getShell(), fDialogMessageTitle, false);
} catch (CoreException e){
ExceptionHandler.handle(e, fDialogMessageTitle, RefactoringMessages.getString("ChangeTypeAction.exception")); //$NON-NLS-1$
}
}
}
}
private static ChangeTypeRefactoring createRefactoring(ICompilationUnit cunit, ITextSelection selection) throws CoreException {
return ChangeTypeRefactoring.create(cunit,
selection.getOffset(), selection.getLength());
}
private RefactoringWizard createWizard(ChangeTypeRefactoring refactoring) {
String pageTitle= RefactoringMessages.getString("ChangeTypeWizard.title"); //$NON-NLS-1$
return new ChangeTypeWizard(refactoring);
}
private boolean checkEnabled(ITextSelection selection) {
return fEditor != null && SelectionConverter.getInputAsCompilationUnit(fEditor) != null;
}
private RefactoringWizard createWizard(Refactoring refactoring) {
return new ChangeTypeWizard((ChangeTypeRefactoring)refactoring);
}
}
|
47,218 |
Bug 47218 NPE during rebuidling of Index [misc]
|
20031120 I got this one while self hosting off of the 4PM build on 1120 - not sure when as I only noticed when I shutdown. I had loaded the platform-ui module in and then immendiately loaded all other plugins from binaries. This didn't seem to affect anything so I don't think it needs to be addressed for M5. java.lang.NullPointerException at org.eclipse.jdt.internal.core.search.indexing.IndexManager.rebuildIndex (IndexManager.java:335) at org.eclipse.jdt.internal.core.search.indexing.IndexManager.getIndex (IndexManager.java:145) at org.eclipse.jdt.internal.core.search.IndexSelector.getIndexes (IndexSelector.java:162) at org.eclipse.jdt.internal.core.search.PatternSearchJob.execute (PatternSearchJob.java:67) at org.eclipse.jdt.internal.core.search.processing.JobManager.performConcurrentJob (JobManager.java:259) at org.eclipse.jdt.core.search.SearchEngine.searchAllTypeNames (SearchEngine.java:736) at org.eclipse.jdt.internal.corext.util.AllTypesCache.search (AllTypesCache.java:430) at org.eclipse.jdt.internal.corext.util.AllTypesCache$TypeCacher.doSearchTypes (AllTypesCache.java:132) at org.eclipse.jdt.internal.corext.util.AllTypesCache$TypeCacher.run (AllTypesCache.java:98)
|
resolved fixed
|
ecc4b16
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-27T22:21:58Z | 2003-11-21T13:06:40Z |
org.eclipse.jdt.ui/core
| |
47,218 |
Bug 47218 NPE during rebuidling of Index [misc]
|
20031120 I got this one while self hosting off of the 4PM build on 1120 - not sure when as I only noticed when I shutdown. I had loaded the platform-ui module in and then immendiately loaded all other plugins from binaries. This didn't seem to affect anything so I don't think it needs to be addressed for M5. java.lang.NullPointerException at org.eclipse.jdt.internal.core.search.indexing.IndexManager.rebuildIndex (IndexManager.java:335) at org.eclipse.jdt.internal.core.search.indexing.IndexManager.getIndex (IndexManager.java:145) at org.eclipse.jdt.internal.core.search.IndexSelector.getIndexes (IndexSelector.java:162) at org.eclipse.jdt.internal.core.search.PatternSearchJob.execute (PatternSearchJob.java:67) at org.eclipse.jdt.internal.core.search.processing.JobManager.performConcurrentJob (JobManager.java:259) at org.eclipse.jdt.core.search.SearchEngine.searchAllTypeNames (SearchEngine.java:736) at org.eclipse.jdt.internal.corext.util.AllTypesCache.search (AllTypesCache.java:430) at org.eclipse.jdt.internal.corext.util.AllTypesCache$TypeCacher.doSearchTypes (AllTypesCache.java:132) at org.eclipse.jdt.internal.corext.util.AllTypesCache$TypeCacher.run (AllTypesCache.java:98)
|
resolved fixed
|
ecc4b16
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-27T22:21:58Z | 2003-11-21T13:06:40Z |
extension/org/eclipse/jdt/internal/corext/util/AllTypesCache.java
| |
47,657 |
Bug 47657 Quick Assist Suggestion: add block to single-line then-statement [quick assist]
| null |
resolved fixed
|
7c3c43a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-28T10:08:04Z | 2003-11-27T19:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.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.ui.text.java.IInvocationContext;
import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
import org.eclipse.jdt.ui.text.java.IProblemLocation;
import org.eclipse.jdt.ui.text.java.IQuickAssistProcessor;
import org.eclipse.jdt.internal.corext.dom.ASTNodeConstants;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
/**
*/
public class QuickAssistProcessor implements IQuickAssistProcessor {
public QuickAssistProcessor() {
super();
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.correction.IAssistProcessor#hasAssists(org.eclipse.jdt.internal.ui.text.correction.IAssistContext)
*/
public boolean hasAssists(IInvocationContext context) throws CoreException {
ASTNode coveringNode= getCoveringNode(context);
if (coveringNode != null) {
return getCatchClauseToThrowsProposals(context, coveringNode, null)
|| getRenameLocalProposals(context, coveringNode, null)
|| getAssignToVariableProposals(context, coveringNode, null)
|| getUnWrapProposals(context, coveringNode, null)
|| getAssignParamToFieldProposals(context, coveringNode, null)
|| getJoinVariableProposals(context, coveringNode, null)
|| getAddFinallyProposals(context, coveringNode, null)
|| getAddElseProposals(context, coveringNode, null)
|| getSplitVariableProposals(context, coveringNode, null);
}
return false;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.correction.IAssistProcessor#getAssists(org.eclipse.jdt.internal.ui.text.correction.IAssistContext, org.eclipse.jdt.internal.ui.text.correction.IProblemLocation[])
*/
public IJavaCompletionProposal[] getAssists(IInvocationContext context, IProblemLocation[] locations) throws CoreException {
ASTNode coveringNode= getCoveringNode(context);
if (coveringNode != null) {
ArrayList resultingCollections= new ArrayList();
// quick assists that show up also if there is an error/warning
getRenameLocalProposals(context, coveringNode, resultingCollections);
if (locations == null || locations.length == 0) {
getCatchClauseToThrowsProposals(context, coveringNode, resultingCollections);
getAssignToVariableProposals(context, coveringNode, resultingCollections);
getAssignParamToFieldProposals(context, coveringNode, resultingCollections);
getUnWrapProposals(context, coveringNode, resultingCollections);
getSplitVariableProposals(context, coveringNode, resultingCollections);
getJoinVariableProposals(context, coveringNode, resultingCollections);
getAddFinallyProposals(context, coveringNode, resultingCollections);
getAddElseProposals(context, coveringNode, resultingCollections);
}
return (IJavaCompletionProposal[]) resultingCollections.toArray(new IJavaCompletionProposal[resultingCollections.size()]);
}
return null;
}
private boolean getJoinVariableProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) throws CoreException {
ASTNode parent= node.getParent();
if (!(parent instanceof VariableDeclarationFragment)) {
return false;
}
VariableDeclarationFragment fragment= (VariableDeclarationFragment) parent;
IVariableBinding binding= fragment.resolveBinding();
if (fragment.getInitializer() != null || binding == null || binding.isField()) {
return false;
}
if (!(fragment.getParent() instanceof VariableDeclarationStatement)) {
return false;
}
VariableDeclarationStatement statement= (VariableDeclarationStatement) fragment.getParent();
SimpleName[] names= LinkedNodeFinder.perform(statement.getParent(), binding);
if (names.length <= 1 && names[0] != fragment.getName()) {
return false;
}
SimpleName firstAccess= names[1];
if (!(firstAccess.getParent() instanceof Assignment)) {
return false;
}
Assignment assignment= (Assignment) firstAccess.getParent();
if (assignment.getLeftHandSide() != firstAccess) {
return false;
}
ASTNode assignParent= assignment.getParent();
if (!(assignParent instanceof ExpressionStatement || assignParent instanceof ForStatement && ((ForStatement) assignParent).initializers().contains(assignment))) {
return false;
}
if (resultingCollections == null) {
return true;
}
ASTRewrite rewrite= new ASTRewrite(statement.getParent());
AST ast= statement.getAST();
String label= CorrectionMessages.getString("QuickAssistProcessor.joindeclaration.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
Expression placeholder= (Expression) rewrite.createMove(assignment.getRightHandSide());
rewrite.markAsInsert(fragment, ASTNodeConstants.INITIALIZER, placeholder, null);
if (assignParent instanceof ExpressionStatement) {
int statementParent= assignParent.getParent().getNodeType();
if (statementParent == ASTNode.IF_STATEMENT || statementParent == ASTNode.WHILE_STATEMENT || statementParent == ASTNode.DO_STATEMENT
|| statementParent == ASTNode.FOR_STATEMENT) {
Block block= ast.newBlock();
rewrite.markAsReplaced(assignParent, block);
} else {
rewrite.markAsRemoved(assignParent);
}
} else {
rewrite.markAsRemoved(assignment);
}
proposal.markAsSelection(rewrite, fragment.getName());
proposal.ensureNoModifications();
resultingCollections.add(proposal);
return true;
}
private boolean getSplitVariableProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) throws CoreException {
ASTNode parent= node.getParent();
if (!(parent instanceof VariableDeclarationFragment)) {
return false;
}
VariableDeclarationFragment fragment= (VariableDeclarationFragment) parent;
if (fragment.getInitializer() == null) {
return false;
}
Statement statement;
ASTNode fragParent= fragment.getParent();
if (fragParent instanceof VariableDeclarationStatement) {
statement= (VariableDeclarationStatement) fragParent;
} else if (fragParent instanceof VariableDeclarationExpression) {
statement= (Statement) fragParent.getParent();
} else {
return false;
}
// statement is ForStatement or VariableDeclarationStatement
ASTNode statementParent= statement.getParent();
int property= ASTNodeConstants.getPropertyOfNode(statement);
Object container= ASTNodeConstants.getNodeChild(statementParent, property);
if (!(container instanceof List)) {
return false;
}
List list= (List) container;
if (resultingCollections == null) {
return true;
}
ASTRewrite rewrite= new ASTRewrite(statement.getParent());
AST ast= statement.getAST();
String label= CorrectionMessages.getString("QuickAssistProcessor.splitdeclaration.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
Statement newStatement;
int insertIndex= list.indexOf(statement);
Expression placeholder= (Expression) rewrite.createMove(fragment.getInitializer());
Assignment assignment= ast.newAssignment();
assignment.setRightHandSide(placeholder);
assignment.setLeftHandSide(ast.newSimpleName(fragment.getName().getIdentifier()));
if (statement instanceof VariableDeclarationStatement) {
newStatement= ast.newExpressionStatement(assignment);
insertIndex+= 1; // add after declaration
} else {
rewrite.markAsReplaced(fragment.getParent(), assignment);
VariableDeclarationFragment newFrag= ast.newVariableDeclarationFragment();
newFrag.setName(ast.newSimpleName(fragment.getName().getIdentifier()));
newFrag.setExtraDimensions(fragment.getExtraDimensions());
VariableDeclarationExpression oldVarDecl= (VariableDeclarationExpression) fragParent;
VariableDeclarationStatement newVarDec= ast.newVariableDeclarationStatement(newFrag);
newVarDec.setType((Type) ASTNode.copySubtree(ast, oldVarDecl.getType()));
newVarDec.setModifiers(oldVarDecl.getModifiers());
newStatement= newVarDec;
}
rewrite.markAsInsertInOriginal(statementParent, property, newStatement, insertIndex, null);
proposal.ensureNoModifications();
resultingCollections.add(proposal);
return true;
}
private ASTNode getCoveringNode(IInvocationContext context) {
NodeFinder finder= new NodeFinder(context.getSelectionOffset(), context.getSelectionLength());
context.getASTRoot().accept(finder);
return finder.getCoveringNode();
}
private boolean getAssignToVariableProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) {
Statement statement= ASTResolving.findParentStatement(node);
if (!(statement instanceof ExpressionStatement)) {
return false;
}
ExpressionStatement expressionStatement= (ExpressionStatement) statement;
Expression expression= expressionStatement.getExpression();
if (expression.getNodeType() == ASTNode.ASSIGNMENT) {
return false; // too confusing and not helpful
}
ITypeBinding typeBinding= expression.resolveTypeBinding();
typeBinding= Bindings.normalizeTypeBinding(typeBinding);
if (typeBinding == null) {
return false;
}
if (resultingCollections == null) {
return true;
}
ICompilationUnit cu= context.getCompilationUnit();
AssignToVariableAssistProposal localProposal= new AssignToVariableAssistProposal(cu, AssignToVariableAssistProposal.LOCAL, expressionStatement, typeBinding, 2);
resultingCollections.add(localProposal);
ASTNode type= ASTResolving.findParentType(expression);
if (type != null) {
AssignToVariableAssistProposal fieldProposal= new AssignToVariableAssistProposal(cu, AssignToVariableAssistProposal.FIELD, expressionStatement, typeBinding, 1);
resultingCollections.add(fieldProposal);
}
return false;
}
private boolean getAssignParamToFieldProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) {
ASTNode parent= node.getParent();
if (!(parent instanceof SingleVariableDeclaration) || !(parent.getParent() instanceof MethodDeclaration)) {
return false;
}
SingleVariableDeclaration paramDecl= (SingleVariableDeclaration) parent;
IVariableBinding binding= paramDecl.resolveBinding();
MethodDeclaration methodDecl= (MethodDeclaration) parent.getParent();
if (binding == null || methodDecl.getBody() == null) {
return false;
}
ITypeBinding typeBinding= binding.getType();
if (typeBinding == null) {
return false;
}
if (resultingCollections != null) {
AssignToVariableAssistProposal fieldProposal= new AssignToVariableAssistProposal(context.getCompilationUnit(), paramDecl, typeBinding, 1);
resultingCollections.add(fieldProposal);
}
return true;
}
private boolean getAddFinallyProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) throws CoreException {
TryStatement tryStatement= ASTResolving.findParentTryStatement(node);
if (tryStatement == null || tryStatement.getFinally() != null) {
return false;
}
Statement statement= ASTResolving.findParentStatement(node);
if (tryStatement != statement && tryStatement.getBody() != statement) {
return false; // an node inside a catch or finally block
}
if (resultingCollections == null) {
return true;
}
ASTRewrite rewrite= new ASTRewrite(tryStatement);
AST ast= tryStatement.getAST();
Block finallyBody= ast.newBlock();
rewrite.markAsInsert(tryStatement, ASTNodeConstants.FINALLY, finallyBody, null);
String label= CorrectionMessages.getString("QuickAssistProcessor.addfinallyblock.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
proposal.ensureNoModifications();
resultingCollections.add(proposal);
return true;
}
private boolean getAddElseProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) throws CoreException {
Statement statement= ASTResolving.findParentStatement(node);
if (!(statement instanceof IfStatement)) {
return false;
}
IfStatement ifStatement= (IfStatement) statement;
if (ifStatement.getElseStatement() != null) {
return false;
}
if (resultingCollections == null) {
return true;
}
ASTRewrite rewrite= new ASTRewrite(statement);
AST ast= statement.getAST();
Block body= ast.newBlock();
rewrite.markAsInsert(ifStatement, ASTNodeConstants.ELSE_STATEMENT, body, null);
String label= CorrectionMessages.getString("QuickAssistProcessor.addelseblock.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
proposal.ensureNoModifications();
resultingCollections.add(proposal);
return true;
}
public static boolean getCatchClauseToThrowsProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) throws CoreException {
CatchClause catchClause= (CatchClause) ASTResolving.findAncestor(node, ASTNode.CATCH_CLAUSE);
if (catchClause == null) {
return false;
}
Statement statement= ASTResolving.findParentStatement(node);
if (statement != catchClause.getParent() && statement != catchClause.getBody()) {
return false; // selection is in a statement inside the body
}
Type type= catchClause.getException().getType();
if (!type.isSimpleType()) {
return false;
}
BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(catchClause);
if (!(bodyDeclaration instanceof MethodDeclaration)) {
return false;
}
if (resultingCollections == null) {
return true;
}
MethodDeclaration methodDeclaration= (MethodDeclaration) bodyDeclaration;
{
ASTRewrite rewrite= new ASTRewrite(methodDeclaration);
removeCatchBlock(rewrite, methodDeclaration, catchClause);
ITypeBinding binding= type.resolveBinding();
if (binding == null || isNotYetThrown(binding, methodDeclaration.thrownExceptions())) {
Name name= ((SimpleType) type).getName();
Name newName= (Name) ASTNode.copySubtree(catchClause.getAST(), name);
rewrite.markAsInsertBeforeOriginal(methodDeclaration, ASTNodeConstants.THROWN_EXCEPTIONS, newName, null, null);
}
String label= CorrectionMessages.getString("QuickAssistProcessor.catchclausetothrows.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 4, image);
proposal.ensureNoModifications();
resultingCollections.add(proposal);
}
{
ASTRewrite rewrite= new ASTRewrite(methodDeclaration);
removeCatchBlock(rewrite, methodDeclaration, catchClause);
String label= CorrectionMessages.getString("QuickAssistProcessor.removecatchclause.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image);
proposal.ensureNoModifications();
resultingCollections.add(proposal);
}
return true;
}
private static void removeCatchBlock(ASTRewrite rewrite, MethodDeclaration methodDeclaration, CatchClause catchClause) {
TryStatement tryStatement= (TryStatement) catchClause.getParent();
if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null) {
rewrite.markAsRemoved(catchClause);
} else {
List statements= tryStatement.getBody().statements();
if (statements.size() > 0) {
ASTNode placeholder= rewrite.collapseNodes(statements, 0, statements.size());
rewrite.markAsReplaced(tryStatement, rewrite.createCopy(placeholder));
} else {
rewrite.markAsRemoved(tryStatement);
}
}
}
private static boolean isNotYetThrown(ITypeBinding binding, List thrownExcpetions) {
for (int i= 0; i < thrownExcpetions.size(); i++) {
Name name= (Name) thrownExcpetions.get(i);
ITypeBinding elem= (ITypeBinding) name.resolveBinding();
if (elem != null) {
if (Bindings.isSuperType(elem, binding)) { // existing exception is base class of new
return false;
}
}
}
return true;
}
private boolean getRenameLocalProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) {
if (!(node instanceof SimpleName)) {
return false;
}
SimpleName name= (SimpleName) node;
IBinding binding= name.resolveBinding();
if (binding == null || binding.getKind() == IBinding.PACKAGE) {
return false;
}
if (resultingCollections == null) {
return true;
}
LinkedNamesAssistProposal proposal= new LinkedNamesAssistProposal(context.getCompilationUnit(), name);
resultingCollections.add(proposal);
return true;
}
private ASTNode getCopyOfInner(ASTRewrite rewrite, ASTNode statement) {
if (statement.getNodeType() == ASTNode.BLOCK) {
Block block= (Block) statement;
List innerStatements= block.statements();
int nStatements= innerStatements.size();
if (nStatements == 1) {
return rewrite.createCopy((ASTNode) innerStatements.get(0));
} else if (nStatements > 1) {
ASTNode placeholder= rewrite.collapseNodes(innerStatements, 0, nStatements);
return rewrite.createCopy(placeholder);
}
return null;
} else {
return rewrite.createCopy(statement);
}
}
private boolean getUnWrapProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) throws CoreException {
ASTNode outer= node;
Block block= null;
if (outer.getNodeType() == ASTNode.BLOCK) {
block= (Block) outer;
outer= block.getParent();
}
ASTNode body= null;
String label= null;
if (outer instanceof IfStatement) {
IfStatement ifStatement= (IfStatement) outer;
Statement elseBlock= ifStatement.getElseStatement();
if (elseBlock == null || ((elseBlock instanceof Block) && ((Block) elseBlock).statements().isEmpty())) {
body= ifStatement.getThenStatement();
}
label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.ifstatement"); //$NON-NLS-1$
} else if (outer instanceof WhileStatement) {
body=((WhileStatement) outer).getBody();
label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.whilestatement"); //$NON-NLS-1$
} else if (outer instanceof ForStatement) {
body=((ForStatement) outer).getBody();
label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.forstatement"); //$NON-NLS-1$
} else if (outer instanceof DoStatement) {
body=((DoStatement) outer).getBody();
label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.dostatement"); //$NON-NLS-1$
} else if (outer instanceof TryStatement) {
TryStatement tryStatement= (TryStatement) outer;
if (tryStatement.catchClauses().isEmpty()) {
body= tryStatement.getBody();
}
label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.trystatement"); //$NON-NLS-1$
} else if (outer instanceof AnonymousClassDeclaration) {
List decls= ((AnonymousClassDeclaration) outer).bodyDeclarations();
for (int i= 0; i < decls.size(); i++) {
ASTNode elem= (ASTNode) decls.get(i);
if (elem instanceof MethodDeclaration) {
Block curr= ((MethodDeclaration) elem).getBody();
if (curr != null && !curr.statements().isEmpty()) {
if (body != null) {
return false;
}
body= curr;
}
} else if (elem instanceof TypeDeclaration) {
return false;
}
}
label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.anonymous"); //$NON-NLS-1$
outer= ASTResolving.findParentStatement(outer);
} else if (outer instanceof Block) {
// -> a block in a block
body= block;
outer= block;
label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.block"); //$NON-NLS-1$
} else if (outer instanceof ParenthesizedExpression) {
ParenthesizedExpression expression= (ParenthesizedExpression) outer;
body= expression.getExpression();
label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.parenthesis"); //$NON-NLS-1$
} else if (outer instanceof MethodInvocation) {
MethodInvocation invocation= (MethodInvocation) outer;
if (invocation.arguments().size() == 1) {
body= (ASTNode) invocation.arguments().get(0);
if (invocation.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
int kind= body.getNodeType();
if (kind != ASTNode.ASSIGNMENT && kind != ASTNode.PREFIX_EXPRESSION && kind != ASTNode.POSTFIX_EXPRESSION
&& kind != ASTNode.METHOD_INVOCATION && kind != ASTNode.SUPER_METHOD_INVOCATION) {
body= null;
}
}
label= CorrectionMessages.getString("QuickAssistProcessor.unwrap.methodinvocation"); //$NON-NLS-1$
}
}
if (body == null) {
return false;
}
ASTRewrite rewrite= new ASTRewrite(outer.getParent());
ASTNode inner= getCopyOfInner(rewrite, body);
if (inner == null) {
return false;
}
if (resultingCollections == null) {
return true;
}
rewrite.markAsReplaced(outer, inner);
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
proposal.ensureNoModifications();
resultingCollections.add(proposal);
return true;
}
}
|
47,678 |
Bug 47678 Duplicate parameter prefixes in auto-generated JavaDoc comments
|
Eclipse 3.0 M5. For the variable type 'Parameters' in 'Preferences/Java/Code Generation/Conventions for variable names' select a non-empty Prefix, e.g. p_. If you now add a JavaDoc comment to a method that has a parameter list with already p_-prefixed names, the @param starts with p_p_ what obviously is wrong.
|
resolved fixed
|
b644784
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-28T10:49:11Z | 2003-11-27T21:53:20Z |
org.eclipse.jdt.ui/core
| |
47,678 |
Bug 47678 Duplicate parameter prefixes in auto-generated JavaDoc comments
|
Eclipse 3.0 M5. For the variable type 'Parameters' in 'Preferences/Java/Code Generation/Conventions for variable names' select a non-empty Prefix, e.g. p_. If you now add a JavaDoc comment to a method that has a parameter list with already p_-prefixed names, the @param starts with p_p_ what obviously is wrong.
|
resolved fixed
|
b644784
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-28T10:49:11Z | 2003-11-27T21:53:20Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java
| |
47,694 |
Bug 47694 Local rename jumps to first occurence of name
|
plugin-export/I20031126.from20031127_1934 In QuickAssistProcessor, go to method 'getRenameLocalProposals', set the cursor in the name and invoke 'local rename'. The editor reveals the first occurence of this method (at the top of the editor). It should stay on the selected name. Seems to be a regression.
|
resolved fixed
|
c44cea4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-28T12:38:15Z | 2003-11-28T09:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LinkedNamesAssistProposal.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 org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
import org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.text.link.LinkedEnvironment;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionGroup;
import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl;
/**
* A template proposal.
*/
public class LinkedNamesAssistProposal implements IJavaCompletionProposal, ICompletionProposalExtension2 {
private SimpleName fNode;
private IRegion fSelectedRegion; // initialized by apply()
private ICompilationUnit fCompilationUnit;
public LinkedNamesAssistProposal(ICompilationUnit cu, SimpleName node) {
fNode= node;
fCompilationUnit= cu;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int)
*/
public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
try {
// create full ast
CompilationUnit root= AST.parseCompilationUnit(fCompilationUnit, true);
SimpleName nameNode= (SimpleName) NodeFinder.perform(root, fNode.getStartPosition(), fNode.getLength());
ASTNode[] sameNodes= LinkedNodeFinder.perform(root, nameNode.resolveBinding());
IDocument document= viewer.getDocument();
LinkedPositionGroup group= new LinkedPositionGroup();
for (int i= 0; i < sameNodes.length; i++) {
ASTNode elem= sameNodes[i];
group.createPosition(document, elem.getStartPosition(), elem.getLength(), i); // let the user iterate over all the linked fields
}
LinkedEnvironment enviroment= LinkedEnvironment.createLinkedEnvironment(document);
enviroment.addGroup(group);
LinkedUIControl ui= new LinkedUIControl(enviroment, viewer);
// ui.setInitialOffset(offset);
ui.setExitPosition(viewer, offset, 0, false);
ui.enter();
fSelectedRegion= ui.getSelectedRegion();
} catch (BadLocationException e) {
}
}
/*
* @see ICompletionProposal#apply(IDocument)
*/
public void apply(IDocument document) {
// can't do anything
}
/*
* @see ICompletionProposal#getSelection(IDocument)
*/
public Point getSelection(IDocument document) {
return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength());
}
/*
* @see ICompletionProposal#getAdditionalProposalInfo()
*/
public String getAdditionalProposalInfo() {
return CorrectionMessages.getString("LinkedNamesAssistProposal.proposalinfo"); //$NON-NLS-1$
}
/*
* @see ICompletionProposal#getDisplayString()
*/
public String getDisplayString() {
return CorrectionMessages.getString("LinkedNamesAssistProposal.description"); //$NON-NLS-1$
}
/*
* @see ICompletionProposal#getImage()
*/
public Image getImage() {
return JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
}
/*
* @see ICompletionProposal#getContextInformation()
*/
public IContextInformation getContextInformation() {
return null;
}
/*
* @see IJavaCompletionProposal#getRelevance()
*/
public int getRelevance() {
return 1;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(org.eclipse.jface.text.ITextViewer, boolean)
*/
public void selected(ITextViewer textViewer, boolean smartToggle) {
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(org.eclipse.jface.text.ITextViewer)
*/
public void unselected(ITextViewer textViewer) {
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent)
*/
public boolean validate(IDocument document, int offset, DocumentEvent event) {
return false;
}
}
|
46,956 |
Bug 46956 QuickFix 'add unimplmented methods' should indicate how many methods are going to be added
|
Sometimes, you think this is what you want, and then suddenly, you've got an extra 20 or 30 methods. It would be nice to know the consequences of this choice in advance. (It's one of the few choices where the "change volume" can really vary a great deal).
|
resolved fixed
|
7714e3a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-29T16:35:23Z | 2003-11-19T13:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/UnimplementedMethodsCompletionProposal.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.Javadoc;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.ReturnStatement;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.ui.CodeGeneration;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class UnimplementedMethodsCompletionProposal extends ASTRewriteCorrectionProposal {
private ASTNode fTypeNode;
public UnimplementedMethodsCompletionProposal(ICompilationUnit cu, ASTNode typeNode, int relevance) {
super(null, cu, null, relevance, null);
setDisplayName(CorrectionMessages.getString("UnimplementedMethodsCompletionProposal.description"));//$NON-NLS-1$
setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE));
fTypeNode= typeNode;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal#getRewrite()
*/
protected ASTRewrite getRewrite() throws CoreException {
ITypeBinding binding;
List bodyDecls;
if (fTypeNode instanceof AnonymousClassDeclaration) {
AnonymousClassDeclaration decl= (AnonymousClassDeclaration) fTypeNode;
binding= decl.resolveBinding();
bodyDecls= decl.bodyDeclarations();
} else {
TypeDeclaration decl= (TypeDeclaration) fTypeNode;
binding= decl.resolveBinding();
bodyDecls= decl.bodyDeclarations();
}
IMethodBinding[] methods= evalUnimplementedMethods(binding);
ASTRewrite rewrite= new ASTRewrite(fTypeNode);
AST ast= fTypeNode.getAST();
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (!settings.createComments || binding.isAnonymous()) {
settings= null;
}
for (int i= 0; i < methods.length; i++) {
MethodDeclaration newMethodDecl= createNewMethodDeclaration(ast, methods[i], rewrite, binding.getName(), settings);
rewrite.markAsInserted(newMethodDecl);
bodyDecls.add(newMethodDecl);
}
return rewrite;
}
private MethodDeclaration createNewMethodDeclaration(AST ast, IMethodBinding binding, ASTRewrite rewrite, String typeName, CodeGenerationSettings commentSettings) throws CoreException {
MethodDeclaration decl= ast.newMethodDeclaration();
decl.setModifiers(binding.getModifiers() & ~Modifier.ABSTRACT);
decl.setName(ast.newSimpleName(binding.getName()));
decl.setConstructor(false);
String returnTypeName= addImport(binding.getReturnType());
decl.setReturnType(ASTNodeFactory.newType(ast, returnTypeName));
List parameters= decl.parameters();
ITypeBinding[] params= binding.getParameterTypes();
String[] paramNames= getArgumentNames(binding);
for (int i= 0; i < params.length; i++) {
String paramTypeName= addImport(params[i]);
SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
var.setType(ASTNodeFactory.newType(ast, paramTypeName));
var.setName(ast.newSimpleName(paramNames[i]));
parameters.add(var);
}
List thrownExceptions= decl.thrownExceptions();
ITypeBinding[] excTypes= binding.getExceptionTypes();
for (int i= 0; i < excTypes.length; i++) {
String excTypeName= addImport(excTypes[i]);
thrownExceptions.add(ASTNodeFactory.newName(ast, excTypeName));
}
Block body= ast.newBlock();
decl.setBody(body);
String bodyStatement= ""; //$NON-NLS-1$
Expression expression= ASTNodeFactory.newDefaultExpression(ast, decl.getReturnType(), decl.getExtraDimensions());
if (expression != null) {
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(expression);
bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'));
}
String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), typeName, binding.getName(), false, bodyStatement, String.valueOf('\n'));
if (placeHolder != null) {
ASTNode todoNode= rewrite.createPlaceholder(placeHolder, ASTRewrite.STATEMENT);
body.statements().add(todoNode);
}
if (commentSettings != null) {
String string= CodeGeneration.getMethodComment(getCompilationUnit(), typeName, decl, binding, String.valueOf('\n'));
if (string != null) {
Javadoc javadoc= (Javadoc) rewrite.createPlaceholder(string, ASTRewrite.JAVADOC);
decl.setJavadoc(javadoc);
}
}
return decl;
}
private String[] getArgumentNames(IMethodBinding binding) {
int nParams= binding.getParameterTypes().length;
if (nParams > 0) {
try {
IJavaProject project= getCompilationUnit().getJavaProject();
IMethod method= Bindings.findMethod(binding, project);
if (method != null) {
return StubUtility.suggestArgumentNames(project, method.getParameterNames());
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
String[] names= new String[nParams];
for (int i= 0; i < names.length; i++) {
names[i]= "arg" + i; //$NON-NLS-1$
}
return names;
}
private void findUnimplementedInterfaceMethods(ITypeBinding typeBinding, HashSet visited, ArrayList allMethods, ArrayList toImplement) {
if (visited.add(typeBinding)) {
IMethodBinding[] typeMethods= typeBinding.getDeclaredMethods();
for (int i= 0; i < typeMethods.length; i++) {
IMethodBinding curr= typeMethods[i];
IMethodBinding impl= findMethod(curr, allMethods);
if (impl == null || ((curr.getExceptionTypes().length < impl.getExceptionTypes().length) && !Modifier.isFinal(impl.getModifiers()))) {
if (impl != null) {
allMethods.remove(impl);
}
// implement an interface method when it does not exist in the hierarchy
// or when it throws less exceptions that the implemented
toImplement.add(curr);
allMethods.add(curr);
}
}
ITypeBinding[] superInterfaces= typeBinding.getInterfaces();
for (int i= 0; i < superInterfaces.length; i++) {
findUnimplementedInterfaceMethods(superInterfaces[i], visited, allMethods, toImplement);
}
}
}
private IMethodBinding[] evalUnimplementedMethods(ITypeBinding typeBinding) {
ArrayList allMethods= new ArrayList();
ArrayList toImplement= new ArrayList();
IMethodBinding[] typeMethods= typeBinding.getDeclaredMethods();
for (int i= 0; i < typeMethods.length; i++) {
IMethodBinding curr= typeMethods[i];
int modifiers= curr.getModifiers();
if (!curr.isConstructor() && !Modifier.isStatic(modifiers) && !Modifier.isPrivate(modifiers)) {
allMethods.add(curr);
}
}
ITypeBinding superClass= typeBinding.getSuperclass();
while (superClass != null) {
typeMethods= superClass.getDeclaredMethods();
for (int i= 0; i < typeMethods.length; i++) {
IMethodBinding curr= typeMethods[i];
int modifiers= curr.getModifiers();
if (!curr.isConstructor() && !Modifier.isStatic(modifiers) && !Modifier.isPrivate(modifiers)) {
if (findMethod(curr, allMethods) == null) {
allMethods.add(curr);
}
}
}
superClass= superClass.getSuperclass();
}
for (int i= 0; i < allMethods.size(); i++) {
IMethodBinding curr= (IMethodBinding) allMethods.get(i);
int modifiers= curr.getModifiers();
if ((Modifier.isAbstract(modifiers) || curr.getDeclaringClass().isInterface()) && (typeBinding != curr.getDeclaringClass())) {
// implement all abstract methods
toImplement.add(curr);
}
}
HashSet visited= new HashSet();
ITypeBinding curr= typeBinding;
while (curr != null) {
ITypeBinding[] superInterfaces= curr.getInterfaces();
for (int i= 0; i < superInterfaces.length; i++) {
findUnimplementedInterfaceMethods(superInterfaces[i], visited, allMethods, toImplement);
}
curr= curr.getSuperclass();
}
return (IMethodBinding[]) toImplement.toArray(new IMethodBinding[toImplement.size()]);
}
private IMethodBinding findMethod(IMethodBinding method, ArrayList allMethods) {
for (int i= 0; i < allMethods.size(); i++) {
IMethodBinding curr= (IMethodBinding) allMethods.get(i);
if (Bindings.isEqualMethod(method, curr.getName(), curr.getParameterTypes())) {
return curr;
}
}
return null;
}
}
|
45,680 |
Bug 45680 Add Import corner case [code manipulation]
|
I'm using M4. I have a source file which imports java.awt.* and java.util.*. Now, I need a method parameter of type java.util.List. I type 'List', highlight it, and press Ctrl+Shift+m; the Add Import dialog appears asking me to choose between java.awt.List and java.util.List. I select the proper one and OK, but my imports do not get updated. Seems like it realizes the java.util.* import should cover me, but it doesn't take into consideration the ambiguous aspect.
|
resolved fixed
|
dc996e9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-11-29T16:49:30Z | 2003-10-28T19:40:00Z |
org.eclipse.jdt.ui/core
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.