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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
50,971 |
Bug 50971 Extract temp: index out of bounds error [refactoring]
|
I20040129 Trying to extract a local from entries[i].getPluginId() caused an exception. private MultiStatus createMultiStatus() { MultiStatus status= new MultiStatus( JavaPlugin.getPluginId(), IStatus.ERROR, RefactoringMessages.getString ("UndoManagerAction.validation_failed"), //$NON-NLS-1$ null); RefactoringStatusEntry[] entries= fPreflightStatus.getEntries (); for (int i= 0; i < entries.length; i++) { status.merge(new Status( IStatus.ERROR, entries[i].getPluginId() != null ? entries [i].getPluginId() : JavaPlugin.getPluginId(), IStatus.ERROR, entries[i].getMessage(), null)); } return status; } Caused by: java.lang.ArrayIndexOutOfBoundsException: 10 at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.allArra ysEqual(ExtractTempRefactoring.java:647) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getLong estArrayPrefix(ExtractTempRefactoring.java:634) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.findDee pestCommonSuperNodePathForReplacedNodes(ExtractTempRefactoring.java:619) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getNode ToInsertTempDeclarationBefore(ExtractTempRefactoring.java:595) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.createA ndInsertTempDeclaration(ExtractTempRefactoring.java:525) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.createT empDeclarationEdit(ExtractTempRefactoring.java:515) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getAllE dits(ExtractTempRefactoring.java:500) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.checkIn put(ExtractTempRefactoring.java:368) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:64) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:99) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:166) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302)
|
resolved fixed
|
30a745b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-23T19:46:38Z | 2004-01-30T16:26:40Z |
org.eclipse.jdt.ui/core
| |
50,971 |
Bug 50971 Extract temp: index out of bounds error [refactoring]
|
I20040129 Trying to extract a local from entries[i].getPluginId() caused an exception. private MultiStatus createMultiStatus() { MultiStatus status= new MultiStatus( JavaPlugin.getPluginId(), IStatus.ERROR, RefactoringMessages.getString ("UndoManagerAction.validation_failed"), //$NON-NLS-1$ null); RefactoringStatusEntry[] entries= fPreflightStatus.getEntries (); for (int i= 0; i < entries.length; i++) { status.merge(new Status( IStatus.ERROR, entries[i].getPluginId() != null ? entries [i].getPluginId() : JavaPlugin.getPluginId(), IStatus.ERROR, entries[i].getMessage(), null)); } return status; } Caused by: java.lang.ArrayIndexOutOfBoundsException: 10 at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.allArra ysEqual(ExtractTempRefactoring.java:647) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getLong estArrayPrefix(ExtractTempRefactoring.java:634) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.findDee pestCommonSuperNodePathForReplacedNodes(ExtractTempRefactoring.java:619) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getNode ToInsertTempDeclarationBefore(ExtractTempRefactoring.java:595) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.createA ndInsertTempDeclaration(ExtractTempRefactoring.java:525) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.createT empDeclarationEdit(ExtractTempRefactoring.java:515) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getAllE dits(ExtractTempRefactoring.java:500) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.checkIn put(ExtractTempRefactoring.java:368) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:64) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:99) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:166) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302)
|
resolved fixed
|
30a745b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-23T19:46:38Z | 2004-01-30T16:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractTempRefactoring.java
| |
51,647 |
Bug 51647 [navigation] Quick Outline: Toggle inherited method does not reveal selection
|
20040211 - Open java.lang.reflect.Field and press CTRL+O on 'getShort'. - Press CTRL+O again see attached screenshot: -> getShort not revealed anymore, tree scrolled horizontally
|
resolved fixed
|
3f3d06b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-25T11:59:43Z | 2004-02-11T14:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaOutlineInformationControl.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
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.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.Widget;
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.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.keys.KeySequence;
import org.eclipse.ui.keys.SWTKeySupport;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.internal.corext.util.SuperTypeHierarchyCache;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.MemberFilter;
/**
* Show outline in light-weight control.
*
* @since 2.1
*/
public class JavaOutlineInformationControl extends AbstractInformationControl {
private KeyAdapter fKeyAdapter;
private OutlineContentProvider fOutlineContentProvider;
private IJavaElement fInput= null;
private AppearanceAwareLabelProvider fInnerLabelProvider;
protected Color fForegroundColor;
private class OutlineLabelProvider extends AppearanceAwareLabelProvider {
private OutlineLabelProvider() {
super(AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS);
}
/**
* {@inheritDoc}
*/
public Color getForeground(Object element) {
if (fOutlineContentProvider.isShowingInheritedMembers()) {
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
if (fInput.getElementType() == IJavaElement.CLASS_FILE)
je= je.getAncestor(IJavaElement.CLASS_FILE);
else
je= je.getAncestor(IJavaElement.COMPILATION_UNIT);
if (fInput.equals(je)) {
return null;
}
}
return fForegroundColor;
}
return null;
}
}
private class OutlineTreeViewer extends TreeViewer {
private boolean fIsFiltering= false;
public OutlineTreeViewer(Tree tree) {
super(tree);
}
/**
* {@inheritDoc}
*/
protected Object[] getFilteredChildren(Object parent) {
Object[] result = getRawChildren(parent);
int unfilteredChildren= result.length;
ViewerFilter[] filters = getFilters();
if (filters != null) {
for (int i= 0; i < filters.length; i++)
result = filters[i].filter(this, parent, result);
}
fIsFiltering= unfilteredChildren != result.length;
return result;
}
/**
* {@inheritDoc}
*/
protected void internalExpandToLevel(Widget node, int level) {
if (!fIsFiltering && node instanceof Item) {
Item i= (Item) node;
if (i.getData() instanceof IJavaElement) {
IJavaElement je= (IJavaElement) i.getData();
if (je.getElementType() == IJavaElement.IMPORT_CONTAINER || isInnerType(je)) {
setExpanded(i, false);
return;
}
}
}
super.internalExpandToLevel(node, level);
}
private boolean isInnerType(IJavaElement element) {
if (element != null && element.getElementType() == IJavaElement.TYPE) {
IType type= (IType)element;
try {
return type.isMember();
} catch (JavaModelException e) {
IJavaElement parent= type.getParent();
if (parent != null) {
int parentElementType= parent.getElementType();
return (parentElementType != IJavaElement.COMPILATION_UNIT && parentElementType != IJavaElement.CLASS_FILE);
}
}
}
return false;
}
}
private class OutlineContentProvider extends StandardJavaElementContentProvider {
private Map fTypeHierarchies= new HashMap();
private boolean fShowInheritedMembers;
/**
* Creates a new Outline content provider.
*
* @param showInheritedMembers <code>true</code> iff inherited members are shown
*/
public OutlineContentProvider(boolean showInheritedMembers) {
super(true);
fShowInheritedMembers= showInheritedMembers;
}
public boolean isShowingInheritedMembers() {
return fShowInheritedMembers;
}
public void toggleShowInheritedMembers() {
getTreeViewer().getTree().setRedraw(false);
fShowInheritedMembers= !fShowInheritedMembers;
getTreeViewer().refresh();
getTreeViewer().getTree().setRedraw(true);
}
/**
* {@inheritDoc}
*/
public Object[] getChildren(Object element) {
if (fShowInheritedMembers && element instanceof IType) {
IType type= (IType)element;
if (type.getDeclaringType() == null) {
ITypeHierarchy th= getSuperTypeHierarchy(type);
if (th != null) {
List children= new ArrayList();
IType[] superClasses= th.getAllSupertypes(type);
children.addAll(Arrays.asList(super.getChildren(type)));
for (int i= 0, scLength= superClasses.length; i < scLength; i++)
children.addAll(Arrays.asList(super.getChildren(superClasses[i])));
return children.toArray();
}
}
}
return super.getChildren(element);
}
private ITypeHierarchy getSuperTypeHierarchy(IType type) {
ITypeHierarchy th= (ITypeHierarchy)fTypeHierarchies.get(type);
if (th == null) {
try {
th= SuperTypeHierarchyCache.getTypeHierarchy(type, getProgressMonitor());
} catch (JavaModelException e) {
return null;
}
fTypeHierarchies.put(type, th);
}
return th;
}
private IProgressMonitor getProgressMonitor() {
IWorkbenchPage wbPage= JavaPlugin.getActivePage();
if (wbPage == null)
return null;
IEditorPart editor= wbPage.getActiveEditor();
if (editor == null)
return null;
return editor.getEditorSite().getActionBars().getStatusLineManager().getProgressMonitor();
}
/**
* {@inheritDoc}
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
super.inputChanged(viewer, oldInput, newInput);
fTypeHierarchies.clear();
}
/**
* {@inheritDoc}
*/
public void dispose() {
super.dispose();
fTypeHierarchies.clear();
}
}
/**
* Creates a new Java outline information control.
*
* @param parent
* @param shellStyle
* @param treeStyle
* @param commandId
*/
public JavaOutlineInformationControl(Shell parent, int shellStyle, int treeStyle, String commandId) {
super(parent, shellStyle, treeStyle, commandId, true);
fForegroundColor= parent.getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY);
}
/**
* {@inheritDoc}
*/
protected Text createFilterText(Composite parent) {
Text text= super.createFilterText(parent);
text.addKeyListener(getKeyAdapter());
return text;
}
/**
* {@inheritDoc}
*/
protected TreeViewer createTreeViewer(Composite parent, int style) {
Tree tree= new Tree(parent, SWT.SINGLE | (style & ~SWT.MULTI));
tree.setLayoutData(new GridData(GridData.FILL_BOTH));
final TreeViewer treeViewer= new OutlineTreeViewer(tree);
// Hide import declartions but show the container
treeViewer.addFilter(new ViewerFilter() {
public boolean select(Viewer viewer, Object parentElement, Object element) {
return !(element instanceof IImportDeclaration);
}
});
treeViewer.addFilter(new NamePatternFilter());
treeViewer.addFilter(new MemberFilter());
fOutlineContentProvider= new OutlineContentProvider(false);
treeViewer.setContentProvider(fOutlineContentProvider);
treeViewer.setSorter(new JavaElementSorter());
treeViewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
fInnerLabelProvider= new OutlineLabelProvider();
treeViewer.setLabelProvider(new DecoratingJavaLabelProvider(fInnerLabelProvider));
treeViewer.getTree().addKeyListener(getKeyAdapter());
return treeViewer;
}
/**
* {@inheritDoc}
*/
protected String getStatusFieldText() {
KeySequence[] sequences= getInvokingCommandKeySequences();
if (sequences == null || sequences.length == 0)
return ""; //$NON-NLS-1$
String keySequence= sequences[0].format();
if (fOutlineContentProvider.isShowingInheritedMembers())
return JavaUIMessages.getFormattedString("JavaOutlineControl.statusFieldText.hideInheritedMembers", keySequence); //$NON-NLS-1$
else
return JavaUIMessages.getFormattedString("JavaOutlineControl.statusFieldText.showInheritedMembers", keySequence); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
public void setInput(Object information) {
if (information == null || information instanceof String) {
inputChanged(null, null);
return;
}
IJavaElement je= (IJavaElement)information;
ICompilationUnit cu= (ICompilationUnit)je.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null)
fInput= cu;
else
fInput= je.getAncestor(IJavaElement.CLASS_FILE);
inputChanged(fInput, information);
}
private KeyAdapter getKeyAdapter() {
if (fKeyAdapter == null) {
fKeyAdapter= new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int accelerator = SWTKeySupport.convertEventToUnmodifiedAccelerator(e);
KeySequence keySequence = KeySequence.getInstance(SWTKeySupport.convertAcceleratorToKeyStroke(accelerator));
KeySequence[] sequences= getInvokingCommandKeySequences();
if (sequences == null)
return;
for (int i= 0; i < sequences.length; i++) {
if (sequences[i].equals(keySequence)) {
e.doit= false;
toggleShowInheritedMembers();
return;
}
}
}
};
}
return fKeyAdapter;
}
/**
* {@inheritDoc}
*/
protected void handleStatusFieldClicked() {
toggleShowInheritedMembers();
}
protected void toggleShowInheritedMembers() {
int flags= AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE;
if (!fOutlineContentProvider.isShowingInheritedMembers())
flags |= JavaElementLabels.ALL_POST_QUALIFIED;
fInnerLabelProvider.setTextFlags(flags);
fOutlineContentProvider.toggleShowInheritedMembers();
updateStatusFieldText();
}
}
|
52,971 |
Bug 52971 Generated delegate methods not qualified with 'this.' in field accesses.
|
I'm using 3.0M7 GTK on X4.3, Kernel 2.6.3. When I select a field, and use the context menu's Source->Generate Delegate Methods... and select some method, the generated method does not have the field qualified with 'this.', even though I have that preference set in Preferences->Code Generation->Names->Qualify all generated field accesses with 'this.' I'll attach my preferences and a snapshot of the preferences panel in the next comments.
|
resolved fixed
|
b78d5e0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-25T14:02:02Z | 2004-02-24T19:13:20Z |
org.eclipse.jdt.ui/core
| |
52,971 |
Bug 52971 Generated delegate methods not qualified with 'this.' in field accesses.
|
I'm using 3.0M7 GTK on X4.3, Kernel 2.6.3. When I select a field, and use the context menu's Source->Generate Delegate Methods... and select some method, the generated method does not have the field qualified with 'this.', even though I have that preference set in Preferences->Code Generation->Names->Qualify all generated field accesses with 'this.' I'll attach my preferences and a snapshot of the preferences panel in the next comments.
|
resolved fixed
|
b78d5e0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-25T14:02:02Z | 2004-02-24T19:13:20Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/AddDelegateMethodsOperation.java
| |
52,918 |
Bug 52918 [Types view] Changed modifier -> type icon not updated
|
The types view (Java Browsing -> Types) does not reflect changes of the type modifier. Examlpe: public class A {}. - While removing the public modifier (change to default/package scope) the types view still shows the class icon to be public. Even after saving and compiling it. I consider it a bug. Thanks, Martin (Kersten)
|
resolved fixed
|
3f43128
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-25T14:22:35Z | 2004-02-24T10:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/JavaBrowsingContentProvider.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.browsing;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.IBasicPropertyConstants;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IImportContainer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IParent;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.IWorkingCopy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
class JavaBrowsingContentProvider extends StandardJavaElementContentProvider implements IElementChangedListener {
private StructuredViewer fViewer;
private Object fInput;
private JavaBrowsingPart fBrowsingPart;
private int fReadsInDisplayTread;
public JavaBrowsingContentProvider(boolean provideMembers, JavaBrowsingPart browsingPart) {
super(provideMembers);
fBrowsingPart= browsingPart;
fViewer= fBrowsingPart.getViewer();
JavaCore.addElementChangedListener(this);
}
public boolean hasChildren(Object element) {
startReadInDisplayThread();
try{
return super.hasChildren(element);
} finally {
finishedReadInDisplayThread();
}
}
public Object[] getChildren(Object element) {
if (!exists(element))
return NO_CHILDREN;
startReadInDisplayThread();
try {
if (element instanceof Collection) {
Collection elements= (Collection)element;
if (elements.isEmpty())
return NO_CHILDREN;
Object[] result= new Object[0];
Iterator iter= ((Collection)element).iterator();
while (iter.hasNext()) {
Object[] children= getChildren(iter.next());
if (children != NO_CHILDREN)
result= concatenate(result, children);
}
return result;
}
if (element instanceof IPackageFragment)
return getPackageContents((IPackageFragment)element);
if (fProvideMembers && element instanceof IType)
return getChildren((IType)element);
if (fProvideMembers && element instanceof ISourceReference && element instanceof IParent)
return removeImportAndPackageDeclarations(super.getChildren(element));
if (element instanceof IJavaProject)
return getPackageFragmentRoots((IJavaProject)element);
return super.getChildren(element);
} catch (JavaModelException e) {
return NO_CHILDREN;
} finally {
finishedReadInDisplayThread();
}
}
private Object[] getPackageContents(IPackageFragment fragment) throws JavaModelException {
ISourceReference[] sourceRefs;
if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
sourceRefs= fragment.getCompilationUnits();
}
else {
IClassFile[] classFiles= fragment.getClassFiles();
List topLevelClassFile= new ArrayList();
for (int i= 0; i < classFiles.length; i++) {
IType type= classFiles[i].getType();
if (type != null && type.getDeclaringType() == null && !type.isAnonymous() && !type.isLocal())
topLevelClassFile.add(classFiles[i]);
}
sourceRefs= (ISourceReference[])topLevelClassFile.toArray(new ISourceReference[topLevelClassFile.size()]);
}
Object[] result= new Object[0];
for (int i= 0; i < sourceRefs.length; i++)
result= concatenate(result, removeImportAndPackageDeclarations(getChildren(sourceRefs[i])));
return concatenate(result, fragment.getNonJavaResources());
}
private Object[] removeImportAndPackageDeclarations(Object[] members) {
ArrayList tempResult= new ArrayList(members.length);
for (int i= 0; i < members.length; i++)
if (!(members[i] instanceof IImportContainer) && !(members[i] instanceof IPackageDeclaration))
tempResult.add(members[i]);
return tempResult.toArray();
}
private Object[] getChildren(IType type) throws JavaModelException{
IParent parent;
if (type.isBinary())
parent= type.getClassFile();
else {
parent= type.getCompilationUnit();
}
if (type.getDeclaringType() != null)
return type.getChildren();
// Add import declarations
IJavaElement[] members= parent.getChildren();
ArrayList tempResult= new ArrayList(members.length);
for (int i= 0; i < members.length; i++)
if ((members[i] instanceof IImportContainer))
tempResult.add(members[i]);
tempResult.addAll(Arrays.asList(type.getChildren()));
return tempResult.toArray();
}
protected Object[] getPackageFragmentRoots(IJavaProject project) throws JavaModelException {
if (!project.getProject().isOpen())
return NO_CHILDREN;
IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
List list= new ArrayList(roots.length);
// filter out package fragments that correspond to projects and
// replace them with the package fragments directly
for (int i= 0; i < roots.length; i++) {
IPackageFragmentRoot root= roots[i];
if (!root.isExternal()) {
Object[] children= root.getChildren();
for (int k= 0; k < children.length; k++)
list.add(children[k]);
}
else if (hasChildren(root)) {
list.add(root);
}
}
return concatenate(list.toArray(), project.getNonJavaResources());
}
// ---------------- Element change handling
/* (non-Javadoc)
* Method declared on IContentProvider.
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
super.inputChanged(viewer, oldInput, newInput);
if (newInput instanceof Collection) {
// Get a template object from the collection
Collection col= (Collection)newInput;
if (!col.isEmpty())
newInput= col.iterator().next();
else
newInput= null;
}
fInput= newInput;
}
/* (non-Javadoc)
* Method declared on IContentProvider.
*/
public void dispose() {
super.dispose();
JavaCore.removeElementChangedListener(this);
}
/* (non-Javadoc)
* Method declared on IElementChangedListener.
*/
public void elementChanged(final ElementChangedEvent event) {
try {
processDelta(event.getDelta());
} catch(JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
}
/**
* Processes a delta recursively. When more than two children are affected the
* tree is fully refreshed starting at this node. The delta is processed in the
* current thread but the viewer updates are posted to the UI thread.
*/
protected void processDelta(IJavaElementDelta delta) throws JavaModelException {
int kind= delta.getKind();
int flags= delta.getFlags();
IJavaElement element= delta.getElement();
if (!getProvideWorkingCopy() && element instanceof IWorkingCopy && ((IWorkingCopy)element).isWorkingCopy())
return;
if (element != null && element.getElementType() == IJavaElement.COMPILATION_UNIT && !isOnClassPath((ICompilationUnit)element))
return;
// handle open and closing of a solution or project
if (((flags & IJavaElementDelta.F_CLOSED) != 0) || ((flags & IJavaElementDelta.F_OPENED) != 0)) {
postRefresh(element);
return;
}
if (kind == IJavaElementDelta.REMOVED) {
Object parent= internalGetParent(element);
if (fBrowsingPart.isValidElement(element)) {
if (element instanceof IClassFile) {
postRemove(((IClassFile)element).getType());
} else if (element instanceof ICompilationUnit && !((ICompilationUnit)element).isWorkingCopy()) {
postRefresh(null);
} else if (element instanceof ICompilationUnit && ((ICompilationUnit)element).isWorkingCopy()) {
if (getProvideWorkingCopy())
postRefresh(null);
} else if (parent instanceof ICompilationUnit && getProvideWorkingCopy() && !((ICompilationUnit)parent).isWorkingCopy()) {
if (element instanceof IWorkingCopy && ((IWorkingCopy)element).isWorkingCopy()) {
// working copy removed from system - refresh
postRefresh(null);
}
} else if (element instanceof IWorkingCopy && ((IWorkingCopy)element).isWorkingCopy() && parent != null && parent.equals(fInput))
// closed editor - removing working copy
postRefresh(null);
else
postRemove(element);
}
if (fBrowsingPart.isAncestorOf(element, fInput)) {
if (element instanceof IWorkingCopy && ((IWorkingCopy)element).isWorkingCopy()) {
postAdjustInputAndSetSelection(JavaModelUtil.toOriginal((IJavaElement) fInput));
} else
postAdjustInputAndSetSelection(null);
}
if (fInput != null && fInput.equals(element))
postRefresh(null);
if (parent instanceof IPackageFragment && fBrowsingPart.isValidElement(parent)) {
// refresh if package gets empty (might be filtered)
if (isPackageFragmentEmpty((IPackageFragment)parent) && fViewer.testFindItem(parent) != null)
postRefresh(null);
}
return;
}
if (kind == IJavaElementDelta.ADDED && delta.getMovedFromElement() != null && element instanceof ICompilationUnit)
return;
if (kind == IJavaElementDelta.ADDED) {
if (fBrowsingPart.isValidElement(element)) {
Object parent= internalGetParent(element);
if (element instanceof IClassFile) {
postAdd(parent, ((IClassFile)element).getType());
} else if (element instanceof ICompilationUnit && !((ICompilationUnit)element).isWorkingCopy()) {
postAdd(parent, ((ICompilationUnit)element).getTypes());
} else if (parent instanceof ICompilationUnit && getProvideWorkingCopy() && !((ICompilationUnit)parent).isWorkingCopy()) {
// do nothing
} else if (element instanceof IWorkingCopy && ((IWorkingCopy)element).isWorkingCopy()) {
// new working copy comes to live
postRefresh(null);
} else
postAdd(parent, element);
} else if (fInput == null) {
IJavaElement newInput= fBrowsingPart.findInputForJavaElement(element);
if (newInput != null)
postAdjustInputAndSetSelection(element);
} else if (element instanceof IType && fBrowsingPart.isValidInput(element)) {
IJavaElement cu1= element.getAncestor(IJavaElement.COMPILATION_UNIT);
IJavaElement cu2= ((IJavaElement)fInput).getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu1 != null && cu2 != null && cu1.equals(cu2))
postAdjustInputAndSetSelection(element);
}
return;
}
if (fInput != null && fInput.equals(element)) {
if (kind == IJavaElementDelta.CHANGED && (flags & IJavaElementDelta.F_CHILDREN) != 0 && (flags & IJavaElementDelta.F_FINE_GRAINED) != 0) {
postRefresh(null, true);
return;
}
}
if (isClassPathChange(delta))
// throw the towel and do a full refresh
postRefresh(null);
if ((flags & IJavaElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0 && fInput instanceof IJavaElement) {
IPackageFragmentRoot pkgRoot= (IPackageFragmentRoot)element;
IJavaElement inputsParent= ((IJavaElement)fInput).getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
if (pkgRoot.equals(inputsParent))
postRefresh(null);
}
// the source attachment of a JAR has changed
if (element instanceof IPackageFragmentRoot && (((flags & IJavaElementDelta.F_SOURCEATTACHED) != 0 || ((flags & IJavaElementDelta.F_SOURCEDETACHED)) != 0)))
postUpdateIcon(element);
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
if (affectedChildren.length > 1) {
// a package fragment might become non empty refresh from the parent
if (element instanceof IPackageFragment) {
IJavaElement parent= (IJavaElement)internalGetParent(element);
// avoid posting a refresh to an unvisible parent
if (element.equals(fInput)) {
postRefresh(element);
} else {
postRefresh(parent);
}
}
// more than one child changed, refresh from here downwards
if (element instanceof IPackageFragmentRoot && fBrowsingPart.isValidElement(element)) {
postRefresh(skipProjectPackageFragmentRoot((IPackageFragmentRoot)element));
return;
}
}
for (int i= 0; i < affectedChildren.length; i++) {
processDelta(affectedChildren[i]);
}
}
private boolean isOnClassPath(ICompilationUnit element) throws JavaModelException {
IJavaProject project= element.getJavaProject();
if (project == null || !project.exists())
return false;
return project.isOnClasspath(element);
}
/**
* Updates the package icon
*/
private void postUpdateIcon(final IJavaElement element) {
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.update(element, new String[]{IBasicPropertyConstants.P_IMAGE});
}
});
}
private void postRefresh(final Object root, boolean updateLabels) {
if (!updateLabels) {
postRefresh(root);
return;
}
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.refresh(root, true);
}
});
}
private void postRefresh(final Object root) {
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.refresh(root, false);
}
});
}
private void postAdd(final Object parent, final Object element) {
postAdd(parent, new Object[] {element});
}
private void postAdd(final Object parent, final Object[] elements) {
if (elements == null || elements.length <= 0)
return;
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
Object[] newElements= getNewElements(elements);
if (fViewer instanceof AbstractTreeViewer) {
if (fViewer.testFindItem(parent) == null) {
Object root= ((AbstractTreeViewer)fViewer).getInput();
if (root != null)
((AbstractTreeViewer)fViewer).add(root, newElements);
}
else
((AbstractTreeViewer)fViewer).add(parent, newElements);
}
else if (fViewer instanceof ListViewer)
((ListViewer)fViewer).add(newElements);
else if (fViewer instanceof TableViewer)
((TableViewer)fViewer).add(newElements);
if (fViewer.testFindItem(elements[0]) != null)
fBrowsingPart.adjustInputAndSetSelection(elements[0]);
}
}
});
}
private Object[] getNewElements(Object[] elements) {
int elementsLength= elements.length;
ArrayList result= new ArrayList(elementsLength);
for (int i= 0; i < elementsLength; i++) {
Object element= elements[i];
if (fViewer.testFindItem(element) == null)
result.add(element);
}
return result.toArray();
}
private void postRemove(final Object element) {
postRemove(new Object[] {element});
}
private void postRemove(final Object[] elements) {
if (elements.length <= 0)
return;
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
if (fViewer instanceof AbstractTreeViewer)
((AbstractTreeViewer)fViewer).remove(elements);
else if (fViewer instanceof ListViewer)
((ListViewer)fViewer).remove(elements);
else if (fViewer instanceof TableViewer)
((TableViewer)fViewer).remove(elements);
}
}
});
}
private void postAdjustInputAndSetSelection(final Object element) {
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.setRedraw(false);
fBrowsingPart.adjustInputAndSetSelection(element);
ctrl.setRedraw(true);
}
}
});
}
protected void startReadInDisplayThread() {
if (isDisplayThread())
fReadsInDisplayTread++;
}
protected void finishedReadInDisplayThread() {
if (isDisplayThread())
fReadsInDisplayTread--;
}
private boolean isDisplayThread() {
Control ctrl= fViewer.getControl();
if (ctrl == null)
return false;
Display currentDisplay= Display.getCurrent();
return currentDisplay != null && currentDisplay.equals(ctrl.getDisplay());
}
private void postRunnable(final Runnable r) {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
fBrowsingPart.setProcessSelectionEvents(false);
try {
if (isDisplayThread() && fReadsInDisplayTread == 0)
ctrl.getDisplay().syncExec(r);
else
ctrl.getDisplay().asyncExec(r);
} finally {
fBrowsingPart.setProcessSelectionEvents(true);
}
}
}
/**
* Returns the parent for the element.
* <p>
* Note: This method will return a working copy if the
* parent is a working copy. The super class implementation
* returns the original element instead.
* </p>
*/
protected Object internalGetParent(Object element) {
if (element instanceof IJavaProject) {
return ((IJavaProject)element).getJavaModel();
}
// try to map resources to the containing package fragment
if (element instanceof IResource) {
IResource parent= ((IResource)element).getParent();
Object jParent= JavaCore.create(parent);
if (jParent != null)
return jParent;
return parent;
}
// for package fragments that are contained in a project package fragment
// we have to skip the package fragment root as the parent.
if (element instanceof IPackageFragment) {
IPackageFragmentRoot parent= (IPackageFragmentRoot)((IPackageFragment)element).getParent();
return skipProjectPackageFragmentRoot(parent);
}
if (element instanceof IJavaElement)
return ((IJavaElement)element).getParent();
return null;
}
}
|
52,857 |
Bug 52857 [spell checking] spell checking does not work for reused editors
|
3.0 M7 0. enable spell checking 1. set the editor preference to close editors automatically (allow only 1 editor) 2. open a CU with misspelled words in the Java editor ==> observe: spell check warnings appear 3. open another CU with misspelled words in the Java editor ==> observe: no spell check warnings
|
resolved fixed
|
a62b3fc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-25T15:05:11Z | 2004-02-23T18:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/spelling/SpellReconcileStrategy.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.spelling;
import java.text.MessageFormat;
import java.util.Locale;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.reconciler.DirtyRegion;
import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.core.IProblemRequestor;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellCheckEngine;
import org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellCheckPreferenceKeys;
import org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellChecker;
import org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellEvent;
import org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellEventListener;
/**
* Reconcile strategy to spell-check comments.
*
* @since 3.0
*/
public class SpellReconcileStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension, ISpellEventListener {
/**
* Spelling problem to be accepted by problem requestors.
*/
public class SpellProblem implements IProblem {
/** The id of the problem */
public static final int Spelling= 0x80000000;
/** The end offset of the problem */
private int fEnd= 0;
/** The line number of the problem */
private int fLine= 1;
/** Was the word found in the dictionary? */
private boolean fMatch;
/** Does the word start a new sentence? */
private boolean fSentence= false;
/** The start offset of the problem */
private int fStart= 0;
/** The word which caused the problem */
private final String fWord;
/**
* Creates a new spelling problem
*
* @param word
* The word which caused the problem
*/
protected SpellProblem(final String word) {
fWord= word;
}
/*
* @see org.eclipse.jdt.core.compiler.IProblem#getArguments()
*/
public String[] getArguments() {
String prefix= ""; //$NON-NLS-1$
String postfix= ""; //$NON-NLS-1$
try {
final IRegion line= fDocument.getLineInformationOfOffset(fStart);
prefix= fDocument.get(line.getOffset(), fStart - line.getOffset());
postfix= fDocument.get(fEnd + 1, line.getOffset() + line.getLength() - fEnd);
} catch (BadLocationException exception) {
// Do nothing
}
return new String[] { fWord, prefix, postfix, fSentence ? Boolean.toString(true) : Boolean.toString(false), fMatch ? Boolean.toString(true) : Boolean.toString(false)};
}
/*
* @see org.eclipse.jdt.core.compiler.IProblem#getID()
*/
public int getID() {
return Spelling;
}
/*
* @see org.eclipse.jdt.core.compiler.IProblem#getMessage()
*/
public String getMessage() {
if (fSentence && fMatch)
return MessageFormat.format(JavaUIMessages.getString("Spelling.error.case.label"), new String[] { fWord }); //$NON-NLS-1$
return MessageFormat.format(JavaUIMessages.getString("Spelling.error.label"), new String[] { fWord }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
/*
* @see org.eclipse.jdt.core.compiler.IProblem#getOriginatingFileName()
*/
public char[] getOriginatingFileName() {
return fEditor.getEditorInput().getName().toCharArray();
}
/*
* @see org.eclipse.jdt.core.compiler.IProblem#getSourceEnd()
*/
public final int getSourceEnd() {
return fEnd;
}
/*
* @see org.eclipse.jdt.core.compiler.IProblem#getSourceLineNumber()
*/
public final int getSourceLineNumber() {
return fLine;
}
/*
* @see org.eclipse.jdt.core.compiler.IProblem#getSourceStart()
*/
public final int getSourceStart() {
return fStart;
}
/**
* Was the problem word found in the dictionary?
*
* @return <code>true</code> iff the word was found, <code>false</code>
* otherwise
*/
public final boolean isDictionaryMatch() {
return fMatch;
}
/*
* @see org.eclipse.jdt.core.compiler.IProblem#isError()
*/
public final boolean isError() {
return false;
}
/**
* Does the problem word start a new sentence?
*
* @return <code>true</code> iff it starts a new sentence, <code>false</code>
* otherwise
*/
public final boolean isSentenceStart() {
return fSentence;
}
/*
* @see org.eclipse.jdt.core.compiler.IProblem#isWarning()
*/
public final boolean isWarning() {
return true;
}
/**
* Sets whether the problem word was found in the dictionary.
*
* @param match
* <code>true</code> iff the word was found, <code>false</code>
* otherwise
*/
public final void setDictionaryMatch(final boolean match) {
fMatch= match;
}
/**
* Sets whether the problem word starts a new sentence.
*
* @param sentence
* <code>true</code> iff the word starts a new sentence,
* <code>false</code> otherwise.
*/
public final void setSentenceStart(final boolean sentence) {
fSentence= sentence;
}
/*
* @see org.eclipse.jdt.core.compiler.IProblem#setSourceEnd(int)
*/
public final void setSourceEnd(final int end) {
fEnd= end;
}
/*
* @see org.eclipse.jdt.core.compiler.IProblem#setSourceLineNumber(int)
*/
public final void setSourceLineNumber(final int line) {
fLine= line;
}
/*
* @see org.eclipse.jdt.core.compiler.IProblem#setSourceStart(int)
*/
public final void setSourceStart(final int start) {
fStart= start;
}
}
/** The document to operate on */
private IDocument fDocument= null;
/** The text editor to operate on */
private final ITextEditor fEditor;
/** The current locale */
private Locale fLocale= SpellCheckEngine.getDefaultLocale();
/** The partitioning of the document */
private final String fPartitioning;
/** The preference store to use */
private final IPreferenceStore fPreferences;
/** The problem requestor */
private final IProblemRequestor fRequestor;
/**
* Creates a new comment reconcile strategy.
*
* @param editor
* The text editor to operate on
* @param partitioning
* The partitioning of the document
* @param store
* The preference store to get the preferences from
*/
public SpellReconcileStrategy(final ITextEditor editor, final String partitioning, final IPreferenceStore store) {
fEditor= editor;
fPartitioning= partitioning;
fPreferences= store;
final IAnnotationModel model= editor.getDocumentProvider().getAnnotationModel(editor.getEditorInput());
fRequestor= (model instanceof IProblemRequestor) ? (IProblemRequestor) model : null;
}
/**
* Returns the current locale of the spell checking preferences.
*
* @return The current locale of the spell checking preferences
*/
public Locale getLocale() {
final String locale= fPreferences.getString(ISpellCheckPreferenceKeys.SPELLING_LOCALE);
if (locale.equals(fLocale.toString()))
return fLocale;
if (locale.length() >= 5)
return new Locale(locale.substring(0, 2), locale.substring(3, 5));
return SpellCheckEngine.getDefaultLocale();
}
/*
* @see org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellEventListener#handle(org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellEvent)
*/
public void handle(final ISpellEvent event) {
if (fRequestor != null) {
final SpellProblem problem= new SpellProblem(event.getWord());
problem.setSourceStart(event.getBegin());
problem.setSourceEnd(event.getEnd());
problem.setSentenceStart(event.isStart());
problem.setDictionaryMatch(event.isMatch());
try {
problem.setSourceLineNumber(fDocument.getLineOfOffset(event.getBegin()) + 1);
} catch (BadLocationException x) {
// Do nothing
}
fRequestor.acceptProblem(problem);
}
}
/*
* @see org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension#initialReconcile()
*/
public void initialReconcile() {
}
/*
* @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#reconcile(org.eclipse.jface.text.reconciler.DirtyRegion,org.eclipse.jface.text.IRegion)
*/
public void reconcile(final DirtyRegion dirtyRegion, final IRegion subRegion) {
reconcile(subRegion);
}
/*
* @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#reconcile(org.eclipse.jface.text.IRegion)
*/
public void reconcile(final IRegion region) {
if (fPreferences.getBoolean(ISpellCheckPreferenceKeys.SPELLING_CHECK_SPELLING) && fRequestor != null) {
try {
fRequestor.beginReporting();
ITypedRegion partition= null;
final ITypedRegion[] partitions= TextUtilities.computePartitioning(fDocument, fPartitioning, 0, fDocument.getLength());
final Locale locale= getLocale();
final ISpellCheckEngine engine= SpellCheckEngine.getInstance();
final ISpellChecker checker= engine.createSpellChecker(locale, fPreferences);
if (checker != null) {
try {
checker.addListener(this);
for (int index= 0; index < partitions.length; index++) {
partition= partitions[index];
if (!partition.getType().equals(IDocument.DEFAULT_CONTENT_TYPE))
checker.execute(new SpellCheckIterator(fDocument, partition, locale));
}
} finally {
checker.removeListener(this);
}
}
} catch (BadLocationException exception) {
// Do nothing
} finally {
fRequestor.endReporting();
}
}
}
/*
* @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#setDocument(org.eclipse.jface.text.IDocument)
*/
public final void setDocument(final IDocument document) {
fDocument= document;
}
/*
* @see org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension#setProgressMonitor(org.eclipse.core.runtime.IProgressMonitor)
*/
public final void setProgressMonitor(final IProgressMonitor monitor) {
// Do nothing
}
}
|
38,503 |
Bug 38503 Quick Fix: return guessing should check visibility
|
M1 The "add return statement' quick fix should check the visbility for the elements guessed
|
resolved fixed
|
e6c51ae
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-26T11:12:38Z | 2003-06-05T10:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/MissingReturnTypeCorrectionProposal.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.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.internal.corext.dom.ASTNodeConstants;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer;
import org.eclipse.jdt.internal.corext.dom.TypeRules;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
public class MissingReturnTypeCorrectionProposal extends LinkedCorrectionProposal {
private static final String RETURN_EXPRESSION_KEY= "value"; //$NON-NLS-1$
private MethodDeclaration fMethodDecl;
private ReturnStatement fExistingReturn;
public MissingReturnTypeCorrectionProposal(ICompilationUnit cu, MethodDeclaration decl, ReturnStatement existingReturn, int relevance) {
super("", cu, null, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE)); //$NON-NLS-1$
fMethodDecl= decl;
fExistingReturn= existingReturn;
}
public String getDisplayString() {
if (fExistingReturn != null) {
return CorrectionMessages.getString("MissingReturnTypeCorrectionProposal.changereturnstatement.description"); //$NON-NLS-1$
} else {
return CorrectionMessages.getString("MissingReturnTypeCorrectionProposal.addreturnstatement.description"); //$NON-NLS-1$
}
}
/*(non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal#getRewrite()
*/
protected ASTRewrite getRewrite() {
AST ast= fMethodDecl.getAST();
ITypeBinding returnBinding= getReturnTypeBinding();
if (fExistingReturn != null) {
ASTRewrite rewrite= new ASTRewrite(fExistingReturn.getParent());
Expression expression= evaluateReturnExpressions(ast, returnBinding, fExistingReturn.getStartPosition());
if (expression != null) {
rewrite.markAsInsert(fExistingReturn, ASTNodeConstants.EXPRESSION, expression, null);
markAsLinked(rewrite, expression, true, RETURN_EXPRESSION_KEY);
}
return rewrite;
} else {
ASTRewrite rewrite= new ASTRewrite(fMethodDecl);
Block block= fMethodDecl.getBody();
List statements= block.statements();
int nStatements= statements.size();
ASTNode lastStatement= null;
if (nStatements > 0) {
lastStatement= (ASTNode) statements.get(nStatements - 1);
}
if (returnBinding != null && lastStatement instanceof ExpressionStatement && lastStatement.getNodeType() != ASTNode.ASSIGNMENT) {
Expression expression= ((ExpressionStatement) lastStatement).getExpression();
ITypeBinding binding= expression.resolveTypeBinding();
if (binding != null && TypeRules.canAssign(binding, returnBinding)) {
Expression placeHolder= (Expression) rewrite.createMove(expression);
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(placeHolder);
rewrite.markAsReplaced(lastStatement, returnStatement);
return rewrite;
}
}
int offset;
if (lastStatement == null) {
offset= block.getStartPosition() + 1;
} else {
offset= lastStatement.getStartPosition() + lastStatement.getLength();
}
ReturnStatement returnStatement= ast.newReturnStatement();
Expression expression= evaluateReturnExpressions(ast, returnBinding, offset);
returnStatement.setExpression(expression);
rewrite.getListRewrite(block, ASTNodeConstants.STATEMENTS).insertLast(returnStatement, null);
markAsLinked(rewrite, returnStatement.getExpression(), true, RETURN_EXPRESSION_KEY);
return rewrite;
}
}
private ITypeBinding getReturnTypeBinding() {
IMethodBinding methodBinding= fMethodDecl.resolveBinding();
if (methodBinding != null && methodBinding.getReturnType() != null) {
return methodBinding.getReturnType();
}
return null;
}
/*
* Evaluates possible return expressions. The favourite expression is returned.
*/
private Expression evaluateReturnExpressions(AST ast, ITypeBinding returnBinding, int returnOffset) {
CompilationUnit root= (CompilationUnit) fMethodDecl.getRoot();
Expression result= null;
if (returnBinding != null) {
ScopeAnalyzer analyzer= new ScopeAnalyzer(root);
IBinding[] bindings= analyzer.getDeclarationsInScope(returnOffset, ScopeAnalyzer.VARIABLES);
for (int i= 0; i < bindings.length; i++) {
IVariableBinding curr= (IVariableBinding) bindings[i];
ITypeBinding type= curr.getType();
if (type != null && TypeRules.canAssign(type, returnBinding) && testModifier(curr)) {
if (result == null) {
result= ast.newSimpleName(curr.getName());
}
addLinkedModeProposal(RETURN_EXPRESSION_KEY, curr.getName());
}
}
}
Expression defaultExpression= ASTNodeFactory.newDefaultExpression(ast, fMethodDecl.getReturnType(), fMethodDecl.getExtraDimensions());
addLinkedModeProposal(RETURN_EXPRESSION_KEY, ASTNodes.asString(defaultExpression));
if (result == null) {
return defaultExpression;
}
return result;
}
private boolean testModifier(IVariableBinding curr) {
int modifiers= curr.getModifiers();
int staticFinal= Modifier.STATIC | Modifier.FINAL;
if ((modifiers & staticFinal) == staticFinal) {
return false;
}
if (Modifier.isStatic(modifiers) && !Modifier.isStatic(fMethodDecl.getModifiers())) {
return false;
}
return true;
}
}
|
52,708 |
Bug 52708 new formatter does allow else on separate line
|
3m7 I cannot make the (extremely good!) new code formatter do this if (foo) { xxxx } else { yyyy } The old one allowed it.
|
resolved fixed
|
cc86f3f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-26T11:31:45Z | 2004-02-20T23:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/ControlStatementsTabPage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.preferences.formatter;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
public class ControlStatementsTabPage extends ModifyDialogTabPage {
private final static String PREVIEW=
createPreviewHeader(FormatterMessages.getString("ControlStatementsTabPage.preview.header")) + //$NON-NLS-1$
"class Example {" + //$NON-NLS-1$
" void bar() {" + //$NON-NLS-1$
" do {} while (true);" + //$NON-NLS-1$
" }" + //$NON-NLS-1$
" void foo2() {" + //$NON-NLS-1$
" if (true) { " + //$NON-NLS-1$
" return;" + //$NON-NLS-1$
" }" + //$NON-NLS-1$
" if (true) {" + //$NON-NLS-1$
" return;" + //$NON-NLS-1$
" } else if (false) {" + //$NON-NLS-1$
" return; " + //$NON-NLS-1$
" } else {" + //$NON-NLS-1$
" return;" + //$NON-NLS-1$
" }" + //$NON-NLS-1$
" }" + //$NON-NLS-1$
" void foo(int state) {" + //$NON-NLS-1$
" if (true) return;" + //$NON-NLS-1$
" if (true) " + //$NON-NLS-1$
" return;" + //$NON-NLS-1$
" else if (false)" + //$NON-NLS-1$
" return;" + //$NON-NLS-1$
" else return;" + //$NON-NLS-1$
" }" + //$NON-NLS-1$
"}"; //$NON-NLS-1$
private final static String [] NOTINSERT_INSERT= {
JavaCore.DO_NOT_INSERT,
JavaCore.INSERT
};
private CompilationUnitPreview fPreview;
protected CheckboxPreference fThenStatementPref, fSimpleIfPref;
public ControlStatementsTabPage(ModifyDialog modifyDialog, Map workingValues) {
super(modifyDialog, workingValues);
}
protected void doCreatePreferences(Composite composite, int numColumns) {
final Group generalGroup= createGroup(numColumns, composite, FormatterMessages.getString("ControlStatementsTabPage.general_group.title")); //$NON-NLS-1$
createOption(generalGroup, numColumns, FormatterMessages.getString("ControlStatementsTabPage.general_group.insert_new_line_in_control_statements"), DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_IN_CONTROL_STATEMENTS, NOTINSERT_INSERT); //$NON-NLS-1$
final Group ifElseGroup= createGroup(numColumns, composite, FormatterMessages.getString("ControlStatementsTabPage.if_else_group.title")); //$NON-NLS-1$
fThenStatementPref= createOption(ifElseGroup, numColumns, FormatterMessages.getString("ControlStatementsTabPage.if_else_group.keep_then_on_same_line"), DefaultCodeFormatterConstants.FORMATTER_KEEP_THEN_STATEMENT_ON_SAME_LINE, FALSE_TRUE); //$NON-NLS-1$
Label l= new Label(ifElseGroup, SWT.NONE);
GridData gd= new GridData();
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(4);
l.setLayoutData(gd);
fSimpleIfPref= createOption(ifElseGroup, numColumns - 1, FormatterMessages.getString("ControlStatementsTabPage.if_else_group.keep_simple_if_on_one_line"), DefaultCodeFormatterConstants.FORMATTER_KEEP_SIMPLE_IF_ON_ONE_LINE, FALSE_TRUE); //$NON-NLS-1$
fThenStatementPref.addObserver( new Observer() {
public void update(Observable o, Object arg) {
fSimpleIfPref.setEnabled(!fThenStatementPref.getChecked());
}
});
fSimpleIfPref.setEnabled(!fThenStatementPref.getChecked());
createOption(ifElseGroup, numColumns, FormatterMessages.getString("ControlStatementsTabPage.if_else_group.keep_else_on_same_line"), DefaultCodeFormatterConstants.FORMATTER_KEEP_ELSE_STATEMENT_ON_SAME_LINE, FALSE_TRUE); //$NON-NLS-1$
createCheckboxPref(ifElseGroup, numColumns, FormatterMessages.getString("ControlStatementsTabPage.if_else_group.keep_else_if_on_one_line"), DefaultCodeFormatterConstants.FORMATTER_COMPACT_ELSE_IF, FALSE_TRUE); //$NON-NLS-1$
createCheckboxPref(ifElseGroup, numColumns, FormatterMessages.getString("ControlStatementsTabPage.if_else_group.keep_guardian_clause_on_one_line"), DefaultCodeFormatterConstants.FORMATTER_KEEP_GUARDIAN_CLAUSE_ON_ONE_LINE, FALSE_TRUE); //$NON-NLS-1$
}
protected void initializePage() {
fPreview.setPreviewText(PREVIEW);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doCreateJavaPreview(org.eclipse.swt.widgets.Composite)
*/
protected JavaPreview doCreateJavaPreview(Composite parent) {
fPreview= new CompilationUnitPreview(fWorkingValues, parent);
return fPreview;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doUpdatePreview()
*/
protected void doUpdatePreview() {
fPreview.update();
}
private CheckboxPreference createOption(Composite composite, int span, String name, String key, String [] values) {
return createCheckboxPref(composite, span, name, key, values);
}
}
|
53,155 |
Bug 53155 Quick Fix should show import as first item in list if available
|
When using a class that has not been imported, it would seem that the import Quick Fix item should be the first in the list, rather than the random location that it currently seems to appear in.
|
resolved fixed
|
87be1f0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-27T09:07:06Z | 2004-02-26T10:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Renaud Waldura <[email protected]> - New class/interface with wizard
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.ISharedImages;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.ui.text.java.IInvocationContext;
import org.eclipse.jdt.ui.text.java.IProblemLocation;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportRewrite;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.dom.ASTNodeConstants;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer;
import org.eclipse.jdt.internal.corext.dom.TypeRules;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.corext.util.TypeFilter;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.ChangeDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.EditDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.InsertDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.RemoveDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.SwapDescription;
public class UnresolvedElementsSubProcessor {
public static void getVariableProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveredNode(astRoot);
if (selectedNode == null) {
return;
}
// type that defines the variable
ITypeBinding binding= null;
ITypeBinding declaringTypeBinding= Bindings.getBindingOfParentType(selectedNode);
if (declaringTypeBinding == null) {
return;
}
// possible type kind of the node
boolean suggestVariableProposals= true;
int typeKind= 0;
while (selectedNode instanceof ParenthesizedExpression) {
selectedNode= ((ParenthesizedExpression) selectedNode).getExpression();
}
Name node= null;
switch (selectedNode.getNodeType()) {
case ASTNode.SIMPLE_NAME:
node= (SimpleName) selectedNode;
ASTNode parent= node.getParent();
if (parent instanceof MethodInvocation && node.equals(((MethodInvocation)parent).getExpression())) {
typeKind= SimilarElementsRequestor.CLASSES;
} else if (parent instanceof SimpleType) {
suggestVariableProposals= false;
typeKind= SimilarElementsRequestor.REF_TYPES;
} else if (parent instanceof QualifiedName) {
Name qualifier= ((QualifiedName) parent).getQualifier();
if (qualifier != node) {
binding= qualifier.resolveTypeBinding();
} else {
typeKind= SimilarElementsRequestor.REF_TYPES;
}
ASTNode outerParent= parent.getParent();
while (outerParent instanceof QualifiedName) {
outerParent= outerParent.getParent();
}
if (outerParent instanceof SimpleType) {
typeKind= SimilarElementsRequestor.REF_TYPES;
suggestVariableProposals= false;
}
}
break;
case ASTNode.QUALIFIED_NAME:
QualifiedName qualifierName= (QualifiedName) selectedNode;
ITypeBinding qualifierBinding= qualifierName.getQualifier().resolveTypeBinding();
if (qualifierBinding != null) {
node= qualifierName.getName();
binding= qualifierBinding;
} else {
node= qualifierName.getQualifier();
typeKind= SimilarElementsRequestor.REF_TYPES;
suggestVariableProposals= node.isSimpleName();
}
if (selectedNode.getParent() instanceof SimpleType) {
typeKind= SimilarElementsRequestor.REF_TYPES;
suggestVariableProposals= false;
}
break;
case ASTNode.FIELD_ACCESS:
FieldAccess access= (FieldAccess) selectedNode;
Expression expression= access.getExpression();
if (expression != null) {
binding= expression.resolveTypeBinding();
if (binding != null) {
node= access.getName();
}
}
break;
case ASTNode.SUPER_FIELD_ACCESS:
binding= declaringTypeBinding.getSuperclass();
node= ((SuperFieldAccess) selectedNode).getName();
break;
default:
}
if (node == null) {
return;
}
// add type proposals
if (typeKind != 0) {
int relevance= Character.isUpperCase(ASTResolving.getSimpleName(node).charAt(0)) ? 3 : 0;
addSimilarTypeProposals(typeKind, cu, node, relevance + 1, proposals);
addNewTypeProposals(cu, node, SimilarElementsRequestor.REF_TYPES, relevance, proposals);
}
if (!suggestVariableProposals) {
return;
}
SimpleName simpleName= node.isSimpleName() ? (SimpleName) node : ((QualifiedName) node).getName();
boolean isWriteAccess= ASTResolving.isWriteAccess(node);
// similar variables
addSimilarVariableProposals(cu, astRoot, simpleName, isWriteAccess, proposals);
// new fields
addNewFieldProposals(cu, astRoot, binding, declaringTypeBinding, simpleName, isWriteAccess, proposals);
// new parameters and local variables
if (binding == null) {
addNewVariableProposals(cu, node, simpleName, proposals);
}
}
private static void addNewVariableProposals(ICompilationUnit cu, Name node, SimpleName simpleName, Collection proposals) throws CoreException {
String name= simpleName.getIdentifier();
BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(node);
int type= bodyDeclaration.getNodeType();
if (type == ASTNode.METHOD_DECLARATION) {
int relevance= StubUtility.hasParameterName(cu.getJavaProject(), name) ? 8 : 5;
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createparameter.description", simpleName.getIdentifier()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.PARAM, simpleName, null, relevance, image));
}
if (type == ASTNode.METHOD_DECLARATION || type == ASTNode.INITIALIZER) {
int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7;
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createlocal.description", simpleName.getIdentifier()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.LOCAL, simpleName, null, relevance, image));
}
if (node.getParent().getNodeType() == ASTNode.ASSIGNMENT) {
Assignment assignment= (Assignment) node.getParent();
if (assignment.getLeftHandSide() == node && assignment.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
ASTNode statement= assignment.getParent();
ASTRewrite rewrite= new ASTRewrite(statement.getParent());
rewrite.markAsRemoved(statement);
String label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.removestatement.description"); //$NON-NLS-1$
Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 4, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
}
private static void addNewFieldProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, ITypeBinding declaringTypeBinding, SimpleName simpleName, boolean isWriteAccess, Collection proposals) throws JavaModelException {
// new variables
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding);
ITypeBinding senderBinding= binding != null ? binding : declaringTypeBinding;
if (!senderBinding.isFromSource() || targetCU == null || !JavaModelUtil.isEditable(targetCU)) {
return;
}
ITypeBinding outsideAnonymous= null;
if (binding == null && senderBinding.isAnonymous()) {
ASTNode anonymDecl= astRoot.findDeclaringNode(senderBinding);
if (anonymDecl != null) {
ITypeBinding bind= Bindings.getBindingOfParentType(anonymDecl.getParent());
if (!bind.isAnonymous()) {
outsideAnonymous= bind;
}
}
}
String name= simpleName.getIdentifier();
int relevance= StubUtility.hasFieldName(cu.getJavaProject(), name) ? 9 : 6;
String label;
Image image;
if (binding == null) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.description", name); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE);
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { name, binding.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
}
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, relevance, image));
// create field in outer class (if inside anonymous)
if (outsideAnonymous != null) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { name, outsideAnonymous.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, outsideAnonymous, relevance + 1, image));
}
// create constant
if (!isWriteAccess) {
relevance= StubUtility.hasConstantName(name) ? 9 : 4;
ITypeBinding target= (outsideAnonymous != null) ? outsideAnonymous : senderBinding;
if (binding == null) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconst.description", name); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE);
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconst.other.description", new Object[] { name, binding.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
}
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.CONST_FIELD, simpleName, target, relevance, image));
}
}
private static void addSimilarVariableProposals(ICompilationUnit cu, CompilationUnit astRoot, SimpleName node, boolean isWriteAccess, Collection proposals) {
IBinding[] varsInScope= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(node, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY);
if (varsInScope.length > 0) {
// avoid corrections like int i= i;
String otherNameInAssign= null;
ASTNode parent= node.getParent();
if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
// node must be initializer
otherNameInAssign= ((VariableDeclarationFragment) parent).getName().getIdentifier();
} else if (parent.getNodeType() == ASTNode.ASSIGNMENT) {
Assignment assignment= (Assignment) parent;
if (isWriteAccess && assignment.getRightHandSide() instanceof SimpleName) {
otherNameInAssign= ((SimpleName) assignment.getRightHandSide()).getIdentifier();
} else if (!isWriteAccess && assignment.getLeftHandSide() instanceof SimpleName) {
otherNameInAssign= ((SimpleName) assignment.getLeftHandSide()).getIdentifier();
}
}
ITypeBinding guessedType= ASTResolving.guessBindingForReference(node);
if (astRoot.getAST().resolveWellKnownType("java.lang.Object") == guessedType) { //$NON-NLS-1$
guessedType= null; // too many suggestions
}
String identifier= node.getIdentifier();
for (int i= 0; i < varsInScope.length; i++) {
IVariableBinding curr= (IVariableBinding) varsInScope[i];
String currName= curr.getName();
boolean isFinal= Modifier.isFinal(curr.getModifiers());
if (!currName.equals(otherNameInAssign) && !(isFinal && curr.isField() && isWriteAccess)) {
int relevance= 0;
if (NameMatcher.isSimilarName(currName, identifier)) {
relevance += 3; // variable with a similar name than the unresolved variable
}
ITypeBinding varType= curr.getType();
if (guessedType != null && varType != null) {
if (!isWriteAccess && TypeRules.canAssign(varType, guessedType)
|| isWriteAccess && TypeRules.canAssign(guessedType, varType)) {
relevance += 2; // unresolved variable can be assign to this variable
}
}
if (relevance > 0) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changevariable.description", currName); //$NON-NLS-1$
proposals.add(new RenameNodeCompletionProposal(label, cu, node.getStartPosition(), node.getLength(), currName, relevance));
}
}
}
}
}
public static void getTypeProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (selectedNode == null) {
return;
}
int kind= SimilarElementsRequestor.ALL_TYPES;
ASTNode parent= selectedNode.getParent();
while (parent.getLength() == selectedNode.getLength()) { // get parent of type or variablefragment
parent= parent.getParent();
}
switch (parent.getNodeType()) {
case ASTNode.TYPE_DECLARATION:
TypeDeclaration typeDeclaration=(TypeDeclaration) parent;
if (typeDeclaration.superInterfaces().contains(selectedNode)) {
kind= SimilarElementsRequestor.INTERFACES;
} else if (selectedNode.equals(typeDeclaration.getSuperclass())) {
kind= SimilarElementsRequestor.CLASSES;
}
break;
case ASTNode.METHOD_DECLARATION:
MethodDeclaration methodDeclaration= (MethodDeclaration) parent;
if (methodDeclaration.thrownExceptions().contains(selectedNode)) {
kind= SimilarElementsRequestor.CLASSES;
} else if (selectedNode.equals(methodDeclaration.getReturnType())) {
kind= SimilarElementsRequestor.ALL_TYPES | SimilarElementsRequestor.VOIDTYPE;
}
break;
case ASTNode.INSTANCEOF_EXPRESSION:
kind= SimilarElementsRequestor.REF_TYPES;
break;
case ASTNode.THROW_STATEMENT:
kind= SimilarElementsRequestor.REF_TYPES;
break;
case ASTNode.CLASS_INSTANCE_CREATION:
if (((ClassInstanceCreation) parent).getAnonymousClassDeclaration() == null) {
kind= SimilarElementsRequestor.CLASSES;
} else {
kind= SimilarElementsRequestor.REF_TYPES;
}
break;
case ASTNode.SINGLE_VARIABLE_DECLARATION:
int superParent= parent.getParent().getNodeType();
if (superParent == ASTNode.CATCH_CLAUSE) {
kind= SimilarElementsRequestor.CLASSES;
}
break;
case ASTNode.TAG_ELEMENT:
kind= SimilarElementsRequestor.REF_TYPES;
break;
default:
}
Name node= null;
if (selectedNode instanceof SimpleType) {
node= ((SimpleType) selectedNode).getName();
} else if (selectedNode instanceof ArrayType) {
Type elementType= ((ArrayType) selectedNode).getElementType();
if (elementType.isSimpleType()) {
node= ((SimpleType) elementType).getName();
}
} else if (selectedNode instanceof Name) {
node= (Name) selectedNode;
} else {
return;
}
// change to simlar type proposals
addSimilarTypeProposals(kind, cu, node, 3, proposals);
// add type
addNewTypeProposals(cu, node, kind, 0, proposals);
}
private static void addSimilarTypeProposals(int kind, ICompilationUnit cu, Name node, int relevance, Collection proposals) throws CoreException {
SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, node, kind);
// try to resolve type in context -> highest severity
String resolvedTypeName= null;
ITypeBinding binding= ASTResolving.guessBindingForTypeReference(node);
if (binding != null) {
if (binding.isArray()) {
binding= binding.getElementType();
}
resolvedTypeName= binding.getQualifiedName();
proposals.add(createTypeRefChangeProposal(cu, resolvedTypeName, node, relevance + 2));
}
// add all similar elements
for (int i= 0; i < elements.length; i++) {
SimilarElement elem= elements[i];
if ((elem.getKind() & SimilarElementsRequestor.ALL_TYPES) != 0) {
String fullName= elem.getName();
if (!fullName.equals(resolvedTypeName)) {
proposals.add(createTypeRefChangeProposal(cu, fullName, node, relevance));
}
}
}
}
private static CUCorrectionProposal createTypeRefChangeProposal(ICompilationUnit cu, String fullName, Name node, int relevance) throws CoreException {
ImportRewrite importRewrite= new ImportRewrite(cu);
importRewrite.setFindAmbiguosImports(true);
String simpleName= importRewrite.addImport(fullName);
String packName= Signature.getQualifier(fullName);
String[] arg= { simpleName, packName };
CUCorrectionProposal proposal;
if (node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) { // import only
// import only
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importtype.description", arg); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL);
proposal= new CUCorrectionProposal(label, cu, relevance + 20, image);
} else {
String label;
if (packName.length() == 0) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.nopack.description", simpleName); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.description", arg); //$NON-NLS-1$
}
proposal= new RenameNodeCompletionProposal(label, cu, node.getStartPosition(), node.getLength(), simpleName, relevance); //$NON-NLS-1$
}
proposal.setImportRewrite(importRewrite);
return proposal;
}
private static void addNewTypeProposals(ICompilationUnit cu, Name refNode, int kind, int relevance, Collection proposals) throws JavaModelException {
Name node= refNode;
do {
String typeName= ASTResolving.getSimpleName(node);
Name qualifier= null;
// only propose to create types for qualifiers when the name starts with upper case
boolean isPossibleName= Character.isUpperCase(typeName.charAt(0)) || (node == refNode);
if (isPossibleName) {
IPackageFragment enclosingPackage= null;
IType enclosingType= null;
if (node.isSimpleName()) {
enclosingPackage= (IPackageFragment) cu.getParent();
// don't sugest member type, user can select it in wizard
} else {
Name qualifierName= ((QualifiedName) node).getQualifier();
// 24347
// IBinding binding= qualifierName.resolveBinding();
// if (binding instanceof ITypeBinding) {
// enclosingType= Binding2JavaModel.find((ITypeBinding) binding, cu.getJavaProject());
IJavaElement[] res= cu.codeSelect(qualifierName.getStartPosition(), qualifierName.getLength());
if (res!= null && res.length > 0 && res[0] instanceof IType) {
enclosingType= (IType) res[0];
} else {
qualifier= qualifierName;
enclosingPackage= JavaModelUtil.getPackageFragmentRoot(cu).getPackageFragment(ASTResolving.getFullName(qualifierName));
}
}
// new top level type
if (enclosingPackage != null && !enclosingPackage.getCompilationUnit(typeName + ".java").exists()) { //$NON-NLS-1$
if ((kind & SimilarElementsRequestor.CLASSES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingPackage, relevance));
}
if ((kind & SimilarElementsRequestor.INTERFACES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingPackage, relevance));
}
}
// new member type
if (enclosingType != null && !enclosingType.isReadOnly() && !enclosingType.getType(typeName).exists()) {
if ((kind & SimilarElementsRequestor.CLASSES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingType, relevance));
}
if ((kind & SimilarElementsRequestor.INTERFACES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingType, relevance));
}
}
}
node= qualifier;
} while (node != null);
}
public static void getMethodProposals(IInvocationContext context, IProblemLocation problem, boolean needsNewName, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(astRoot);
if (!(selectedNode instanceof SimpleName)) {
return;
}
SimpleName nameNode= (SimpleName) selectedNode;
List arguments;
Expression sender;
boolean isSuperInvocation;
ASTNode invocationNode= nameNode.getParent();
if (invocationNode instanceof MethodInvocation) {
MethodInvocation methodImpl= (MethodInvocation) invocationNode;
arguments= methodImpl.arguments();
sender= methodImpl.getExpression();
isSuperInvocation= false;
} else if (invocationNode instanceof SuperMethodInvocation) {
SuperMethodInvocation methodImpl= (SuperMethodInvocation) invocationNode;
arguments= methodImpl.arguments();
sender= methodImpl.getQualifier();
isSuperInvocation= true;
} else {
return;
}
String methodName= nameNode.getIdentifier();
int nArguments= arguments.size();
// corrections
IBinding[] bindings= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(nameNode, ScopeAnalyzer.METHODS);
ArrayList parameterMismatchs= new ArrayList();
for (int i= 0; i < bindings.length; i++) {
IMethodBinding binding= (IMethodBinding) bindings[i];
String curr= binding.getName();
if (curr.equals(methodName) && needsNewName) {
parameterMismatchs.add(binding);
} else if (binding.getParameterTypes().length == nArguments && NameMatcher.isSimilarName(methodName, curr)) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changemethod.description", curr); //$NON-NLS-1$
proposals.add(new RenameNodeCompletionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), curr, 6));
}
}
addParameterMissmatchProposals(context, problem, parameterMismatchs, invocationNode, arguments, proposals);
// new method
ITypeBinding binding= null;
if (sender != null) {
binding= sender.resolveTypeBinding();
} else {
binding= Bindings.getBindingOfParentType(invocationNode);
if (isSuperInvocation && binding != null) {
binding= binding.getSuperclass();
}
}
if (binding != null && binding.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding);
if (targetCU != null) {
String label;
Image image;
String sig= getMethodSignature(methodName, arguments);
if (cu.equals(targetCU)) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.description", sig); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE);
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", new Object[] { sig, targetCU.getElementName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
}
proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 5, image));
if (binding.isAnonymous() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(binding, methodName, null) == null) { // no covering method
ASTNode anonymDecl= astRoot.findDeclaringNode(binding);
if (anonymDecl != null) {
binding= Bindings.getBindingOfParentType(anonymDecl.getParent());
if (!binding.isAnonymous()) {
String[] args= new String[] { sig, binding.getName() };
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", args); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED);
proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 5, image));
}
}
}
}
}
if (!isSuperInvocation) {
ASTNode parent= invocationNode.getParent();
while (parent instanceof Expression && parent.getNodeType() != ASTNode.CAST_EXPRESSION) {
parent= parent.getParent();
}
if (!isSuperInvocation && parent instanceof CastExpression) {
addMissingCastParentsProposal(cu, (CastExpression) parent, sender, nameNode, getArgumentTypes(arguments), proposals);
}
}
}
private static void addMissingCastParentsProposal(ICompilationUnit cu, CastExpression expression, Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes, Collection proposals) throws CoreException {
ITypeBinding castType= expression.getType().resolveBinding();
if (castType == null) {
return;
}
if (paramTypes != null) {
if (Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes) == null) {
return;
}
} else if (Bindings.findFieldInHierarchy(castType, accessSelector.getIdentifier()) == null) {
return;
}
ITypeBinding bindingToCast= accessExpression.resolveTypeBinding();
if (bindingToCast != null && !TypeRules.canCast(castType, bindingToCast)) {
return;
}
IMethodBinding res= Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes);
if (res != null) {
AST ast= expression.getAST();
ASTRewrite rewrite= new ASTRewrite(expression.getParent());
CastExpression newCast= ast.newCastExpression();
newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType()));
newCast.setExpression((Expression) rewrite.createCopy(accessExpression));
ParenthesizedExpression parents= ast.newParenthesizedExpression();
parents.setExpression(newCast);
ASTNode node= rewrite.createCopy(expression.getExpression());
rewrite.markAsReplaced(expression, node);
rewrite.markAsReplaced(accessExpression, parents);
String label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.missingcastbrackets.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 8, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
private static void addParameterMissmatchProposals(IInvocationContext context, IProblemLocation problem, List similarElements, ASTNode invocationNode, List arguments, Collection proposals) throws CoreException {
int nSimilarElements= similarElements.size();
ITypeBinding[] argTypes= getArgumentTypes(arguments);
if (argTypes == null || nSimilarElements == 0) {
return;
}
for (int i= 0; i < nSimilarElements; i++) {
IMethodBinding elem = (IMethodBinding) similarElements.get(i);
int diff= elem.getParameterTypes().length - argTypes.length;
if (diff == 0) {
int nProposals= proposals.size();
doEqualNumberOfParameters(context, invocationNode, problem, arguments, argTypes, elem, proposals);
if (nProposals != proposals.size()) {
return; // only suggest for one method (avoid duplicated proposals)
}
} else if (diff > 0) {
doMoreParameters(context, problem, invocationNode, arguments, argTypes, elem, proposals);
} else {
doMoreArguments(context, problem, invocationNode, arguments, argTypes, elem, proposals);
}
}
}
private static void doMoreParameters(IInvocationContext context, IProblemLocation problem, ASTNode invocationNode, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException {
ITypeBinding[] paramTypes= methodBinding.getParameterTypes();
int k= 0, nSkipped= 0;
int diff= paramTypes.length - argTypes.length;
int[] indexSkipped= new int[diff];
for (int i= 0; i < paramTypes.length; i++) {
if (k < argTypes.length && TypeRules.canAssign(argTypes[k], paramTypes[i])) {
k++; // match
} else {
if (nSkipped >= diff) {
return; // too different
}
indexSkipped[nSkipped++]= i;
}
}
ITypeBinding declaringType= methodBinding.getDeclaringClass();
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
// add arguments
{
String[] arg= new String[] { getMethodSignature(methodBinding, false) };
String label;
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargument.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addarguments.description", arg); //$NON-NLS-1$
}
AddArgumentCorrectionProposal proposal= new AddArgumentCorrectionProposal(label, context.getCompilationUnit(), invocationNode, indexSkipped, paramTypes, 8);
proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD));
proposal.ensureNoModifications();
proposals.add(proposal);
}
// remove parameters
if (!declaringType.isFromSource()) {
return;
}
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
if (targetCU != null) {
ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length];
ITypeBinding[] changedTypes= new ITypeBinding[diff];
for (int i= diff - 1; i >= 0; i--) {
int idx= indexSkipped[i];
changeDesc[idx]= new RemoveDescription();
changedTypes[i]= paramTypes[idx];
}
String[] arg= new String[] { getMethodSignature(methodBinding, !cu.equals(targetCU)), getTypeNames(changedTypes) };
String label;
if (methodBinding.isConstructor()) {
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparam.constr.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparams.constr.description", arg); //$NON-NLS-1$
}
} else {
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparam.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparams.description", arg); //$NON-NLS-1$
}
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE);
ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, 5, image);
proposals.add(proposal);
}
}
private static String getTypeNames(ITypeBinding[] types) {
StringBuffer buf= new StringBuffer();
for (int i= 0; i < types.length; i++) {
if (i > 0) {
buf.append(", "); //$NON-NLS-1$
}
buf.append(types[i].getName());
}
return buf.toString();
}
private static String getArgumentName(ICompilationUnit cu, List arguments, int index) {
String def= String.valueOf(index + 1);
ASTNode expr= (ASTNode) arguments.get(index);
if (expr.getLength() > 18) {
return def;
}
try {
String str= cu.getBuffer().getText(expr.getStartPosition(), expr.getLength());
for (int i= 0; i < str.length(); i++) {
if (Strings.isLineDelimiterChar(str.charAt(i))) {
return def;
}
}
ASTMatcher matcher= new ASTMatcher();
for (int i= 0; i < arguments.size(); i++) {
if (i != index && matcher.safeSubtreeMatch(expr, arguments.get(i))) {
return def;
}
}
return '\'' + str + '\'';
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return def;
}
private static void doMoreArguments(IInvocationContext context, IProblemLocation problem, ASTNode invocationNode, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException {
ITypeBinding[] paramTypes= methodBinding.getParameterTypes();
int k= 0, nSkipped= 0;
int diff= argTypes.length - paramTypes.length;
int[] indexSkipped= new int[diff];
for (int i= 0; i < argTypes.length; i++) {
if (k < paramTypes.length && TypeRules.canAssign(argTypes[i], paramTypes[k])) {
k++; // match
} else {
if (nSkipped >= diff) {
return; // too different
}
indexSkipped[nSkipped++]= i;
}
}
ITypeBinding declaringType= methodBinding.getDeclaringClass();
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
// remove arguments
{
ASTNode selectedNode= problem.getCoveringNode(astRoot);
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
for (int i= diff - 1; i >= 0; i--) {
rewrite.markAsRemoved((Expression) arguments.get(indexSkipped[i]));
}
String[] arg= new String[] { getMethodSignature(methodBinding, false) };
String label;
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeargument.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removearguments.description", arg); //$NON-NLS-1$
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
// add parameters
if (!declaringType.isFromSource()) {
return;
}
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
if (targetCU != null) {
boolean isDifferentCU= !cu.equals(targetCU);
if (isDifferentCU && isImplicitConstructor(methodBinding, targetCU)) {
return;
}
ChangeDescription[] changeDesc= new ChangeDescription[argTypes.length];
ITypeBinding[] changeTypes= new ITypeBinding[diff];
for (int i= diff - 1; i >= 0; i--) {
int idx= indexSkipped[i];
Expression arg= (Expression) arguments.get(idx);
String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null;
ITypeBinding newType= Bindings.normalizeTypeBinding(argTypes[idx]);
if (newType == null) {
newType= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
changeDesc[idx]= new InsertDescription(newType, name);
changeTypes[i]= newType;
}
String[] arg= new String[] { getMethodSignature(methodBinding, isDifferentCU), getTypeNames(changeTypes) };
String label;
if (methodBinding.isConstructor()) {
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparam.constr.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparams.constr.description", arg); //$NON-NLS-1$
}
} else {
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparam.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparams.description", arg); //$NON-NLS-1$
}
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, 5, image);
proposals.add(proposal);
}
}
private static boolean isImplicitConstructor(IMethodBinding meth, ICompilationUnit targetCU) {
if (meth.isConstructor() && meth.getParameterTypes().length == 0) {
IMethodBinding[] bindings= meth.getDeclaringClass().getDeclaredMethods();
// implicit constructors must be the only constructor
for (int i= 0; i < bindings.length; i++) {
IMethodBinding curr= bindings[i];
if (curr.isConstructor() && curr != meth) {
return false;
}
}
ASTParser parser= ASTParser.newParser(AST.LEVEL_2_0);
parser.setSource(targetCU);
parser.setFocalPosition(0);
parser.setResolveBindings(true);
CompilationUnit unit= (CompilationUnit) parser.createAST(null);
return unit.findDeclaringNode(meth.getKey()) == null;
}
return false;
}
private static String getMethodSignature(IMethodBinding binding, boolean inOtherCU) {
StringBuffer buf= new StringBuffer();
if (inOtherCU && !binding.isConstructor()) {
buf.append(binding.getDeclaringClass().getName()).append('.');
}
buf.append(binding.getName());
return getMethodSignature(buf.toString(), binding.getParameterTypes());
}
private static String getMethodSignature(String name, List args) {
ITypeBinding[] params= new ITypeBinding[args.size()];
for (int i= 0; i < args.size(); i++) {
Expression expr= (Expression) args.get(i);
ITypeBinding curr= Bindings.normalizeTypeBinding(expr.resolveTypeBinding());
if (curr == null) {
curr= expr.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
params[i]= curr;
}
return getMethodSignature(name, params);
}
private static String getMethodSignature(String name, ITypeBinding[] params) {
StringBuffer buf= new StringBuffer();
buf.append(name).append('(');
for (int i= 0; i < params.length; i++) {
if (i > 0) {
buf.append(", "); //$NON-NLS-1$
}
buf.append(params[i].getName());
}
buf.append(')');
return buf.toString();
}
private static void doEqualNumberOfParameters(IInvocationContext context, ASTNode invocationNode, IProblemLocation problem, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException {
ITypeBinding[] paramTypes= methodBinding.getParameterTypes();
int[] indexOfDiff= new int[paramTypes.length];
int nDiffs= 0;
for (int n= 0; n < argTypes.length; n++) {
if (!TypeRules.canAssign(argTypes[n], paramTypes[n])) {
indexOfDiff[nDiffs++]= n;
}
}
ITypeBinding declaringType= methodBinding.getDeclaringClass();
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode nameNode= problem.getCoveringNode(astRoot);
if (nameNode == null) {
return;
}
if (nDiffs == 0) {
if (nameNode.getParent() instanceof MethodInvocation) {
MethodInvocation inv= (MethodInvocation) nameNode.getParent();
if (inv.getExpression() == null) {
addQualifierToOuterProposal(context, inv, methodBinding, proposals);
}
}
return;
}
if (nDiffs == 1) { // one argument missmatching: try to fix
int idx= indexOfDiff[0];
Expression nodeToCast= (Expression) arguments.get(idx);
ITypeBinding castType= paramTypes[idx];
ITypeBinding binding= nodeToCast.resolveTypeBinding();
if (binding == null || TypeRules.canCast(castType, binding)) {
String castTypeName= castType.getQualifiedName();
ASTRewriteCorrectionProposal proposal= LocalCorrectionsSubProcessor.createCastProposal(context, castTypeName, nodeToCast, 6);
String[] arg= new String[] { getArgumentName(cu, arguments, idx), castTypeName};
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargumentcast.description", arg)); //$NON-NLS-1$
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (nDiffs == 2) { // try to swap
int idx1= indexOfDiff[0];
int idx2= indexOfDiff[1];
boolean canSwap= TypeRules.canAssign(argTypes[idx1], paramTypes[idx2]) && TypeRules.canAssign(argTypes[idx2], paramTypes[idx1]);
if (canSwap) {
Expression arg1= (Expression) arguments.get(idx1);
Expression arg2= (Expression) arguments.get(idx2);
ASTRewrite rewrite= new ASTRewrite(arg1.getParent());
rewrite.markAsReplaced(arg1, rewrite.createCopy(arg2));
rewrite.markAsReplaced(arg2, rewrite.createCopy(arg1));
{
String[] arg= new String[] { getArgumentName(cu, arguments, idx1), getArgumentName(cu, arguments, idx2) };
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swaparguments.description", arg); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
if (declaringType.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
if (targetCU != null) {
ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length];
for (int i= 0; i < nDiffs; i++) {
changeDesc[idx1]= new SwapDescription(idx2);
}
ITypeBinding[] swappedTypes= new ITypeBinding[] { paramTypes[idx1], paramTypes[idx2] };
String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getTypeNames(swappedTypes) };
String label;
if (methodBinding.isConstructor()) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swapparams.constr.description", args); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swapparams.description", args); //$NON-NLS-1$
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, 5, image);
proposals.add(proposal);
}
}
return;
}
}
if (declaringType.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
if (targetCU != null) {
ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length];
for (int i= 0; i < nDiffs; i++) {
int diffIndex= indexOfDiff[i];
Expression arg= (Expression) arguments.get(diffIndex);
String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null;
changeDesc[diffIndex]= new EditDescription(argTypes[diffIndex], name);
}
String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getMethodSignature(methodBinding.getName(), arguments) };
String label;
if (methodBinding.isConstructor()) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changeparamsignature.constr.description", args); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changeparamsignature.description", args); //$NON-NLS-1$
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, 7, image);
proposals.add(proposal);
}
}
}
private static ITypeBinding[] getArgumentTypes(List arguments) {
ITypeBinding[] res= new ITypeBinding[arguments.size()];
for (int i= 0; i < res.length; i++) {
Expression expression= (Expression) arguments.get(i);
ITypeBinding curr= expression.resolveTypeBinding();
if (curr == null) {
return null;
}
curr= Bindings.normalizeTypeBinding(curr);
if (curr == null) {
curr= expression.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
res[i]= curr;
}
return res;
}
private static void addQualifierToOuterProposal(IInvocationContext context, MethodInvocation invocationNode, IMethodBinding binding, Collection proposals) throws CoreException {
ITypeBinding declaringType= binding.getDeclaringClass();
ITypeBinding parentType= Bindings.getBindingOfParentType(invocationNode);
ITypeBinding currType= parentType;
boolean isInstanceMethod= !Modifier.isStatic(binding.getModifiers());
while (currType != null && !Bindings.isSuperType(declaringType, currType)) {
if (isInstanceMethod && Modifier.isStatic(currType.getModifiers())) {
return;
}
currType= currType.getDeclaringClass();
}
if (currType == null || currType == parentType) {
return;
}
ASTRewrite rewrite= new ASTRewrite(invocationNode.getParent());
ImportRewrite imports= new ImportRewrite(context.getCompilationUnit());
AST ast= invocationNode.getAST();
String qualifier= imports.addImport(currType);
Name name= ASTNodeFactory.newName(ast, qualifier);
Expression newExpression;
if (isInstanceMethod) {
ThisExpression expr= ast.newThisExpression();
expr.setQualifier(name);
newExpression= expr;
} else {
newExpression= name;
}
rewrite.markAsInsert(invocationNode, ASTNodeConstants.EXPRESSION, newExpression, null);
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetoouter.description", currType.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image);
proposal.setImportRewrite(imports);
proposal.ensureNoModifications();
proposals.add(proposal);
}
public static void getConstructorProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(astRoot);
if (selectedNode == null) {
return;
}
ITypeBinding targetBinding= null;
List arguments= null;
IMethodBinding recursiveConstructor= null;
int type= selectedNode.getNodeType();
if (type == ASTNode.CLASS_INSTANCE_CREATION) {
ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode;
IBinding binding= creation.getName().resolveBinding();
if (binding instanceof ITypeBinding) {
targetBinding= (ITypeBinding) binding;
arguments= creation.arguments();
}
} else if (type == ASTNode.SUPER_CONSTRUCTOR_INVOCATION) {
ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode);
if (typeBinding != null && !typeBinding.isAnonymous()) {
targetBinding= typeBinding.getSuperclass();
arguments= ((SuperConstructorInvocation) selectedNode).arguments();
}
} else if (type == ASTNode.CONSTRUCTOR_INVOCATION) {
ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode);
if (typeBinding != null && !typeBinding.isAnonymous()) {
targetBinding= typeBinding;
arguments= ((ConstructorInvocation) selectedNode).arguments();
recursiveConstructor= ASTResolving.findParentMethodDeclaration(selectedNode).resolveBinding();
}
}
if (targetBinding == null) {
return;
}
IMethodBinding[] methods= targetBinding.getDeclaredMethods();
ArrayList similarElements= new ArrayList();
for (int i= 0; i < methods.length; i++) {
IMethodBinding curr= methods[i];
if (curr.isConstructor() && recursiveConstructor != curr) {
similarElements.add(curr); // similar elements can contain a implicit default constructor
}
}
addParameterMissmatchProposals(context, problem, similarElements, selectedNode, arguments, proposals);
if (targetBinding.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, targetBinding);
if (targetCU != null) {
String[] args= new String[] { getMethodSignature( targetBinding.getName(), arguments) };
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconstructor.description", args); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
proposals.add(new NewMethodCompletionProposal(label, targetCU, selectedNode, arguments, targetBinding, 5, image));
}
}
}
public static void getAmbiguosTypeReferenceProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
int offset= problem.getOffset();
int len= problem.getLength();
IJavaElement[] elements= cu.codeSelect(offset, len);
for (int i= 0; i < elements.length; i++) {
IJavaElement curr= elements[i];
if (curr instanceof IType && !TypeFilter.isFiltered((IType) curr)) {
String qualifiedTypeName= JavaModelUtil.getFullyQualifiedName((IType) curr);
ImportRewrite imports= new ImportRewrite(cu);
imports.setFindAmbiguosImports(true);
imports.addImport(qualifiedTypeName);
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importexplicit.description", qualifiedTypeName); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL);
CUCorrectionProposal proposal= new CUCorrectionProposal(label, cu, 5, image);
proposal.setImportRewrite(imports);
proposals.add(proposal);
}
}
}
}
|
53,215 |
Bug 53215 NPE showing package explorer
|
Build 20040226 I launched my workbench which came up with the Package Explorer stacked underneath other views. I then clicked on the new pulldown to bring the Package Explorer. The following exception occurred: org.eclipse.jface.util.Assert$AssertionFailedException: null argument; at org.eclipse.jface.util.Assert.isNotNull(Assert.java:139) at org.eclipse.jface.util.Assert.isNotNull(Assert.java:116) at org.eclipse.jface.util.ListenerList.add(ListenerList.java:88) at org.eclipse.jface.viewers.Viewer.addSelectionChangedListener(Viewer.java:129) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart.showInput(PackageExplorerPart. java:960) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart. editorActivated(PackageExplorerPart.java:916) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$1. partActivated(PackageExplorerPart.java:148) at org.eclipse.ui.internal.PartListenerList$1.run(PartListenerList.java:49) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:788) at org.eclipse.core.runtime.Platform.run(Platform.java:497) at org.eclipse.ui.internal.PartListenerList.firePartActivated(PartListenerList.java:47) at org.eclipse.ui.internal.WorkbenchPage.firePartActivated(WorkbenchPage.java:1287) at org.eclipse.ui.internal.WorkbenchPage.setActivePart(WorkbenchPage.java:2586) at org.eclipse.ui.internal.WorkbenchPage.requestActivation(WorkbenchPage.java:2281) at org.eclipse.ui.internal.PartPane.requestActivation(PartPane.java:362) at org.eclipse.ui.internal.EditorPane.requestActivation(EditorPane.java:153) at org.eclipse.ui.internal.PartPane.handleEvent(PartPane.java:342) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:956) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:980) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:961) at org.eclipse.swt.widgets.Shell.setActiveControl(Shell.java:859) at org.eclipse.swt.widgets.Control.sendFocusEvent(Control.java:2142) at org.eclipse.swt.widgets.Control.gtk_event_after(Control.java:1677) at org.eclipse.swt.widgets.Widget.windowProc(Widget.java:1212) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2362) at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(Native Method) at org.eclipse.swt.widgets.Display.eventProc(Display.java:728) at org.eclipse.swt.internal.gtk.OS.gtk_clipboard_wait_for_contents(Native Method) at org.eclipse.swt.dnd.Clipboard._getAvailableTypes(Clipboard.java:364) at org.eclipse.swt.dnd.Clipboard.getAvailableTypes(Clipboard.java:300) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction.canOperateOn(PasteAction.java:127) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction.selectionChanged(PasteAction.java: 116) at org.eclipse.jdt.ui.actions.SelectionDispatchAction. dispatchSelectionChanged(SelectionDispatchAction.java:200) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.update(SelectionDispatchAction.java:114) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction.<init>(PasteAction.java:107) at org.eclipse.jdt.ui.actions.CCPActionGroup.<init>(CCPActionGroup.java:80) at org.eclipse.jdt.ui.actions.CCPActionGroup.<init>(CCPActionGroup.java:63) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerActionGroup. <init>(PackageExplorerActionGroup.java:123) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart. makeActions(PackageExplorerPart.java:576) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart. createPartControl(PackageExplorerPart.java:280) at org.eclipse.ui.internal.PartPane$1.run(PartPane.java:118) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:788) at org.eclipse.core.runtime.Platform.run(Platform.java:497) at org.eclipse.ui.internal.PartPane.createChildControl(PartPane.java:114) at org.eclipse.ui.internal.ViewPane.createChildControl(ViewPane.java:322) at org.eclipse.ui.internal.ViewFactory$1.run(ViewFactory.java:245) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:788) at org.eclipse.core.runtime.Platform.run(Platform.java:497) at org.eclipse.ui.internal.ViewFactory.busyRestoreView(ViewFactory.java:174) at org.eclipse.ui.internal.ViewFactory$2.run(ViewFactory.java:419) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.ui.internal.ViewFactory.restoreView(ViewFactory.java:417) at org.eclipse.ui.internal.ViewFactory$ViewReference.getPart(ViewFactory.java:93) at org.eclipse.ui.internal.WorkbenchPage$1.propertyChange(WorkbenchPage.java:129) at org.eclipse.ui.internal.LayoutPart.setVisible(LayoutPart.java:234) at org.eclipse.ui.internal.PartPane.setVisible(PartPane.java:376) at org.eclipse.ui.internal.PartTabFolder.setSelection(PartTabFolder.java:1221) at org.eclipse.ui.internal.PartTabFolder.access$8(PartTabFolder.java:1207) at org.eclipse.ui.internal.PartTabFolder$4.handleEvent(PartTabFolder.java:380) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:956) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:980) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:965) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:835) at org.eclipse.swt.custom.CTabFolder2.setSelection(CTabFolder2.java:2876) at org.eclipse.swt.custom.CTabFolder2$6.widgetSelected(CTabFolder2.java:3228) 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:956) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1876) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1651) at org.eclipse.swt.custom.CTabFolder2.showList(CTabFolder2.java:3237) at org.eclipse.swt.custom.CTabFolder2.onMouse(CTabFolder2.java:1903) at org.eclipse.swt.custom.CTabFolder2$1.handleEvent(CTabFolder2.java:283) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:956) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1876) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1651) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1566) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1542) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:263) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:256) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:100) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:279) at org.eclipse.core.launcher.Main.run(Main.java:742) at org.eclipse.core.launcher.Main.main(Main.java:581)
|
resolved fixed
|
e6ce6a6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-27T09:58:54Z | 2004-02-26T18:26:40Z |
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.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.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
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.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.*;
import org.eclipse.ui.*;
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.ui.views.framelist.FrameAction;
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.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;
import org.eclipse.jdt.ui.actions.CustomFiltersActionGroup;
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.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.preferences.MembersOrderPreferenceCache;
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.internal.ui.workingsets.WorkingSetFilterActionGroup;
/**
* 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);
return new PackageExplorerContentProvider(this, showCUChildren);
}
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;
Object input= getElementOfInput(editor.getEditorInput());
if (input == null)
return;
if (!inputIsSelected(editor.getEditorInput()))
showInput(input);
}
private boolean inputIsSelected(IEditorInput input) {
IStructuredSelection selection= (IStructuredSelection)fViewer.getSelection();
if (selection.size() != 1)
return false;
IEditorInput selectionAsInput= null;
try {
selectionAsInput= EditorUtility.getEditorInput(selection.getFirstElement());
} catch (JavaModelException e1) {
return false;
}
return input.equals(selectionAsInput);
}
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 (MembersOrderPreferenceCache.isMemberOrderProperty(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() {
try {
fViewer.getControl().setRedraw(false);
fViewer.collapseToLevel(getViewPartInput(), AbstractTreeViewer.ALL_LEVELS);
} finally {
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 tryToReveal(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());
}
}
public boolean tryToReveal(Object element) {
if (revealElementOrParent(element))
return true;
WorkingSetFilterActionGroup workingSetGroup = fActionSet.getWorkingSetActionGroup();
IWorkingSet workingSet = workingSetGroup.getWorkingSet();
if (workingSetGroup.isFiltered(getVisibleParent(element), element)) {
String message= PackagesMessages.getFormattedString("PackageExplorer.notFound", workingSet.getName()); //$NON-NLS-1$
if (MessageDialog.openQuestion(getSite().getShell(), PackagesMessages.getString("PackageExplorer.filteredDialog.title"), message)) { //$NON-NLS-1$
workingSetGroup.setWorkingSet(null, true);
if (revealElementOrParent(element))
return true;
}
}
// try to remove filters
CustomFiltersActionGroup filterGroup = fActionSet.getCustomFilterActionGroup();
String[] filters= filterGroup.removeFiltersFor(getVisibleParent(element), element, getTreeViewer().getContentProvider());
if (filters.length > 0) {
String message= PackagesMessages.getString("PackageExplorer.removeFilters"); //$NON-NLS-1$
if (MessageDialog.openQuestion(getSite().getShell(), PackagesMessages.getString("PackageExplorer.filteredDialog.title"), message)) { //$NON-NLS-1$
filterGroup.setFilters(filters);
if (revealElementOrParent(element))
return true;
}
}
FrameAction action = fActionSet.getUpAction();
while (action.getFrameList().getCurrentIndex() > 0) {
action.run();
if (revealElementOrParent(element))
return true;
}
return false;
}
private boolean revealElementOrParent(Object element) {
if (this != null) {
if (revealAndVerify(element))
return true;
element= getVisibleParent(element);
if (element != null) {
if (revealAndVerify(element))
return true;
if (element instanceof IJavaElement) {
IResource resource= ((IJavaElement)element).getResource();
if (resource != null) {
if (revealAndVerify(resource))
return true;
}
}
}
}
return false;
}
private Object getVisibleParent(Object object) {
// Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=19104
if (object == null)
return null;
if (!(object instanceof IJavaElement))
return object;
IJavaElement element2= (IJavaElement) object;
switch (element2.getElementType()) {
case IJavaElement.IMPORT_DECLARATION:
case IJavaElement.PACKAGE_DECLARATION:
case IJavaElement.IMPORT_CONTAINER:
case IJavaElement.TYPE:
case IJavaElement.METHOD:
case IJavaElement.FIELD:
case IJavaElement.INITIALIZER:
// select parent cu/classfile
element2= (IJavaElement)element2.getOpenable();
break;
case IJavaElement.JAVA_MODEL:
element2= null;
break;
}
if (element2.getElementType() == IJavaElement.COMPILATION_UNIT) {
element2= JavaModelUtil.toOriginal((ICompilationUnit)element2);
}
return element2;
}
private boolean revealAndVerify(Object element) {
if (element == null)
return false;
selectReveal(new StructuredSelection(element));
IElementComparer comparer= getTreeViewer().getComparer();
Object selected= ((IStructuredSelection)getSite().getSelectionProvider().getSelection()).getFirstElement();
if (comparer != null ? comparer.equals(element, selected) : element.equals(selected))
return true;
return false;
}
}
|
52,372 |
Bug 52372 Cannot cancel open type
|
Build 20040212 If indexing is happening, 'Open Type...' (Ctrl+Shift+T) can take a long time. Pressing 'Cancel' has no effect. Also no progress is shown to the user.
|
verified fixed
|
4c886c3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-27T13:42:13Z | 2004-02-18T16:00:00Z |
org.eclipse.jdt.ui/core
| |
52,372 |
Bug 52372 Cannot cancel open type
|
Build 20040212 If indexing is happening, 'Open Type...' (Ctrl+Shift+T) can take a long time. Pressing 'Cancel' has no effect. Also no progress is shown to the user.
|
verified fixed
|
4c886c3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-27T13:42:13Z | 2004-02-18T16:00:00Z |
extension/org/eclipse/jdt/internal/corext/util/AllTypesCache.java
| |
53,010 |
Bug 53010 Editor preferences do not take effect on open editors
|
I-20040224 Go to the Java > Editor > Syntax preference page. Change the keyword color to red. Press Ok. At this point, we use to see the preview update. Not on this build (problem #1). Press Ok, and close the pref dialog. The java editor that was already open did not update. I had to close it and reopen it for the colors to take effect (problem #2)
|
resolved fixed
|
f994e36
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-27T14:35:47Z | 2004-02-25T00:46:40Z |
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.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
import org.eclipse.swt.custom.ST;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
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.AnnotationRulerColumn;
import org.eclipse.jface.text.source.CompositeRuler;
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.ISourceViewerExtension2;
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.EditorsUI;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.ISelectionListener;
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.AnnotationPreference;
import org.eclipse.ui.texteditor.ChainedPreferenceStore;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.ExtendedTextEditor;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.PreferencesAdapter;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextNavigationAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportContainer;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
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.CompilationUnit;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.Name;
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.corext.dom.NodeFinder;
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.ExceptionOccurrencesFinder;
import org.eclipse.jdt.internal.ui.search.OccurrencesFinder;
import org.eclipse.jdt.internal.ui.text.AbstractJavaScanner;
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.text.java.hover.JavaExpandHover;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.ISelectionListenerWithAST;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager;
/**
* 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();
}
}
/**
* 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);
}
}
/**
* Adapts an options {@link java.util.Map} to {@link org.eclipse.jface.preference.IPreferenceStore}.
* <p>
* This preference store is read-only i.e. write access
* throws an {@link java.lang.UnsupportedOperationException}.
* </p>
*
* @since 3.0
*/
private static class OptionsAdapter implements IPreferenceStore {
/**
* A property change event filter.
*/
public interface IPropertyChangeEventFilter {
/**
* Should the given event be filtered?
* @param event The property change event.
* @return <code>true</code> iff the given event should be filtered.
*/
public boolean isFiltered(PropertyChangeEvent event);
}
/**
* Property change listener. Listens for events in the options Map and
* fires a {@link org.eclipse.jface.util.PropertyChangeEvent}
* on this adapter with arguments from the received event.
*/
private class PropertyChangeListener implements IPropertyChangeListener {
/**
* {@inheritDoc}
*/
public void propertyChange(PropertyChangeEvent event) {
if (getFilter().isFiltered(event))
return;
if (event.getNewValue() == null)
fOptions.remove(event.getProperty());
else
fOptions.put(event.getProperty(), event.getNewValue());
firePropertyChangeEvent(event.getProperty(), event.getOldValue(), event.getNewValue());
}
}
/** Listeners on this adapter */
private ListenerList fListeners= new ListenerList();
/** Listener on the adapted options Map */
private IPropertyChangeListener fListener= new PropertyChangeListener();
/** Adapted options Map */
private Map fOptions;
/** Preference store through which events are received. */
private IPreferenceStore fMockupPreferenceStore;
/** Property event filter. */
private IPropertyChangeEventFilter fFilter;
/**
* Initialize with the given options.
*
* @param options The options to wrap.
*/
public OptionsAdapter(Map options, IPreferenceStore mockupPreferenceStore, IPropertyChangeEventFilter filter) {
fMockupPreferenceStore= mockupPreferenceStore;
fOptions= options;
setFilter(filter);
}
/**
* {@inheritDoc}
*/
public void addPropertyChangeListener(IPropertyChangeListener listener) {
if (fListeners.size() == 0)
fMockupPreferenceStore.addPropertyChangeListener(fListener);
fListeners.add(listener);
}
/**
* {@inheritDoc}
*/
public void removePropertyChangeListener(IPropertyChangeListener listener) {
fListeners.remove(listener);
if (fListeners.size() == 0)
fMockupPreferenceStore.removePropertyChangeListener(fListener);
}
/**
* {@inheritDoc}
*/
public boolean contains(String name) {
return fOptions.containsKey(name);
}
/**
* {@inheritDoc}
*/
public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) {
PropertyChangeEvent event= new PropertyChangeEvent(this, name, oldValue, newValue);
Object[] listeners= fListeners.getListeners();
for (int i= 0; i < listeners.length; i++)
((IPropertyChangeListener) listeners[i]).propertyChange(event);
}
/**
* {@inheritDoc}
*/
public boolean getBoolean(String name) {
boolean value= BOOLEAN_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null)
value= s.equals(TRUE);
return value;
}
/**
* {@inheritDoc}
*/
public boolean getDefaultBoolean(String name) {
return BOOLEAN_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public double getDefaultDouble(String name) {
return DOUBLE_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public float getDefaultFloat(String name) {
return FLOAT_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public int getDefaultInt(String name) {
return INT_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public long getDefaultLong(String name) {
return LONG_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public String getDefaultString(String name) {
return STRING_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public double getDouble(String name) {
double value= DOUBLE_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Double(s).doubleValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public float getFloat(String name) {
float value= FLOAT_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Float(s).floatValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public int getInt(String name) {
int value= INT_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Integer(s).intValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public long getLong(String name) {
long value= LONG_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Long(s).longValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public String getString(String name) {
String value= (String) fOptions.get(name);
if (value == null)
value= STRING_DEFAULT_DEFAULT;
return value;
}
/**
* {@inheritDoc}
*/
public boolean isDefault(String name) {
return false;
}
/**
* {@inheritDoc}
*/
public boolean needsSaving() {
return !fOptions.isEmpty();
}
/**
* {@inheritDoc}
*/
public void putValue(String name, String value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, double value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, float value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, int value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, long value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, String defaultObject) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, boolean value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setToDefault(String name) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, double value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, float value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, int value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, long value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, String value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, boolean value) {
throw new UnsupportedOperationException();
}
/**
* Returns the adapted options Map.
*
* @return Returns the adapted options Map.
*/
public Map getOptions() {
return fOptions;
}
/**
* Returns the mockup preference store, events are received through this preference store.
* @return Returns the mockup preference store.
*/
public IPreferenceStore getMockupPreferenceStore() {
return fMockupPreferenceStore;
}
/**
* Set the event filter to the given filter.
*
* @param filter The new filter.
*/
public void setFilter(IPropertyChangeEventFilter filter) {
fFilter= filter;
}
/**
* Returns the event filter.
*
* @return The event filter.
*/
public IPropertyChangeEventFilter getFilter() {
return fFilter;
}
}
/*
* 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= getNewPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
private void updateKeyModifierMask() {
String modifiers= getNewPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
fKeyModifierMask= computeStateMask(modifiers);
if (fKeyModifierMask == -1) {
// Fallback to stored state mask
fKeyModifierMask= getNewPreferenceStore().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= getNewPreferenceStore();
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(getNewPreferenceStore(), 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.setDocumentPartitioning(IJavaPartitions.JAVA_PARTITIONING);
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;
}
}
}
/**
* 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= getNewPreferenceStore();
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= getNewPreferenceStore();
if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
super.run();
return;
}
// Ignore trailing white spaces
char character= document.getChar(position);
while (position > 0 && Character.isWhitespace(character)) {
--position;
character= document.getChar(position);
}
// Check whether left hand character of caret is valid identifier part
if (Character.isJavaIdentifierPart(character)) {
int offset= 0;
int order= CollationElementIterator.NULLORDER;
short previous= Short.MAX_VALUE;
short next= Short.MAX_VALUE;
// Acquire collator for partition around caret
final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position);
final String buffer= document.get(region.getOffset(), position - region.getOffset() + 1);
final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer);
// Iterate to first upper-case character
iterator.setOffset(buffer.length() - 1);
do {
// Check whether we reached begin of word or single upper-case start
offset= iterator.getOffset();
character= document.getChar(region.getOffset() + offset);
if (!Character.isJavaIdentifierPart(character))
throw new BadLocationException();
else if (Character.isUpperCase(character)) {
++offset;
break;
}
// Test next characters
order= iterator.previous();
next= CollationElementIterator.tertiaryOrder(order);
if (next <= previous)
previous= next;
else
break;
} while (order != CollationElementIterator.NULLORDER);
// Check left character for multiple upper-case characters
position= position - buffer.length() + offset - 1;
character= document.getChar(position);
while (position >= 0 && Character.isUpperCase(character))
character= document.getChar(--position);
setCaretPosition(position + 1);
getTextWidget().showSelection();
fireSelectionChanged();
return;
}
} catch (BadLocationException exception) {
// Use default behavior
}
super.run();
}
/**
* Sets the caret position to the sub-word boundary given with <code>position</code>.
*
* @param position Position where the action should move the caret
*/
protected abstract void setCaretPosition(int position);
}
/**
* Text navigation action to navigate to the previous sub-word.
*
* @since 3.0
*/
protected class NavigatePreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new navigate previous sub-word action.
*/
public NavigatePreviousSubWordAction() {
super(ST.WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position));
}
}
/**
* Text operation action to delete the previous sub-word.
*
* @since 3.0
*/
protected class DeletePreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new delete previous sub-word action.
*/
public DeletePreviousSubWordAction() {
super(ST.DELETE_WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
try {
viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$
} catch (BadLocationException exception) {
// Should not happen
}
}
}
/**
* Text operation action to select the previous sub-word.
*
* @since 3.0
*/
protected class SelectPreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new select previous sub-word action.
*/
public SelectPreviousSubWordAction() {
super(ST.SELECT_WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed()) {
final Point selection= text.getSelection();
final int caret= text.getCaretOffset();
final int offset= modelOffset2WidgetOffset(viewer, position);
if (caret == selection.x)
text.setSelectionRange(selection.y, offset - selection.y);
else
text.setSelectionRange(selection.x, offset - selection.x);
}
}
}
/**
* Quick format action to format the enclosing java element.
* <p>
* The quick format action works as follows:
* <ul>
* <li>If there is no selection and the caret is positioned on a Java element,
* only this element is formatted. If the element has some accompanying comment,
* then the comment is formatted as well.</li>
* <li>If the selection spans one or more partitions of the document, then all
* partitions covered by the selection are entirely formatted.</li>
* <p>
* Partitions at the end of the selection are not completed, except for comments.
*
* @since 3.0
*/
protected class QuickFormatAction extends Action {
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
final JavaSourceViewer viewer= (JavaSourceViewer) getSourceViewer();
if (viewer.isEditable()) {
final Point selection= viewer.rememberSelection();
try {
viewer.setRedraw(false);
final String type= TextUtilities.getContentType(viewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, selection.x);
if (type.equals(IDocument.DEFAULT_CONTENT_TYPE) && selection.y == 0) {
try {
final IJavaElement element= getElementAt(selection.x, true);
if (element != null && element.exists()) {
final int kind= element.getElementType();
if (kind == IJavaElement.TYPE || kind == IJavaElement.METHOD || kind == IJavaElement.INITIALIZER) {
final ISourceReference reference= (ISourceReference)element;
final ISourceRange range= reference.getSourceRange();
if (range != null) {
viewer.setSelectedRange(range.getOffset(), range.getLength());
viewer.doOperation(ISourceViewer.FORMAT);
}
}
}
} catch (JavaModelException exception) {
// Should not happen
}
} else {
viewer.setSelectedRange(selection.x, 1);
viewer.doOperation(ISourceViewer.FORMAT);
}
} catch (BadLocationException exception) {
// Can not happen
} finally {
viewer.setRedraw(true);
viewer.restoreSelection();
}
}
}
}
/**
* Internal activation listener.
* @since 3.0
*/
private class ActivationListener extends ShellAdapter {
/*
* @see org.eclipse.swt.events.ShellAdapter#shellActivated(org.eclipse.swt.events.ShellEvent)
*/
public void shellActivated(ShellEvent e) {
if (fMarkOccurrenceAnnotations && isActivePart())
SelectionListenerWithASTManager.getDefault().forceSelectionChange(JavaEditor.this, (ITextSelection)getSelectionProvider().getSelection());
}
/*
* @see org.eclipse.swt.events.ShellAdapter#shellDeactivated(org.eclipse.swt.events.ShellEvent)
*/
public void shellDeactivated(ShellEvent e) {
removeOccurrenceAnnotations();
}
}
/** Preference key for the link color */
protected final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR;
/** Preference key for matching brackets */
protected final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS;
/** Preference key for matching brackets color */
protected final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
/** Preference key for compiler task tags */
private final static String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS;
/** Preference key for browser like links */
private final static String BROWSER_LIKE_LINKS= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
/** Preference key for key modifier of browser like links */
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
/**
* Preference key for key modifier mask of browser like links.
* The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code>
* cannot be resolved to valid SWT modifier bits.
*
* @since 2.1.1
*/
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' };
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/**
* The editor selection changed listener.
*
* @since 3.0
*/
private EditorSelectionChangedListener fEditorSelectionChangedListener;
/** The selection changed listener */
protected AbstractSelectionChangedListener fOutlineSelectionChangedListener= new OutlineSelectionChangedListener();
/** The editor's bracket matcher */
protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS);
/** This editor's encoding support */
private DefaultEncodingSupport fEncodingSupport;
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/**
* 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;
/**
* Tells whether all occurrences of the element at the
* current caret location are automatically marked in
* this editor.
* @since 3.0
*/
private boolean fMarkOccurrenceAnnotations;
/**
* Tells whether the occurrence annotations are sticky
* i.e. whether they stay even if there's no valid Java
* element at the current caret position.
* @since 3.0
*/
private boolean fStickyOccurrenceAnnotations;
/**
* The internal shell activation listener for updating occurrences.
* @since 3.0
*/
private ActivationListener fActivationListener= new ActivationListener();
private ISelectionListenerWithAST fPostSelectionListenerWithAST;
private Job fOccurrencesFinderJob;
/**
* 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 newStore= createNewPreferenceStore(null);
setNewPreferenceStore(newStore, JavaPlugin.getDefault().getPreferenceStore());
setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" }); //$NON-NLS-1$
fMarkOccurrenceAnnotations= newStore.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES);
fStickyOccurrenceAnnotations= newStore.getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES);
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles);
StyledText text= viewer.getTextWidget();
text.addBidiSegmentListener(new BidiSegmentListener() {
public void lineGetSegments(BidiSegmentEvent event) {
event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
}
});
JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
// ensure source viewer decoration support has been created and configured
getSourceViewerDecorationSupport(viewer);
return viewer;
}
public final ISourceViewer getViewer() {
return getSourceViewer();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) {
return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
return affectsBehavior(event) || super.affectsTextPresentation(event);
}
/**
* Determines whether the preference change encoded by the given event
* changes the behavior of one of its contained components.
*
* @param event the event to be investigated
* @return <code>true</code> if event causes a behavioral change
* @since 3.0
*/
protected boolean affectsBehavior(PropertyChangeEvent event) {
JavaSourceViewerConfiguration configuration= (JavaSourceViewerConfiguration) getSourceViewerConfiguration();
return ((AbstractJavaScanner) configuration.getCodeScanner()).affectsBehavior(event)
|| ((AbstractJavaScanner) configuration.getMultilineCommentScanner()).affectsBehavior(event)
|| ((AbstractJavaScanner) configuration.getSinglelineCommentScanner()).affectsBehavior(event)
|| ((AbstractJavaScanner) configuration.getStringScanner()).affectsBehavior(event)
|| ((AbstractJavaScanner) configuration.getJavaDocScanner()).affectsBehavior(event);
}
/**
* Adapts the behavior of the contained components to the change
* encoded in the given event.
*
* @param event the event to which to adapt
* @since 3.0
*/
private void adaptTaskTagDependents(PropertyChangeEvent event) {
JavaSourceViewerConfiguration svc= (JavaSourceViewerConfiguration) getSourceViewerConfiguration();
if (((AbstractJavaScanner) svc.getCodeScanner()).affectsBehavior(event))
((AbstractJavaScanner) svc.getCodeScanner()).adaptToPreferenceChange(event);
if (((AbstractJavaScanner) svc.getMultilineCommentScanner()).affectsBehavior(event))
((AbstractJavaScanner) svc.getMultilineCommentScanner()).adaptToPreferenceChange(event);
if (((AbstractJavaScanner) svc.getSinglelineCommentScanner()).affectsBehavior(event))
((AbstractJavaScanner) svc.getSinglelineCommentScanner()).adaptToPreferenceChange(event);
if (((AbstractJavaScanner) svc.getStringScanner()).affectsBehavior(event))
((AbstractJavaScanner) svc.getStringScanner()).adaptToPreferenceChange(event);
if (((AbstractJavaScanner) svc.getJavaDocScanner()).affectsBehavior(event))
((AbstractJavaScanner) svc.getJavaDocScanner()).adaptToPreferenceChange(event);
}
/**
* Creates and returns the preference store for this Java editor with the given input.
*
* @param input The editor input for which to create the preference store
*
* @since 3.0
*/
private IPreferenceStore createNewPreferenceStore(IEditorInput input) {
List stores= new ArrayList(3);
IJavaProject project= EditorUtility.getJavaProject(input);
if (project != null)
stores.add(new OptionsAdapter(project.getOptions(false), JavaPlugin.getDefault().getMockupPreferenceStore(), new OptionsAdapter.IPropertyChangeEventFilter() {
public boolean isFiltered(PropertyChangeEvent event) {
IJavaElement inputJavaElement= getInputJavaElement();
IJavaProject javaProject= inputJavaElement != null ? inputJavaElement.getJavaProject() : null;
if (javaProject == null)
return true;
return !javaProject.getProject().equals(event.getSource());
}
}));
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
stores.add(tools.getPreferenceStore());
if (tools.getCorePreferenceStore() != null)
stores.add(new PreferencesAdapter(tools.getCorePreferenceStore()));
if (stores.size() == 1)
return (IPreferenceStore) stores.get(0);
return new ChainedPreferenceStore((IPreferenceStore[]) stores.toArray(new IPreferenceStore[stores.size()]));
}
/**
* 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 {
if (fEncodingSupport != null)
fEncodingSupport.reset();
setOutlinePageInput(fOutlinePage, input);
ISourceViewer sourceViewer= getSourceViewer();
if (!(sourceViewer instanceof ISourceViewerExtension2)) {
setNewPreferenceStore(createNewPreferenceStore(input));
super.doSetInput(input);
return;
}
// uninstall & unregister preference store listener
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
getSourceViewerDecorationSupport(sourceViewer).uninstall();
((ISourceViewerExtension2)sourceViewer).unconfigure();
setNewPreferenceStore(createNewPreferenceStore(input));
// install & register preference store listener
sourceViewer.configure(getSourceViewerConfiguration());
getSourceViewerDecorationSupport(sourceViewer).install(getNewPreferenceStore());
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
super.doSetInput(input);
}
/**
* {@inheritDoc}
*/
protected void setNewPreferenceStore(IPreferenceStore store, IPreferenceStore pre_3_0_Store) {
super.setNewPreferenceStore(store, pre_3_0_Store);
if (getSourceViewerConfiguration() instanceof JavaSourceViewerConfiguration)
((JavaSourceViewerConfiguration)getSourceViewerConfiguration()).setNewPreferenceStore(store);
}
/**
* {@inheritDoc}
*/
protected void setNewPreferenceStore(IPreferenceStore store) {
super.setNewPreferenceStore(store);
if (getSourceViewerConfiguration() instanceof JavaSourceViewerConfiguration)
((JavaSourceViewerConfiguration)getSourceViewerConfiguration()).setNewPreferenceStore(store);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
// cancel possible running computation
fMarkOccurrenceAnnotations= false;
uninstallOccurrencesFinder();
if (fActivationListener != null) {
Shell shell= getEditorSite().getShell();
if (shell != null && !shell.isDisposed())
shell.removeShellListener(fActivationListener);
fActivationListener= null;
}
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
if (fEncodingSupport != null) {
fEncodingSupport.dispose();
fEncodingSupport= null;
}
if (fBracketMatcher != null) {
fBracketMatcher.dispose();
fBracketMatcher= null;
}
if (fSelectionHistory != null) {
fSelectionHistory.dispose();
fSelectionHistory= null;
}
if (fEditorSelectionChangedListener != null) {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
super.dispose();
}
protected void createActions() {
super.createActions();
ActionGroup oeg, ovg, jsg, sg;
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
oeg= new OpenEditorActionGroup(this),
sg= new ShowActionGroup(this),
ovg= new OpenViewActionGroup(this),
jsg= new JavaSearchActionGroup(this)
});
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg});
ResourceAction resAction= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
resAction= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
resAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC);
setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
WorkbenchHelp.setHelp(resAction, IJavaHelpContextIds.SHOW_JAVADOC_ACTION);
Action action= new GotoMatchingBracketAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
fEncodingSupport= new DefaultEncodingSupport();
fEncodingSupport.initialize(this);
fSelectionHistory= new SelectionHistory(this);
action= new StructureSelectEnclosingAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING);
setAction(StructureSelectionAction.ENCLOSING, action);
action= new StructureSelectNextAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT);
setAction(StructureSelectionAction.NEXT, action);
action= new StructureSelectPreviousAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS);
setAction(StructureSelectionAction.PREVIOUS, action);
StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory);
historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST);
setAction(StructureSelectionAction.HISTORY, historyAction);
fSelectionHistory.setHistoryAction(historyAction);
action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
action= new QuickFormatAction();
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.QUICK_FORMAT);
setAction(IJavaEditorActionDefinitionIds.QUICK_FORMAT, action);
action= new RemoveOccurrenceAnnotations(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS);
setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$
// add annotation actions
action= new JavaSelectMarkerRulerAction2(JavaEditorMessages.getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$
setAction("AnnotationAction", 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 (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) {
boolean markOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue();
if (markOccurrenceAnnotations != fMarkOccurrenceAnnotations) {
fMarkOccurrenceAnnotations= markOccurrenceAnnotations;
if (!fMarkOccurrenceAnnotations)
uninstallOccurrencesFinder();
else
installOccurrencesFinder();
}
}
}
if (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
boolean stickyOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue();
if (stickyOccurrenceAnnotations != fStickyOccurrenceAnnotations) {
fStickyOccurrenceAnnotations= stickyOccurrenceAnnotations;
// if (!fMarkOccurrenceAnnotations)
// uninstallOccurrencesFinder();
// else
// installOccurrencesFinder();
}
}
}
if (COMPILER_TASK_TAGS.equals(event.getProperty()))
adaptTaskTagDependents(event);
} 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= getNewPreferenceStore();
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;
}
}
/**
* 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);
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);
if (fMarkOccurrenceAnnotations)
installOccurrencesFinder();
getEditorSite().getShell().addShellListener(fActivationListener);
}
protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
support.setCharacterPairMatcher(fBracketMatcher);
support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
super.configureSourceViewerDecorationSupport(support);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#gotoMarker(org.eclipse.core.resources.IMarker)
*/
public void gotoMarker(IMarker marker) {
fLastMarkerTarget= marker;
if (!fIsUpdatingAnnotationViews) {
super.gotoMarker(marker);
}
}
/**
* Jumps to the next enabled annotation according to the given direction.
* An annotation type is enabled if it is configured to be in the
* Next/Previous tool bar drop down menu and if it is checked.
*
* @param forward <code>true</code> if search direction is forward, <code>false</code> if backward
*/
public void gotoAnnotation(boolean forward) {
ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection();
Position position= new Position(0, 0);
if (false /* delayed - see bug 18316 */) {
getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
selectAndReveal(position.getOffset(), position.getLength());
} else /* no delay - see bug 18316 */ {
Annotation annotation= getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
setStatusLineErrorMessage(null);
setStatusLineMessage(null);
if (annotation != null) {
updateAnnotationViews(annotation);
selectAndReveal(position.getOffset(), position.getLength());
setStatusLineMessage(annotation.getText());
}
}
}
/**
* Updates the annotation views that show the given annotation.
*
* @param annotation the annotation
*/
private void updateAnnotationViews(Annotation annotation) {
IMarker marker= null;
if (annotation instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) annotation).getMarker();
else if (annotation instanceof IJavaAnnotation) {
Iterator e= ((IJavaAnnotation) annotation).getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null && !marker.equals(fLastMarkerTarget)) {
try {
boolean isProblem= marker.isSubtypeOf(IMarker.PROBLEM);
IWorkbenchPage page= getSite().getPage();
IViewPart view= page.findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW: IPageLayout.ID_TASK_LIST); //$NON-NLS-1$ //$NON-NLS-2$
if (view != null) {
Method method= view.getClass().getMethod("setSelection", new Class[] { IStructuredSelection.class, boolean.class}); //$NON-NLS-1$
method.invoke(view, new Object[] {new StructuredSelection(marker), Boolean.TRUE });
}
} catch (CoreException x) {
} catch (NoSuchMethodException x) {
} catch (IllegalAccessException x) {
} catch (InvocationTargetException x) {
}
// ignore exceptions, don't update any of the lists, just set statusline
}
}
/**
* Finds and marks occurrence annotations.
*
* @since 3.0
*/
class OccurrencesFinderJob extends Job implements IDocumentListener {
private IDocument fDocument;
private boolean fCancelled= false;
private IProgressMonitor fProgressMonitor;
private Position[] fPositions;
public OccurrencesFinderJob(IDocument document, Position[] positions) {
super("Occurrences Marker"); //$NON-NLS-1$
fDocument= document;
fPositions= positions;
fDocument.addDocumentListener(this);
}
private boolean isCancelled() {
return fCancelled || fProgressMonitor.isCanceled();
}
/*
* @see Job#run(org.eclipse.core.runtime.IProgressMonitor)
*/
public IStatus run(IProgressMonitor progressMonitor) {
fProgressMonitor= progressMonitor;
try {
if (isCancelled())
return Status.CANCEL_STATUS;
ITextViewer textViewer= getViewer();
if (textViewer == null)
return Status.CANCEL_STATUS;
IDocument document= textViewer.getDocument();
if (document == null)
return Status.CANCEL_STATUS;
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider == null)
return Status.CANCEL_STATUS;
IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
if (annotationModel == null)
return Status.CANCEL_STATUS;
// Add occurrence annotations
int length= fPositions.length;
Map annotationMap= new HashMap(length);
for (int i= 0; i < length; i++) {
if (isCancelled())
return Status.CANCEL_STATUS;
String message;
Position position= fPositions[i];
// Create & add annotation
try {
message= document.get(position.offset, position.length);
} catch (BadLocationException ex) {
// Skip this match
continue;
}
annotationMap.put(
new Annotation("org.eclipse.jdt.ui.occurrences", false, message), //$NON-NLS-1$
position);
}
if (isCancelled())
return Status.CANCEL_STATUS;
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);
}
return Status.OK_STATUS;
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentAboutToBeChanged(DocumentEvent event) {
fCancelled= true;
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
}
}
/**
* Updates the occurrences annotations based
* on the current selection.
*
* @since 3.0
*/
protected void updateOccurrenceAnnotations(ITextSelection selection, CompilationUnit astRoot) {
if (!fMarkOccurrenceAnnotations)
return;
if (astRoot == null || selection == null)
return;
IDocument document= getSourceViewer().getDocument();
if (document == null)
return;
if (fOccurrencesFinderJob != null)
fOccurrencesFinderJob.cancel();
ExceptionOccurrencesFinder exceptionFinder= new ExceptionOccurrencesFinder();
String message= exceptionFinder.initialize(astRoot, selection.getOffset(), selection.getLength());
List matches= new ArrayList();
if (message == null) {
matches= exceptionFinder.perform();
}
if (matches.size() == 0) {
ASTNode node= NodeFinder.perform(astRoot, selection.getOffset(), selection.getLength());
if (!(node instanceof Name)) {
if (!fStickyOccurrenceAnnotations)
removeOccurrenceAnnotations();
return;
}
IBinding binding= ((Name)node).resolveBinding();
if (binding == null && fStickyOccurrenceAnnotations)
return;
// Find the matches && extract positions so we can forget the AST
OccurrencesFinder finder = new OccurrencesFinder(binding);
message= finder.initialize(astRoot, selection.getOffset(), selection.getLength());
if (message == null) {
matches= finder.perform();
}
}
Position[] positions= new Position[matches.size()];
int i= 0;
for (Iterator each= matches.iterator(); each.hasNext();) {
ASTNode currentNode= (ASTNode)each.next();
positions[i++]= new Position(currentNode.getStartPosition(), currentNode.getLength());
}
fOccurrencesFinderJob= new OccurrencesFinderJob(document, positions);
//fOccurrencesFinderJob.setPriority(Job.DECORATE);
//fOccurrencesFinderJob.setSystem(true);
//fOccurrencesFinderJob.schedule();
((OccurrencesFinderJob) fOccurrencesFinderJob).run(new NullProgressMonitor());
}
protected void installOccurrencesFinder() {
fMarkOccurrenceAnnotations= true;
fPostSelectionListenerWithAST= new ISelectionListenerWithAST() {
public void selectionChanged(IEditorPart part, ITextSelection selection, CompilationUnit astRoot) {
updateOccurrenceAnnotations(selection, astRoot);
}
};
SelectionListenerWithASTManager.getDefault().addListener(this, fPostSelectionListenerWithAST);
}
protected void uninstallOccurrencesFinder() {
fMarkOccurrenceAnnotations= false;
if (fOccurrencesFinderJob != null) {
fOccurrencesFinderJob.cancel();
fOccurrencesFinderJob= null;
}
if (fPostSelectionListenerWithAST != null) {
SelectionListenerWithASTManager.getDefault().removeListener(this, fPostSelectionListenerWithAST);
fPostSelectionListenerWithAST= null;
}
removeOccurrenceAnnotations();
}
void removeOccurrenceAnnotations() {
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider == null)
return;
IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
if (annotationModel == null || fOccurrenceAnnotations == null)
return;
synchronized (annotationModel) {
if (annotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
} else {
for (int i= 0, length= fOccurrenceAnnotations.length; i < length; i++)
annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
}
fOccurrenceAnnotations= null;
}
}
/**
* Returns the Java element wrapped by this editors input.
*
* @return the Java element wrapped by this editors input.
* @since 3.0
*/
abstract protected IJavaElement getInputJavaElement();
protected void updateStatusLine() {
ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection();
Annotation annotation= getAnnotation(selection.getOffset(), selection.getLength());
setStatusLineErrorMessage(null);
setStatusLineMessage(null);
if (annotation != null) {
try {
fIsUpdatingAnnotationViews= true;
updateAnnotationViews(annotation);
} finally {
fIsUpdatingAnnotationViews= false;
}
if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation) annotation).isProblem())
setStatusLineMessage(annotation.getText());
}
}
/**
* Jumps to the matching bracket.
*/
public void gotoMatchingBracket() {
ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
if (document == null)
return;
IRegion selection= getSignedSelection(sourceViewer);
int selectionLength= Math.abs(selection.getLength());
if (selectionLength > 1) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
// #26314
int sourceCaretOffset= selection.getOffset() + selection.getLength();
if (isSurroundedByBrackets(document, sourceCaretOffset))
sourceCaretOffset -= selection.getLength();
IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
if (region == null) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
int offset= region.getOffset();
int length= region.getLength();
if (length < 1)
return;
int anchor= fBracketMatcher.getAnchor();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset + 1: offset + length;
boolean visible= false;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion= sourceViewer.getVisibleRegion();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
}
if (!visible) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
if (selection.getLength() < 0)
targetOffset -= selection.getLength();
sourceViewer.setSelectedRange(targetOffset, selection.getLength());
sourceViewer.revealRange(targetOffset, selection.getLength());
}
/**
* Sets the given message as error message to this editor's status line.
*
* @param msg message to be set
*/
protected void setStatusLineErrorMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
}
/**
* Sets the given message as message to this editor's status line.
*
* @param msg message to be set
* @since 3.0
*/
protected void setStatusLineMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(false, msg, null);
}
/**
* Returns the signed current selection.
* The length will be negative if the resulting selection
* is right-to-left (RtoL).
* <p>
* The selection offset is model based.
* </p>
*
* @param sourceViewer the source viewer
* @return a region denoting the current signed selection, for a resulting RtoL selections lenght is < 0
*/
protected IRegion getSignedSelection(ISourceViewer sourceViewer) {
StyledText text= sourceViewer.getTextWidget();
Point selection= text.getSelectionRange();
if (text.getCaretOffset() == selection.x) {
selection.x= selection.x + selection.y;
selection.y= -selection.y;
}
selection.x= widgetOffset2ModelOffset(sourceViewer, selection.x);
return new Region(selection.x, selection.y);
}
private static boolean isBracket(char character) {
for (int i= 0; i != BRACKETS.length; ++i)
if (character == BRACKETS[i])
return true;
return false;
}
private static boolean isSurroundedByBrackets(IDocument document, int offset) {
if (offset == 0 || offset == document.getLength())
return false;
try {
return
isBracket(document.getChar(offset - 1)) &&
isBracket(document.getChar(offset));
} catch (BadLocationException e) {
return false;
}
}
/**
* Returns the annotation closest to the given range respecting the given
* direction. If an annotation is found, the annotations current position
* is copied into the provided annotation position.
*
* @param offset the region offset
* @param length the region length
* @param forward <code>true</code> for forwards, <code>false</code> for backward
* @param annotationPosition the position of the found annotation
* @return the found annotation
*/
private Annotation getNextAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) {
Annotation nextAnnotation= null;
Position nextAnnotationPosition= null;
Annotation containingAnnotation= null;
Position containingAnnotationPosition= null;
boolean currentAnnotation= false;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= Integer.MAX_VALUE;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true, true);
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation)a).hasOverlay() || !isNavigationTarget(a))
continue;
Position p= model.getPosition(a);
if (p == null)
continue;
if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || p.includes(offset)) {
if (containingAnnotation == null || (forward && p.length >= containingAnnotationPosition.length || !forward && p.length >= containingAnnotationPosition.length)) {
containingAnnotation= a;
containingAnnotationPosition= p;
currentAnnotation= p.length == length;
}
} else {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument + currentDistance;
if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
} else {
currentDistance= offset + length - (p.getOffset() + p.length);
if (currentDistance < 0)
currentDistance= endOfDocument + currentDistance;
if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
}
}
}
if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) {
annotationPosition.setOffset(containingAnnotationPosition.getOffset());
annotationPosition.setLength(containingAnnotationPosition.getLength());
return containingAnnotation;
}
if (nextAnnotationPosition != null) {
annotationPosition.setOffset(nextAnnotationPosition.getOffset());
annotationPosition.setLength(nextAnnotationPosition.getLength());
}
return nextAnnotation;
}
/**
* Returns the annotation overlapping with the given range or <code>null</code>.
*
* @param offset the region offset
* @param length the region length
* @return the found annotation or <code>null</code>
* @since 3.0
*/
private Annotation getAnnotation(int offset, int length) {
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true, true);
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if (!isNavigationTarget(a))
continue;
Position p= model.getPosition(a);
if (p != null && p.overlapsWith(offset, length))
return a;
}
return null;
}
/**
* Returns whether the given annotation is configured as a target for the
* "Go to Next/Previous Annotation" actions
*
* @param annotation the annotation
* @return <code>true</code> if this is a target, <code>false</code>
* otherwise
* @since 3.0
*/
private boolean isNavigationTarget(Annotation annotation) {
Preferences preferences= Platform.getPlugin(EditorsUI.PLUGIN_ID).getPluginPreferences();
AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(annotation);
// See bug 41689
// String key= forward ? preference.getIsGoToNextNavigationTargetKey() : preference.getIsGoToPreviousNavigationTargetKey();
String key= preference == null ? null : preference.getIsGoToNextNavigationTargetKey();
return (key != null && preferences.getBoolean(key));
}
/**
* Computes and returns the source reference that includes the caret and
* serves as provider for the outline page selection and the editor range
* indication.
*
* @return the computed source reference
* @since 3.0
*/
protected ISourceReference computeHighlightRangeSourceReference() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return null;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return null;
int caret= 0;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3)sourceViewer;
caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} else {
int offset= sourceViewer.getVisibleRegion().getOffset();
caret= offset + styledText.getCaretOffset();
}
IJavaElement element= getElementAt(caret, false);
if ( !(element instanceof ISourceReference))
return null;
if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
IImportDeclaration declaration= (IImportDeclaration) element;
IImportContainer container= (IImportContainer) declaration.getParent();
ISourceRange srcRange= null;
try {
srcRange= container.getSourceRange();
} catch (JavaModelException e) {
}
if (srcRange != null && srcRange.getOffset() == caret)
return container;
}
return (ISourceReference) element;
}
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @param reconcile <code>true</code> if editor input should be reconciled in advance
* @return the most narrow java element
* @since 3.0
*/
protected IJavaElement getElementAt(int offset, boolean reconcile) {
return getElementAt(offset);
}
/*
* @see org.eclipse.ui.texteditor.ExtendedTextEditor#createChangeHover()
*/
protected LineChangeHover createChangeHover() {
return new JavaChangeHover(IJavaPartitions.JAVA_PARTITIONING);
}
protected boolean isPrefQuickDiffAlwaysOn() {
return false; // never show change ruler for the non-editable java editor. Overridden in subclasses like CompilationUnitEditor
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions()
*/
protected void createNavigationActions() {
super.createNavigationActions();
final StyledText textWidget= getSourceViewer().getTextWidget();
IAction action= new SmartLineStartAction(textWidget, false);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START);
setAction(ITextEditorActionDefinitionIds.LINE_START, action);
action= new SmartLineStartAction(textWidget, true);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START);
setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action);
action= new NavigatePreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS);
setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL);
action= new NavigateNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT);
setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL);
action= new DeletePreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD);
setAction(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.BS, SWT.NULL);
action= new DeleteNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD);
setAction(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.DEL, SWT.NULL);
action= new SelectPreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS);
setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL);
action= new SelectNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT);
setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL);
}
/*
* @see org.eclipse.ui.texteditor.ExtendedTextEditor#createCompositeRuler()
*/
protected CompositeRuler createCompositeRuler() {
if (!getNewPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER))
return super.createCompositeRuler();
CompositeRuler ruler= new CompositeRuler();
AnnotationRulerColumn column= new AnnotationRulerColumn(VERTICAL_RULER_WIDTH, getAnnotationAccess());
column.setHover(new JavaExpandHover(ruler, ruler, new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
// for now: just invoke ruler double click action
triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK);
}
private void triggerAction(String actionID) {
IAction action= getAction(actionID);
if (action != null) {
if (action instanceof IUpdate)
((IUpdate) action).update();
// hack to propagate line change
if (action instanceof ISelectionListener) {
((ISelectionListener)action).selectionChanged(null, null);
}
if (action.isEnabled())
action.run();
}
}
}, getAnnotationAccess()));
ruler.addDecorator(0, column);
if (isLineNumberRulerVisible())
ruler.addDecorator(1, createLineNumberRulerColumn());
else if (isPrefQuickDiffAlwaysOn())
ruler.addDecorator(1, createChangeRulerColumn());
return ruler;
}
}
|
53,010 |
Bug 53010 Editor preferences do not take effect on open editors
|
I-20040224 Go to the Java > Editor > Syntax preference page. Change the keyword color to red. Press Ok. At this point, we use to see the preview update. Not on this build (problem #1). Press Ok, and close the pref dialog. The java editor that was already open did not update. I had to close it and reopen it for the colors to take effect (problem #2)
|
resolved fixed
|
f994e36
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-27T14:35:47Z | 2004-02-25T00:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/JavaSourceViewerConfiguration.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.text;
import java.util.Vector;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.AbstractInformationControlManager;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DefaultTextDoubleClickStrategy;
import org.eclipse.jface.text.IAutoIndentStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.ITextDoubleClickStrategy;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.formatter.ContentFormatter2;
import org.eclipse.jface.text.formatter.IContentFormatter;
import org.eclipse.jface.text.formatter.IFormattingStrategy;
import org.eclipse.jface.text.information.IInformationPresenter;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.presentation.IPresentationReconciler;
import org.eclipse.jface.text.presentation.PresentationReconciler;
import org.eclipse.jface.text.reconciler.IReconciler;
import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
import org.eclipse.jface.text.rules.RuleBasedScanner;
import org.eclipse.jface.text.source.IAnnotationHover;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.ui.texteditor.ChainedPreferenceStore;
import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.PreferencesAdapter;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.AbstractJavaScanner;
import org.eclipse.jdt.internal.ui.text.ContentAssistPreference;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.JavaAnnotationHover;
import org.eclipse.jdt.internal.ui.text.JavaCommentScanner;
import org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy;
import org.eclipse.jdt.internal.ui.text.JavaElementProvider;
import org.eclipse.jdt.internal.ui.text.JavaOutlineInformationControl;
import org.eclipse.jdt.internal.ui.text.JavaReconciler;
import org.eclipse.jdt.internal.ui.text.SingleTokenJavaScanner;
import org.eclipse.jdt.internal.ui.text.comment.CommentFormattingStrategy;
import org.eclipse.jdt.internal.ui.text.comment.JavaDocRegion;
import org.eclipse.jdt.internal.ui.text.comment.JavaSnippetFormattingStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaCodeScanner;
import org.eclipse.jdt.internal.ui.text.java.JavaCompletionProcessor;
import org.eclipse.jdt.internal.ui.text.java.JavaDoubleClickSelector;
import org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaStringAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaStringDoubleClickSelector;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaInformationProvider;
import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocCompletionProcessor;
import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocScanner;
import org.eclipse.jdt.internal.ui.text.spelling.WordCompletionProcessor;
import org.eclipse.jdt.internal.ui.typehierarchy.HierarchyInformationControl;
/**
* Configuration for a source viewer which shows Java code.
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*/
public class JavaSourceViewerConfiguration extends SourceViewerConfiguration {
/**
* Preference key used to look up display tab width.
*
* @since 2.0
* @deprecated As of 3.0 replaced by {@link ExtendedTextEditorPreferenceConstants#EDITOR_TAB_WIDTH}
*/
public final static String PREFERENCE_TAB_WIDTH= PreferenceConstants.EDITOR_TAB_WIDTH;
/**
* Preference key for inserting spaces rather than tabs.
*
* @since 2.0
*/
public final static String SPACES_FOR_TABS= PreferenceConstants.EDITOR_SPACES_FOR_TABS;
private JavaTextTools fJavaTextTools;
private ITextEditor fTextEditor;
private String fDocumentPartitioning;
/**
* The Java source code scanner
*
* @since 3.0
*/
private AbstractJavaScanner fCodeScanner;
/**
* The Java multiline comment scanner
*
* @since 3.0
*/
private AbstractJavaScanner fMultilineCommentScanner;
/**
* The Java singleline comment scanner
*
* @since 3.0
*/
private AbstractJavaScanner fSinglelineCommentScanner;
/**
* The Java string scanner
*
* @since 3.0
*/
private AbstractJavaScanner fStringScanner;
/**
* The JavaDoc scanner
*
* @since 3.0
*/
private AbstractJavaScanner fJavaDocScanner;
/**
* The new preference store
* <p>Note that this is work in progress and still subject to change.</p>
*
* @since 3.0
*/
private IPreferenceStore fNewPreferenceStore;
/**
* Creates a new Java source viewer configuration for viewers in the given editor
* using the given Java tools and the specified document partitioning.
*
* @param tools the Java text tools to be used
* @param editor the editor in which the configured viewer(s) will reside
* @param partitioning the document partitioning for this configuration
* @see JavaTextTools
* @since 3.0
*/
public JavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor, String partitioning) {
fJavaTextTools= tools;
fTextEditor= editor;
fDocumentPartitioning= partitioning;
setNewPreferenceStore(createNewPreferenceStore());
}
/**
* Creates a new Java source viewer configuration for viewers in the given editor
* using the given Java tools.
*
* @param tools the Java text tools to be used
* @param editor the editor in which the configured viewer(s) will reside
* @see JavaTextTools
*/
public JavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor) {
this(tools, editor, null);
}
/**
* Returns the Java source code scanner for this configuration.
*
* @return the Java source code scanner
*/
public RuleBasedScanner getCodeScanner() {
return fCodeScanner;
}
/**
* Returns the Java multiline comment scanner for this configuration.
*
* @return the Java multiline comment scanner
* @since 2.0
*/
public RuleBasedScanner getMultilineCommentScanner() {
return fMultilineCommentScanner;
}
/**
* Returns the Java singleline comment scanner for this configuration.
*
* @return the Java singleline comment scanner
* @since 2.0
*/
public RuleBasedScanner getSinglelineCommentScanner() {
return fSinglelineCommentScanner;
}
/**
* Returns the Java string scanner for this configuration.
*
* @return the Java string scanner
* @since 2.0
*/
public RuleBasedScanner getStringScanner() {
return fStringScanner;
}
/**
* Returns the JavaDoc scanner for this configuration.
*
* @return the JavaDoc scanner
*/
public RuleBasedScanner getJavaDocScanner() {
return fJavaDocScanner;
}
/**
* Returns the color manager for this configuration.
*
* @return the color manager
*/
protected IColorManager getColorManager() {
return fJavaTextTools.getColorManager();
}
/**
* Returns the editor in which the configured viewer(s) will reside.
*
* @return the enclosing editor
*/
protected ITextEditor getEditor() {
return fTextEditor;
}
/**
* Returns the preference store used by this configuration to initialize
* the individual bits and pieces.
* <p>
* FIXME: deprecate when new API is stabilized.
* </p>
*
* @return the preference store used to initialize this configuration
* @since 2.0
*/
public IPreferenceStore getPreferenceStore() {
return fJavaTextTools.getPreferenceStore();
}
/**
* Returns the new preference store used by this configuration to initialize
* the individual bits and pieces.
* <p>
* XXX: Note that this is work in progress and API is still subject to change.
* </p>
*
* @return the new preference store used to initialize this configuration
*
* @since 3.0
*/
public IPreferenceStore getNewPreferenceStore() {
return fNewPreferenceStore;
}
/**
* Sets the preference store used by this configuration to initialize
* the individual bits and pieces to the given preference store.
* <p>
* XXX: Note that this is work in progress and API is still subject to change.
* </p>
*
* @param preferenceStore the preference store to initialize this configuration
*
* @since 3.0
*/
public void setNewPreferenceStore(IPreferenceStore preferenceStore) {
fNewPreferenceStore= preferenceStore;
initializeScanners();
}
/**
* Creates and returns a new preference store which combines the preference
* stores from the text tools.
*
* @param tools Text tools
* @return Legacy preference store
*
* @since 3.0
*/
private IPreferenceStore createNewPreferenceStore() {
if (fJavaTextTools.getCorePreferenceStore() == null)
return fJavaTextTools.getPreferenceStore();
return new ChainedPreferenceStore(new IPreferenceStore[] { fJavaTextTools.getPreferenceStore(), new PreferencesAdapter(fJavaTextTools.getCorePreferenceStore()) });
}
/**
* Initializes the scanners.
*
* @since 3.0
*/
private void initializeScanners() {
fCodeScanner= new JavaCodeScanner(getColorManager(), getNewPreferenceStore());
fMultilineCommentScanner= new JavaCommentScanner(getColorManager(), getNewPreferenceStore(), IJavaColorConstants.JAVA_MULTI_LINE_COMMENT);
fSinglelineCommentScanner= new JavaCommentScanner(getColorManager(), getNewPreferenceStore(), IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT);
fStringScanner= new SingleTokenJavaScanner(getColorManager(), getNewPreferenceStore(), IJavaColorConstants.JAVA_STRING);
fJavaDocScanner= new JavaDocScanner(getColorManager(), getNewPreferenceStore());
}
/*
* @see SourceViewerConfiguration#getPresentationReconciler(ISourceViewer)
*/
public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
PresentationReconciler reconciler= new PresentationReconciler();
reconciler.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
DefaultDamagerRepairer dr= new DefaultDamagerRepairer(getCodeScanner());
reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
dr= new DefaultDamagerRepairer(getJavaDocScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_DOC);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_DOC);
dr= new DefaultDamagerRepairer(getMultilineCommentScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
dr= new DefaultDamagerRepairer(getSinglelineCommentScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
dr= new DefaultDamagerRepairer(getStringScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_STRING);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_STRING);
dr= new DefaultDamagerRepairer(getStringScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_CHARACTER);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_CHARACTER);
return reconciler;
}
/*
* @see SourceViewerConfiguration#getContentAssistant(ISourceViewer)
*/
public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
if (getEditor() != null) {
ContentAssistant assistant= new ContentAssistant();
assistant.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
assistant.setRestoreCompletionProposalSize(getSettings("completion_proposal_size")); //$NON-NLS-1$
IContentAssistProcessor processor= new JavaCompletionProcessor(getEditor());
assistant.setContentAssistProcessor(processor, IDocument.DEFAULT_CONTENT_TYPE);
// Register the same processor for strings and single line comments to get code completion at the start of those partitions.
assistant.setContentAssistProcessor(processor, IJavaPartitions.JAVA_STRING);
assistant.setContentAssistProcessor(processor, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
processor= new WordCompletionProcessor();
assistant.setContentAssistProcessor(processor, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
assistant.setContentAssistProcessor(processor, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
assistant.setContentAssistProcessor(processor, IJavaPartitions.JAVA_STRING);
assistant.setContentAssistProcessor(new JavaDocCompletionProcessor(getEditor()), IJavaPartitions.JAVA_DOC);
ContentAssistPreference.configure(assistant, getNewPreferenceStore());
assistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE);
assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
return assistant;
}
return null;
}
/*
* @see SourceViewerConfiguration#getReconciler(ISourceViewer)
*/
public IReconciler getReconciler(ISourceViewer sourceViewer) {
final ITextEditor editor= getEditor();
if (editor != null && editor.isEditable()) {
JavaCompositeReconcilingStrategy strategy= new JavaCompositeReconcilingStrategy(editor, getConfiguredDocumentPartitioning(sourceViewer));
JavaReconciler reconciler= new JavaReconciler(editor, strategy, false);
reconciler.setIsIncrementalReconciler(false);
reconciler.setProgressMonitor(new NullProgressMonitor());
reconciler.setDelay(500);
return reconciler;
}
return null;
}
/*
* @see SourceViewerConfiguration#getAutoIndentStrategy(ISourceViewer, String)
*/
public IAutoIndentStrategy getAutoIndentStrategy(ISourceViewer sourceViewer, String contentType) {
if (IJavaPartitions.JAVA_DOC.equals(contentType) ||
IJavaPartitions.JAVA_MULTI_LINE_COMMENT.equals(contentType))
return new JavaDocAutoIndentStrategy(getConfiguredDocumentPartitioning(sourceViewer));
else if (IJavaPartitions.JAVA_STRING.equals(contentType))
return new JavaStringAutoIndentStrategy(getConfiguredDocumentPartitioning(sourceViewer));
return new JavaAutoIndentStrategy(getConfiguredDocumentPartitioning(sourceViewer));
}
/*
* @see SourceViewerConfiguration#getDoubleClickStrategy(ISourceViewer, String)
*/
public ITextDoubleClickStrategy getDoubleClickStrategy(ISourceViewer sourceViewer, String contentType) {
if (IJavaPartitions.JAVA_DOC.equals(contentType) ||
IJavaPartitions.JAVA_MULTI_LINE_COMMENT.equals(contentType) ||
IJavaPartitions.JAVA_SINGLE_LINE_COMMENT.equals(contentType))
return new DefaultTextDoubleClickStrategy();
else if (IJavaPartitions.JAVA_STRING.equals(contentType) ||
IJavaPartitions.JAVA_CHARACTER.equals(contentType))
return new JavaStringDoubleClickSelector(getConfiguredDocumentPartitioning(sourceViewer));
return new JavaDoubleClickSelector();
}
/*
* @see SourceViewerConfiguration#getDefaultPrefixes(ISourceViewer, String)
* @since 2.0
*/
public String[] getDefaultPrefixes(ISourceViewer sourceViewer, String contentType) {
return new String[] { "//", "" }; //$NON-NLS-1$ //$NON-NLS-2$
}
/*
* @see SourceViewerConfiguration#getIndentPrefixes(ISourceViewer, String)
*/
public String[] getIndentPrefixes(ISourceViewer sourceViewer, String contentType) {
Vector vector= new Vector();
// prefix[0] is either '\t' or ' ' x tabWidth, depending on useSpaces
int tabWidth= CodeFormatterUtil.getTabWidth();
boolean useSpaces= getNewPreferenceStore().getBoolean(SPACES_FOR_TABS);
for (int i= 0; i <= tabWidth; i++) {
StringBuffer prefix= new StringBuffer();
if (useSpaces) {
for (int j= 0; j + i < tabWidth; j++)
prefix.append(' ');
if (i != 0)
prefix.append('\t');
} else {
for (int j= 0; j < i; j++)
prefix.append(' ');
if (i != tabWidth)
prefix.append('\t');
}
vector.add(prefix.toString());
}
vector.add(""); //$NON-NLS-1$
return (String[]) vector.toArray(new String[vector.size()]);
}
/*
* @see SourceViewerConfiguration#getTabWidth(ISourceViewer)
*/
public int getTabWidth(ISourceViewer sourceViewer) {
IPreferenceStore store= fNewPreferenceStore;
if (fNewPreferenceStore == null)
// backwards compatibility code
store= getPreferenceStore();
if (store.contains(ExtendedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH))
return store.getInt(ExtendedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH);
else
// backwards compatibility code
return store.getInt(PREFERENCE_TAB_WIDTH);
}
/*
* @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer)
*/
public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) {
return new JavaAnnotationHover(JavaAnnotationHover.VERTICAL_RULER_HOVER);
}
/*
* @see SourceViewerConfiguration#getOverviewRulerAnnotationHover(ISourceViewer)
* @since 3.0
*/
public IAnnotationHover getOverviewRulerAnnotationHover(ISourceViewer sourceViewer) {
return new JavaAnnotationHover(JavaAnnotationHover.OVERVIEW_RULER_HOVER);
}
/*
* @see SourceViewerConfiguration#getConfiguredTextHoverStateMasks(ISourceViewer, String)
* @since 2.1
*/
public int[] getConfiguredTextHoverStateMasks(ISourceViewer sourceViewer, String contentType) {
JavaEditorTextHoverDescriptor[] hoverDescs= JavaPlugin.getDefault().getJavaEditorTextHoverDescriptors();
int stateMasks[]= new int[hoverDescs.length];
int stateMasksLength= 0;
for (int i= 0; i < hoverDescs.length; i++) {
if (hoverDescs[i].isEnabled()) {
int j= 0;
int stateMask= hoverDescs[i].getStateMask();
while (j < stateMasksLength) {
if (stateMasks[j] == stateMask)
break;
j++;
}
if (j == stateMasksLength)
stateMasks[stateMasksLength++]= stateMask;
}
}
if (stateMasksLength == hoverDescs.length)
return stateMasks;
int[] shortenedStateMasks= new int[stateMasksLength];
System.arraycopy(stateMasks, 0, shortenedStateMasks, 0, stateMasksLength);
return shortenedStateMasks;
}
/*
* @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int)
* @since 2.1
*/
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) {
JavaEditorTextHoverDescriptor[] hoverDescs= JavaPlugin.getDefault().getJavaEditorTextHoverDescriptors();
int i= 0;
while (i < hoverDescs.length) {
if (hoverDescs[i].isEnabled() && hoverDescs[i].getStateMask() == stateMask)
return new JavaEditorTextHoverProxy(hoverDescs[i], getEditor());
i++;
}
return null;
}
/*
* @see SourceViewerConfiguration#getTextHover(ISourceViewer, String)
*/
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
return getTextHover(sourceViewer, contentType, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
/*
* @see SourceViewerConfiguration#getConfiguredContentTypes(ISourceViewer)
*/
public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
return new String[] {
IDocument.DEFAULT_CONTENT_TYPE,
IJavaPartitions.JAVA_DOC,
IJavaPartitions.JAVA_MULTI_LINE_COMMENT,
IJavaPartitions.JAVA_SINGLE_LINE_COMMENT,
IJavaPartitions.JAVA_STRING,
IJavaPartitions.JAVA_CHARACTER
};
}
/*
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredDocumentPartitioning(org.eclipse.jface.text.source.ISourceViewer)
*/
public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) {
if (fDocumentPartitioning != null)
return fDocumentPartitioning;
return super.getConfiguredDocumentPartitioning(sourceViewer);
}
/*
* @see SourceViewerConfiguration#getContentFormatter(ISourceViewer)
*/
public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) {
final ContentFormatter2 formatter= new ContentFormatter2();
formatter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
IFormattingStrategy strategy= new JavaFormattingStrategy(sourceViewer);
formatter.setFormattingStrategy(strategy);
formatter.setFormattingStrategy(strategy, IDocument.DEFAULT_CONTENT_TYPE);
formatter.setFormattingStrategy(new CommentFormattingStrategy(formatter, sourceViewer), IJavaPartitions.JAVA_DOC);
formatter.setFormattingStrategy(new CommentFormattingStrategy(formatter, sourceViewer), IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
formatter.setFormattingStrategy(new CommentFormattingStrategy(formatter, sourceViewer), IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
formatter.setFormattingStrategy(new JavaSnippetFormattingStrategy(sourceViewer), JavaDocRegion.JAVA_SNIPPET_PARTITION);
return formatter;
}
/*
* @see SourceViewerConfiguration#getInformationControlCreator(ISourceViewer)
* @since 2.0
*/
public IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
return new DefaultInformationControl(parent, SWT.NONE, new HTMLTextPresenter(true));
}
};
}
/**
* Returns the information presenter control creator. The creator is a factory creating the
* presenter controls for the given source viewer. This implementation always returns a creator
* for <code>DefaultInformationControl</code> instances.
*
* @param sourceViewer the source viewer to be configured by this configuration
* @return an information control creator
* @since 2.1
*/
private IInformationControlCreator getInformationPresenterControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int style= SWT.V_SCROLL | SWT.H_SCROLL;
return new DefaultInformationControl(parent, shellStyle, style, new HTMLTextPresenter(false));
// return new HoverBrowserControl(parent);
}
};
}
/**
* Returns the outline presenter control creator. The creator is a factory creating outline
* presenter controls for the given source viewer. This implementation always returns a creator
* for <code>JavaOutlineInformationControl</code> instances.
*
* @param sourceViewer the source viewer to be configured by this configuration
* @return an information control creator
* @since 2.1
*/
private IInformationControlCreator getOutlinePresenterControlCreator(ISourceViewer sourceViewer, final String commandId) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int treeStyle= SWT.V_SCROLL | SWT.H_SCROLL;
return new JavaOutlineInformationControl(parent, shellStyle, treeStyle, commandId);
}
};
}
private IInformationControlCreator getHierarchyPresenterControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int treeStyle= SWT.V_SCROLL | SWT.H_SCROLL;
return new HierarchyInformationControl(parent, shellStyle, treeStyle);
}
};
}
/*
* @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer)
* @since 2.0
*/
public IInformationPresenter getInformationPresenter(ISourceViewer sourceViewer) {
InformationPresenter presenter= new InformationPresenter(getInformationPresenterControlCreator(sourceViewer));
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
IInformationProvider provider= new JavaInformationProvider(getEditor());
presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER);
presenter.setSizeConstraints(60, 10, true, true);
return presenter;
}
/**
* Returns the outline presenter which will determine and shown
* information requested for the current cursor position.
*
* @param sourceViewer the source viewer to be configured by this configuration
* @param doCodeResolve a boolean which specifies whether code resolve should be used to compute the Java element
* @return an information presenter
* @since 2.1
*/
public IInformationPresenter getOutlinePresenter(ISourceViewer sourceViewer, boolean doCodeResolve) {
InformationPresenter presenter;
if (doCodeResolve)
presenter= new InformationPresenter(getOutlinePresenterControlCreator(sourceViewer, IJavaEditorActionDefinitionIds.OPEN_STRUCTURE));
else
presenter= new InformationPresenter(getOutlinePresenterControlCreator(sourceViewer, IJavaEditorActionDefinitionIds.SHOW_OUTLINE));
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
presenter.setAnchor(AbstractInformationControlManager.ANCHOR_GLOBAL);
IInformationProvider provider= new JavaElementProvider(getEditor(), doCodeResolve);
presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_STRING);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER);
presenter.setSizeConstraints(20, 20, true, false);
presenter.setRestoreInformationControlBounds(getSettings("outline_presenter_bounds"), true, true); //$NON-NLS-1$
return presenter;
}
private IDialogSettings getSettings(String sectionName) {
IDialogSettings settings= JavaPlugin.getDefault().getDialogSettings().getSection(sectionName);
if (settings == null)
settings= JavaPlugin.getDefault().getDialogSettings().addNewSection(sectionName);
return settings;
}
public IInformationPresenter getHierarchyPresenter(ISourceViewer sourceViewer, boolean doCodeResolve) {
InformationPresenter presenter= new InformationPresenter(getHierarchyPresenterControlCreator(sourceViewer));
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
presenter.setAnchor(AbstractInformationControlManager.ANCHOR_GLOBAL);
IInformationProvider provider= new JavaElementProvider(getEditor(), doCodeResolve);
presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_STRING);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER);
presenter.setSizeConstraints(50, 20, true, false);
presenter.setRestoreInformationControlBounds(getSettings("hierarchy_presenter_bounds"), true, true); //$NON-NLS-1$
return presenter;
}
}
|
53,299 |
Bug 53299 Synchronizing 5 projects is locking too much
|
Build 20040219 While synchronizing 5 projects, I started editing one file in project no.1, while no.3 was being synchronized (1 was long done). I still got locked on validate edit, though the project 1 should have been released from the sync rsc lock. (I did check that no other competing job was getting in the way)
|
resolved fixed
|
d3604f3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-01T11:13:40Z | 2004-02-27T16:40:00Z |
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.IResourceRuleFactory;
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.IAnnotationAccessExtension;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelListener;
import org.eclipse.jface.text.source.IAnnotationModelListenerExtension;
import org.eclipse.jface.text.source.IAnnotationPresentation;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.editors.text.TextFileDocumentProvider;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.AnnotationPreferenceLookup;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.MarkerUtilities;
import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.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.text.spelling.SpellReconcileStrategy.SpellProblem;
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, IAnnotationPresentation {
private static final String SPELLING_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.spelling";
//XXX: To be fully correct these constants should be non-static
/**
* The layer in which task problem annotations are located.
*/
private static final int TASK_LAYER;
/**
* The layer in which info problem annotations are located.
*/
private static final int INFO_LAYER;
/**
* The layer in which warning problem annotations representing are located.
*/
private static final int WARNING_LAYER;
/**
* The layer in which error problem annotations representing are located.
*/
private static final int ERROR_LAYER;
static {
AnnotationPreferenceLookup lookup= EditorsUI.getAnnotationPreferenceLookup();
TASK_LAYER= computeLayer("org.eclipse.ui.workbench.texteditor.task", lookup); //$NON-NLS-1$
INFO_LAYER= computeLayer("org.eclipse.jdt.ui.info", lookup); //$NON-NLS-1$
WARNING_LAYER= computeLayer("org.eclipse.jdt.ui.warning", lookup); //$NON-NLS-1$
ERROR_LAYER= computeLayer("org.eclipse.jdt.ui.error", lookup); //$NON-NLS-1$
}
private static int computeLayer(String annotationType, AnnotationPreferenceLookup lookup) {
Annotation annotation= new Annotation(annotationType, false, null);
AnnotationPreference preference= lookup.getAnnotationPreference(annotation);
if (preference != null)
return preference.getPresentationLayer() + 1;
else
return IAnnotationAccessExtension.DEFAULT_LAYER + 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 int fLayer= IAnnotationAccessExtension.DEFAULT_LAYER;
public ProblemAnnotation(IProblem problem, ICompilationUnit cu) {
fProblem= problem;
fCompilationUnit= cu;
if (SpellProblem.Spelling == fProblem.getID()) {
setType(SPELLING_ANNOTATION_TYPE);
fLayer= WARNING_LAYER;
} else if (IProblem.Task == fProblem.getID()) {
setType(JavaMarkerAnnotation.TASK_ANNOTATION_TYPE);
fLayer= TASK_LAYER;
} else if (fProblem.isWarning()) {
setType(JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE);
fLayer= WARNING_LAYER;
} else if (fProblem.isError()) {
setType(JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE);
fLayer= ERROR_LAYER;
} else {
setType(JavaMarkerAnnotation.INFO_ANNOTATION_TYPE);
fLayer= INFO_LAYER;
}
}
/*
* @see org.eclipse.jface.text.source.IAnnotationPresentation#getLayer()
*/
public int getLayer() {
return fLayer;
}
private void initializeImages() {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=18936
if (!fQuickFixImagesInitialized) {
if (isProblem() && indicateQuixFixableProblems() && JavaCorrectionProcessor.hasCorrections(this)) { // no light bulb for tasks
if (!fgQuickFixImagesInitialized) {
fgQuickFixImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM);
fgQuickFixErrorImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_ERROR);
fgQuickFixImagesInitialized= true;
}
if (JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(getType()))
fImage= fgQuickFixErrorImage;
else
fImage= fgQuickFixImage;
}
fQuickFixImagesInitialized= true;
}
}
private boolean indicateQuixFixableProblems() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION);
}
/*
* @see Annotation#paint
*/
public void paint(GC gc, Canvas canvas, Rectangle r) {
initializeImages();
if (fImage != null)
drawImage(fImage, gc, canvas, r, SWT.CENTER, SWT.TOP);
}
/*
* @see IJavaAnnotation#getImage(Display)
*/
public Image getImage(Display display) {
initializeImages();
return fImage;
}
/*
* @see IJavaAnnotation#getMessage()
*/
public String getText() {
return fProblem.getMessage();
}
/*
* @see IJavaAnnotation#getArguments()
*/
public String[] getArguments() {
return isProblem() ? fProblem.getArguments() : null;
}
/*
* @see IJavaAnnotation#getId()
*/
public int getId() {
return fProblem.getID();
}
/*
* @see IJavaAnnotation#isProblem()
*/
public boolean isProblem() {
String type= getType();
return JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE.equals(type) ||
JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(type) ||
SPELLING_ANNOTATION_TYPE.equals(type);
}
/*
* @see IJavaAnnotation#hasOverlay()
*/
public boolean hasOverlay() {
return false;
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation#getOverlay()
*/
public IJavaAnnotation getOverlay() {
return null;
}
/*
* @see IJavaAnnotation#addOverlaid(IJavaAnnotation)
*/
public void addOverlaid(IJavaAnnotation annotation) {
if (fOverlaids == null)
fOverlaids= new ArrayList(1);
fOverlaids.add(annotation);
}
/*
* @see IJavaAnnotation#removeOverlaid(IJavaAnnotation)
*/
public void removeOverlaid(IJavaAnnotation annotation) {
if (fOverlaids != null) {
fOverlaids.remove(annotation);
if (fOverlaids.size() == 0)
fOverlaids= null;
}
}
/*
* @see IJavaAnnotation#getOverlaidIterator()
*/
public Iterator getOverlaidIterator() {
if (fOverlaids != null)
return fOverlaids.iterator();
return null;
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation#getCompilationUnit()
*/
public ICompilationUnit getCompilationUnit() {
return fCompilationUnit;
}
}
/**
* Internal structure for mapping positions to some value.
* The reason for this specific structure is that positions can
* change over time. Thus a lookup is based on value and not
* on hash value.
*/
protected static class ReverseMap {
static class Entry {
Position fPosition;
Object fValue;
}
private List fList= new ArrayList(2);
private int fAnchor= 0;
public ReverseMap() {
}
public Object get(Position position) {
Entry entry;
// behind anchor
int length= fList.size();
for (int i= fAnchor; i < length; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position)) {
fAnchor= i;
return entry.fValue;
}
}
// before anchor
for (int i= 0; i < fAnchor; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position)) {
fAnchor= i;
return entry.fValue;
}
}
return null;
}
private int getIndex(Position position) {
Entry entry;
int length= fList.size();
for (int i= 0; i < length; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position))
return i;
}
return -1;
}
public void put(Position position, Object value) {
int index= getIndex(position);
if (index == -1) {
Entry entry= new Entry();
entry.fPosition= position;
entry.fValue= value;
fList.add(entry);
} else {
Entry entry= (Entry) fList.get(index);
entry.fValue= value;
}
}
public void remove(Position position) {
int index= getIndex(position);
if (index > -1)
fList.remove(index);
}
public void clear() {
fList.clear();
}
}
/**
* Annotation model dealing with java marker annotations and temporary problems.
* Also acts as problem requestor for its compilation unit. Initialiy inactive. Must explicitly be
* activated.
*/
protected 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 boolean fIncludesProblemAnnotationChanges= false;
public CompilationUnitAnnotationModel(IResource resource) {
super(resource);
}
public void setCompilationUnit(ICompilationUnit unit) {
fCompilationUnit= unit;
}
protected MarkerAnnotation createMarkerAnnotation(IMarker marker) {
String markerType= MarkerUtilities.getMarkerType(marker);
if (markerType != null && markerType.startsWith(JavaMarkerAnnotation.JAVA_MARKER_TYPE_PREFIX))
return new JavaMarkerAnnotation(marker);
return super.createMarkerAnnotation(marker);
}
/*
* @see org.eclipse.jface.text.source.AnnotationModel#createAnnotationModelEvent()
*/
protected AnnotationModelEvent createAnnotationModelEvent() {
return new CompilationUnitAnnotationModelEvent(this, getResource());
}
protected Position createPositionFromProblem(IProblem problem) {
int start= problem.getSourceStart();
if (start < 0)
return null;
int length= problem.getSourceEnd() - problem.getSourceStart() + 1;
if (length < 0)
return null;
return new Position(start, length);
}
protected void update(IMarkerDelta[] markerDeltas) {
super.update(markerDeltas);
if (fIncludesProblemAnnotationChanges) {
try {
if (fCompilationUnit != null)
fCompilationUnit.reconcile(true, null);
} catch (JavaModelException ex) {
if (!ex.isDoesNotExist())
handleCoreException(ex, ex.getMessage());
}
}
}
/*
* @see IProblemRequestor#beginReporting()
*/
public void beginReporting() {
}
/*
* @see org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension#beginReportingSequence()
*/
public void beginReportingSequence() {
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() {
}
/*
* @see org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension#endReportingSequence()
*/
public void endReportingSequence() {
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);
overlayMarkers(position, annotation);
addAnnotation(annotation, position, false);
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);
}
} else {
}
}
private void overlayMarkers(Position position, ProblemAnnotation problemAnnotation) {
Object value= getAnnotations(position);
if (value instanceof List) {
List list= (List) value;
for (Iterator e = list.iterator(); e.hasNext();)
setOverlay(e.next(), problemAnnotation);
} else {
setOverlay(value, problemAnnotation);
}
}
/**
* Tells this annotation model to collect temporary problems from now on.
*/
private void startCollectingProblems() {
fCollectedProblems= new ArrayList();
fGeneratedAnnotations= new ArrayList();
}
/**
* Tells this annotation model to no longer collect temporary problems.
*/
private void stopCollectingProblems() {
if (fGeneratedAnnotations != null) {
removeAnnotations(fGeneratedAnnotations, true, true);
fGeneratedAnnotations.clear();
}
fCollectedProblems= null;
fGeneratedAnnotations= null;
}
/*
* @see org.eclipse.jface.text.source.AnnotationModel#fireModelChanged(org.eclipse.jface.text.source.AnnotationModelEvent)
*/
protected void fireModelChanged(AnnotationModelEvent event) {
if (event instanceof CompilationUnitAnnotationModelEvent) {
CompilationUnitAnnotationModelEvent e= (CompilationUnitAnnotationModelEvent) event;
fIncludesProblemAnnotationChanges= e.includesProblemMarkerAnnotationChanges();
}
super.fireModelChanged(event);
}
/*
* @see IProblemRequestor#isActive()
*/
public boolean isActive() {
return fIsActive && (fCollectedProblems != null);
}
/*
* @see IProblemRequestorExtension#setProgressMonitor(IProgressMonitor)
*/
public void setProgressMonitor(IProgressMonitor monitor) {
fProgressMonitor= monitor;
}
/*
* @see IProblemRequestorExtension#setIsActive(boolean)
*/
public void setIsActive(boolean isActive) {
if (fIsActive != isActive) {
fIsActive= isActive;
if (fIsActive)
startCollectingProblems();
else
stopCollectingProblems();
}
}
private Object getAnnotations(Position position) {
return fReverseMap.get(position);
}
/*
* @see AnnotationModel#addAnnotation(Annotation, Position, boolean)
*/
protected void addAnnotation(Annotation annotation, Position position, boolean fireModelChanged) throws BadLocationException {
super.addAnnotation(annotation, position, fireModelChanged);
Object cached= fReverseMap.get(position);
if (cached == null)
fReverseMap.put(position, annotation);
else if (cached instanceof List) {
List list= (List) cached;
list.add(annotation);
} else if (cached instanceof Annotation) {
List list= new ArrayList(2);
list.add(cached);
list.add(annotation);
fReverseMap.put(position, list);
}
}
/*
* @see AnnotationModel#removeAllAnnotations(boolean)
*/
protected void removeAllAnnotations(boolean fireModelChanged) {
super.removeAllAnnotations(fireModelChanged);
fReverseMap.clear();
}
/*
* @see AnnotationModel#removeAnnotation(Annotation, boolean)
*/
protected void removeAnnotation(Annotation annotation, boolean fireModelChanged) {
Position position= getPosition(annotation);
Object cached= fReverseMap.get(position);
if (cached instanceof List) {
List list= (List) cached;
list.remove(annotation);
if (list.size() == 1) {
fReverseMap.put(position, list.get(0));
list.clear();
}
} else if (cached instanceof Annotation) {
fReverseMap.remove(position);
}
super.removeAnnotation(annotation, fireModelChanged);
}
}
protected static class GlobalAnnotationModelListener implements IAnnotationModelListener, IAnnotationModelListenerExtension {
private ListenerList fListenerList;
public GlobalAnnotationModelListener() {
fListenerList= new ListenerList();
}
/**
* @see IAnnotationModelListener#modelChanged(IAnnotationModel)
*/
public void modelChanged(IAnnotationModel model) {
Object[] listeners= fListenerList.getListeners();
for (int i= 0; i < listeners.length; i++) {
((IAnnotationModelListener) listeners[i]).modelChanged(model);
}
}
/**
* @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent)
*/
public void modelChanged(AnnotationModelEvent event) {
Object[] listeners= fListenerList.getListeners();
for (int i= 0; i < listeners.length; i++) {
Object curr= listeners[i];
if (curr instanceof IAnnotationModelListenerExtension) {
((IAnnotationModelListenerExtension) curr).modelChanged(event);
}
}
}
public void addListener(IAnnotationModelListener listener) {
fListenerList.add(listener);
}
public void removeListener(IAnnotationModelListener listener) {
fListenerList.remove(listener);
}
}
/** Preference key for temporary problems */
private final static String HANDLE_TEMPORARY_PROBLEMS= PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS;
/** Indicates whether the save has been initialized by this provider */
private boolean fIsAboutToSave= false;
/** The save policy used by this provider */
private ISavePolicy fSavePolicy;
/** Internal property changed listener */
private IPropertyChangeListener fPropertyListener;
/** Annotation model listener added to all created CU annotation models */
private GlobalAnnotationModelListener fGlobalAnnotationModelListener;
/**
* Constructor
*/
public 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) {
IFile file= ((IFileEditorInput)info.fElement).getFile();
IResourceRuleFactory ruleFactory= ResourcesPlugin.getWorkspace().getRuleFactory();
if (file == null || !file.exists())
return ruleFactory.createRule(file);
else
return ruleFactory.modifyRule(file);
} 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();
}
}
|
53,311 |
Bug 53311 [KeyBindings] F5 doesn't work
|
Version: 3.0.0 Build id: 200312182000
|
verified fixed
|
f070c30
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-01T14:19:02Z | 2004-02-27T19:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerActionGroup.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 org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.OpenStrategy;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.IWorkingSetManager;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.MoveResourceAction;
import org.eclipse.ui.actions.OpenInNewWindowAction;
import org.eclipse.ui.actions.RenameResourceAction;
import org.eclipse.ui.views.framelist.BackAction;
import org.eclipse.ui.views.framelist.ForwardAction;
import org.eclipse.ui.views.framelist.FrameAction;
import org.eclipse.ui.views.framelist.FrameList;
import org.eclipse.ui.views.framelist.GoIntoAction;
import org.eclipse.ui.views.framelist.UpAction;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IOpenable;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.BuildActionGroup;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.CustomFiltersActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.ImportActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.JdtActionConstants;
import org.eclipse.jdt.ui.actions.NavigateActionGroup;
import org.eclipse.jdt.ui.actions.ProjectActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup;
import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup;
class PackageExplorerActionGroup extends CompositeActionGroup implements ISelectionChangedListener {
private PackageExplorerPart fPart;
private GoIntoAction fZoomInAction;
private BackAction fBackAction;
private ForwardAction fForwardAction;
private UpAction fUpAction;
private GotoTypeAction fGotoTypeAction;
private GotoPackageAction fGotoPackageAction;
private GotoResourceAction fGotoResourceAction;
private CollapseAllAction fCollapseAllAction;
private RenameResourceAction fRenameResourceAction;
private MoveResourceAction fMoveResourceAction;
private ToggleLinkingAction fToggleLinkingAction;
private NavigateActionGroup fNavigateActionGroup;
private BuildActionGroup fBuildActionGroup;
private CCPActionGroup fCCPActionGroup;
private WorkingSetFilterActionGroup fWorkingSetFilterActionGroup;
private CustomFiltersActionGroup fCustomFiltersActionGroup;
private int fLastElement;
private static final int INIT= 0;
private static final int RESOURCE= 1;
private static final int REST= 2;
public PackageExplorerActionGroup(PackageExplorerPart part) {
super();
fPart= part;
TreeViewer viewer= part.getViewer();
IPropertyChangeListener workingSetListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
doWorkingSetChanged(event);
}
};
IWorkbenchPartSite site = fPart.getSite();
Shell shell= site.getShell();
ISelectionProvider provider= site.getSelectionProvider();
IStructuredSelection selection= (IStructuredSelection) provider.getSelection();
setGroups(new ActionGroup[] {
new NewWizardsActionGroup(site),
fNavigateActionGroup= new NavigateActionGroup(fPart),
fCCPActionGroup= new CCPActionGroup(fPart),
new GenerateActionGroup(fPart),
new RefactorActionGroup(fPart),
new ImportActionGroup(fPart),
fBuildActionGroup= new BuildActionGroup(fPart),
new JavaSearchActionGroup(fPart),
new ProjectActionGroup(fPart),
fWorkingSetFilterActionGroup= new WorkingSetFilterActionGroup(JavaUI.ID_PACKAGES, shell, workingSetListener),
fCustomFiltersActionGroup= new CustomFiltersActionGroup(fPart, viewer),
new LayoutActionGroup(part)});
viewer.addFilter(fWorkingSetFilterActionGroup.getWorkingSetFilter());
PackagesFrameSource frameSource= new PackagesFrameSource(fPart);
FrameList frameList= new FrameList(frameSource);
frameSource.connectTo(frameList);
fZoomInAction= new GoIntoAction(frameList);
fBackAction= new BackAction(frameList);
fForwardAction= new ForwardAction(frameList);
fUpAction= new UpAction(frameList);
fRenameResourceAction= new RenameResourceAction(shell);
fMoveResourceAction= new MoveResourceAction(shell);
fGotoTypeAction= new GotoTypeAction(fPart);
fGotoPackageAction= new GotoPackageAction(fPart);
fGotoResourceAction= new GotoResourceAction(fPart);
fCollapseAllAction= new CollapseAllAction(fPart);
fToggleLinkingAction = new ToggleLinkingAction(fPart);
provider.addSelectionChangedListener(this);
update(selection);
fLastElement= INIT;
}
public void dispose() {
ISelectionProvider provider= fPart.getSite().getSelectionProvider();
provider.removeSelectionChangedListener(this);
super.dispose();
}
//---- Selection changed listener ---------------------------------------------------------
public void selectionChanged(SelectionChangedEvent event) {
fRenameResourceAction.selectionChanged(event);
fMoveResourceAction.selectionChanged(event);
IStructuredSelection selection= (IStructuredSelection)event.getSelection();
update(selection);
}
private void update(IStructuredSelection selection) {
int size= selection.size();
Object element= selection.getFirstElement();
IActionBars actionBars= fPart.getViewSite().getActionBars();
if (size == 1 && element instanceof IResource) {
if (fLastElement != RESOURCE) { // fLastAction in a work around for http://bugs.eclipse.org/bugs/show_bug.cgi?id=30508
actionBars.setGlobalActionHandler(ActionFactory.RENAME.getId(), fRenameResourceAction);
actionBars.setGlobalActionHandler(ActionFactory.MOVE.getId(), fMoveResourceAction);
actionBars.updateActionBars();
fLastElement= RESOURCE;
}
} else {
if (fLastElement != REST) {
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.RENAME, null);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.MOVE, null);
actionBars.updateActionBars();
fLastElement= REST;
}
}
}
//---- Persistent state -----------------------------------------------------------------------
/* package */ void restoreFilterAndSorterState(IMemento memento) {
fWorkingSetFilterActionGroup.restoreState(memento);
fCustomFiltersActionGroup.restoreState(memento);
}
/* package */ void saveFilterAndSorterState(IMemento memento) {
fWorkingSetFilterActionGroup.saveState(memento);
fCustomFiltersActionGroup.saveState(memento);
}
//---- Action Bars ----------------------------------------------------------------------------
public void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
setGlobalActionHandlers(actionBars);
fillToolBar(actionBars.getToolBarManager());
fillViewMenu(actionBars.getMenuManager());
}
/* package */ void updateActionBars(IActionBars actionBars) {
actionBars.getToolBarManager().removeAll();
actionBars.getMenuManager().removeAll();
fillActionBars(actionBars);
actionBars.updateActionBars();
fZoomInAction.setEnabled(true);
}
private void setGlobalActionHandlers(IActionBars actionBars) {
// Navigate Go Into and Go To actions.
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_INTO, fZoomInAction);
actionBars.setGlobalActionHandler(ActionFactory.BACK.getId(), fBackAction);
actionBars.setGlobalActionHandler(ActionFactory.FORWARD.getId(), fForwardAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.UP, fUpAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_TO_RESOURCE, fGotoResourceAction);
actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_TYPE, fGotoTypeAction);
actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_PACKAGE, fGotoPackageAction);
}
/* package */ void fillToolBar(IToolBarManager toolBar) {
toolBar.add(fBackAction);
toolBar.add(fForwardAction);
toolBar.add(fUpAction);
toolBar.add(new Separator());
toolBar.add(fCollapseAllAction);
toolBar.add(fToggleLinkingAction);
}
/* package */ void fillViewMenu(IMenuManager menu) {
menu.add(fToggleLinkingAction);
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$
}
/* package */ void handleSelectionChanged(SelectionChangedEvent event) {
}
//---- Context menu -------------------------------------------------------------------------
public void fillContextMenu(IMenuManager menu) {
IStructuredSelection selection= (IStructuredSelection)getContext().getSelection();
int size= selection.size();
Object element= selection.getFirstElement();
addGotoMenu(menu, element, size);
addOpenNewWindowAction(menu, element);
super.fillContextMenu(menu);
}
private void addGotoMenu(IMenuManager menu, Object element, int size) {
boolean enabled= size == 1 && fPart.getViewer().isExpandable(element) && (isGoIntoTarget(element) || element instanceof IContainer);
fZoomInAction.setEnabled(enabled);
if (enabled)
menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction);
}
private boolean isGoIntoTarget(Object element) {
if (element == null)
return false;
if (element instanceof IJavaElement) {
int type= ((IJavaElement)element).getElementType();
return type == IJavaElement.JAVA_PROJECT ||
type == IJavaElement.PACKAGE_FRAGMENT_ROOT ||
type == IJavaElement.PACKAGE_FRAGMENT;
}
return false;
}
private void addOpenNewWindowAction(IMenuManager menu, Object element) {
if (element instanceof IJavaElement) {
element= ((IJavaElement)element).getResource();
}
if (!(element instanceof IContainer))
return;
menu.appendToGroup(
IContextMenuConstants.GROUP_OPEN,
new OpenInNewWindowAction(fPart.getSite().getWorkbenchWindow(), (IContainer)element));
}
//---- Key board and mouse handling ------------------------------------------------------------
/* package*/ void handleDoubleClick(DoubleClickEvent event) {
TreeViewer viewer= fPart.getViewer();
Object element= ((IStructuredSelection)event.getSelection()).getFirstElement();
if (viewer.isExpandable(element)) {
if (doubleClickGoesInto()) {
// don't zoom into compilation units and class files
if (element instanceof ICompilationUnit || element instanceof IClassFile)
return;
if (element instanceof IOpenable || element instanceof IContainer) {
fZoomInAction.run();
}
} else {
IAction openAction= fNavigateActionGroup.getOpenAction();
if (openAction != null && openAction.isEnabled() && OpenStrategy.getOpenMethod() == OpenStrategy.DOUBLE_CLICK)
return;
viewer.setExpandedState(element, !viewer.getExpandedState(element));
}
}
}
/* package */ void handleOpen(OpenEvent event) {
IAction openAction= fNavigateActionGroup.getOpenAction();
if (openAction != null && openAction.isEnabled()) {
openAction.run();
return;
}
}
/* package */ void handleKeyEvent(KeyEvent event) {
if (event.stateMask != 0)
return;
if (event.keyCode == SWT.F5) {
IAction refreshAction= fBuildActionGroup.getRefreshAction();
if (refreshAction != null && refreshAction.isEnabled())
refreshAction.run();
} else if (event.character == SWT.DEL) {
IAction delete= fCCPActionGroup.getDeleteAction();
if (delete != null && delete.isEnabled())
delete.run();
}
else if (event.keyCode == SWT.BS) {
if (fUpAction != null && fUpAction.isEnabled())
fUpAction.run();
}
}
private void doWorkingSetChanged(PropertyChangeEvent event) {
IWorkingSet workingSet= (IWorkingSet) event.getNewValue();
String workingSetName= null;
if (workingSet != null)
workingSetName= workingSet.getName();
fPart.setWorkingSetName(workingSetName);
fPart.updateTitle();
String property= event.getProperty();
if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) {
TreeViewer viewer= fPart.getViewer();
viewer.getControl().setRedraw(false);
viewer.refresh();
viewer.getControl().setRedraw(true);
}
}
private boolean doubleClickGoesInto() {
return PreferenceConstants.DOUBLE_CLICK_GOES_INTO.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.DOUBLE_CLICK));
}
public FrameAction getUpAction() {
return fUpAction;
}
public FrameAction getBackAction() {
return fBackAction;
}
public FrameAction getForwardAction() {
return fForwardAction;
}
public WorkingSetFilterActionGroup getWorkingSetActionGroup() {
return fWorkingSetFilterActionGroup;
}
public CustomFiltersActionGroup getCustomFilterActionGroup() {
return fCustomFiltersActionGroup;
}
}
|
53,383 |
Bug 53383 incorrect progress message in new search view
|
1) perform a file search for "deprecated" in *.java files in the workspace. -> while the search is running the following message is shown: running)(deprecated - 123 match in Workspace The parenthesis aren't match and no plural is used.
|
resolved fixed
|
6afa783
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-01T16:19:48Z | 2004-03-01T14:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchQuery.java
| |
53,383 |
Bug 53383 incorrect progress message in new search view
|
1) perform a file search for "deprecated" in *.java files in the workspace. -> while the search is running the following message is shown: running)(deprecated - 123 match in Workspace The parenthesis aren't match and no plural is used.
|
resolved fixed
|
6afa783
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-01T16:19:48Z | 2004-03-01T14:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchResult.java
| |
53,383 |
Bug 53383 incorrect progress message in new search view
|
1) perform a file search for "deprecated" in *.java files in the workspace. -> while the search is running the following message is shown: running)(deprecated - 123 match in Workspace The parenthesis aren't match and no plural is used.
|
resolved fixed
|
6afa783
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-01T16:19:48Z | 2004-03-01T14:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchResultPage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.search;
import java.util.HashMap;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.search.ui.IContextMenuConstants;
import org.eclipse.search.ui.ISearchResultViewPart;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.search.ui.text.AbstractTextSearchViewPage;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
public class JavaSearchResultPage extends AbstractTextSearchViewPage {
private NewSearchViewActionGroup fActionGroup;
private JavaSearchContentProvider fContentProvider;
private int fCurrentSortOrder;
private SortAction fSortByNameAction;
private SortAction fSortByParentName;
private SortAction fSortByPathAction;
private GroupAction fGroupTypeAction;
private GroupAction fGroupFileAction;
private GroupAction fGroupPackageAction;
private GroupAction fGroupProjectAction;
private int fCurrentGrouping;
public JavaSearchResultPage() {
fSortByNameAction= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByName"), this, JavaSearchResultLabelProvider.SHOW_ELEMENT_CONTAINER); //$NON-NLS-1$
fSortByPathAction= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByPath"), this, JavaSearchResultLabelProvider.SHOW_PATH); //$NON-NLS-1$
fSortByParentName= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByParentName"), this, JavaSearchResultLabelProvider.SHOW_CONTAINER_ELEMENT); //$NON-NLS-1$
fCurrentSortOrder= JavaSearchResultLabelProvider.SHOW_ELEMENT_CONTAINER;
fGroupProjectAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_project"), this, LevelTreeContentProvider.LEVEL_PROJECT); //$NON-NLS-1$
fGroupPackageAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_package"), this, LevelTreeContentProvider.LEVEL_PACKAGE); //$NON-NLS-1$
fGroupFileAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_file"), this, LevelTreeContentProvider.LEVEL_FILE); //$NON-NLS-1$
fGroupTypeAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_type"), this, LevelTreeContentProvider.LEVEL_TYPE); //$NON-NLS-1$
fCurrentGrouping= LevelTreeContentProvider.LEVEL_PACKAGE;
}
public void setViewPart(ISearchResultViewPart part) {
// TODO Auto-generated method stub
super.setViewPart(part);
fActionGroup= new NewSearchViewActionGroup(part);
}
public void showMatch(Object element, int offset, int length) throws PartInitException {
IEditorPart editor= null;
if (element instanceof IJavaElement) {
IJavaElement javaElement= (IJavaElement) element;
try {
editor= EditorUtility.openInEditor(javaElement, false);
} catch (PartInitException e1) {
return;
} catch (JavaModelException e1) {
return;
}
} else if (element instanceof IFile) {
editor= IDE.openEditor(JavaPlugin.getActivePage(), (IFile) element, false);
}
if (!(editor instanceof ITextEditor)) {
if (element instanceof IFile) {
IFile file= (IFile) element;
showWithMarker(editor, file, offset, length);
}
} else {
ITextEditor textEditor= (ITextEditor) editor;
textEditor.selectAndReveal(offset, length);
}
}
private void showWithMarker(IEditorPart editor, IFile file, int offset, int length) throws PartInitException {
try {
IMarker marker= file.createMarker(SearchUI.SEARCH_MARKER);
HashMap attributes= new HashMap(4);
attributes.put(IMarker.CHAR_START, new Integer(offset));
attributes.put(IMarker.CHAR_END, new Integer(offset + length));
marker.setAttributes(attributes);
IDE.gotoMarker(editor, marker);
marker.delete();
} catch (CoreException e) {
throw new PartInitException(SearchMessages.getString("JavaSearchResultPage.error.marker"), e); //$NON-NLS-1$
}
}
protected void fillContextMenu(IMenuManager mgr) {
super.fillContextMenu(mgr);
addSortActions(mgr);
addGroupActions(mgr);
fActionGroup.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
fActionGroup.fillContextMenu(mgr);
}
private void addSortActions(IMenuManager mgr) {
if (!isFlatLayout())
return;
MenuManager sortMenu= new MenuManager(SearchMessages.getString("JavaSearchResultPage.sortBylabel")); //$NON-NLS-1$
sortMenu.add(fSortByNameAction);
sortMenu.add(fSortByPathAction);
sortMenu.add(fSortByParentName);
fSortByNameAction.setChecked(fCurrentSortOrder == fSortByNameAction.getSortOrder());
fSortByPathAction.setChecked(fCurrentSortOrder == fSortByPathAction.getSortOrder());
fSortByParentName.setChecked(fCurrentSortOrder == fSortByParentName.getSortOrder());
mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, sortMenu);
}
private void addGroupActions(IMenuManager mgr) {
if (isFlatLayout())
return;
MenuManager groupMenu= new MenuManager(SearchMessages.getString("JavaSearchResultPage.groupyby_label")); //$NON-NLS-1$
groupMenu.add(fGroupProjectAction);
groupMenu.add(fGroupPackageAction);
groupMenu.add(fGroupFileAction);
groupMenu.add(fGroupTypeAction);
fGroupProjectAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_PROJECT);
fGroupPackageAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_PACKAGE);
fGroupFileAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_FILE);
fGroupTypeAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_TYPE);
mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, groupMenu);
}
public void dispose() {
fActionGroup.dispose();
super.dispose();
}
protected void elementsChanged(Object[] objects) {
if (fContentProvider != null)
fContentProvider.elementsChanged(objects);
}
protected void clear() {
if (fContentProvider != null)
fContentProvider.clear();
}
protected void configureViewer(StructuredViewer viewer) {
if (viewer instanceof TreeViewer) {
viewer.setSorter(new ViewerSorter());
viewer.setLabelProvider(new PostfixLabelProvider(this));
fContentProvider= new LevelTreeContentProvider((TreeViewer) viewer, fCurrentGrouping);
viewer.setContentProvider(fContentProvider);
} else {
viewer.setLabelProvider(new DelegatingLabelProvider(this, new JavaSearchResultLabelProvider()));
fContentProvider=new JavaSearchTableContentProvider((TableViewer) viewer);
viewer.setContentProvider(fContentProvider);
setSortOrder(fCurrentSortOrder);
}
}
void setSortOrder(int order) {
fCurrentSortOrder= order;
StructuredViewer viewer= getViewer();
DelegatingLabelProvider lpWrapper= (DelegatingLabelProvider) viewer.getLabelProvider();
((JavaSearchResultLabelProvider)lpWrapper.getLabelProvider()).setOrder(order);
if (order == JavaSearchResultLabelProvider.SHOW_ELEMENT_CONTAINER) {
viewer.setSorter(new NameSorter());
} else if (order == JavaSearchResultLabelProvider.SHOW_PATH) {
viewer.setSorter(new PathSorter());
} else
viewer.setSorter(new ParentSorter());
}
public void init(IPageSite site) {
super.init(site);
fActionGroup.fillActionBars(site.getActionBars());
}
/**
* Precondition here: the viewer must be shwing a tree with a LevelContentProvider.
* @param order
*/
void setGrouping(int grouping) {
fCurrentGrouping= grouping;
StructuredViewer viewer= getViewer();
LevelTreeContentProvider cp= (LevelTreeContentProvider) viewer.getContentProvider();
cp.setLevel(grouping);
}
protected StructuredViewer getViewer() {
// override so that it's visible in the package.
return super.getViewer();
}
}
|
53,201 |
Bug 53201 NPE when re-running newly generated javadoc.xml
| null |
resolved fixed
|
4acbc5c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-02T10:53:37Z | 2004-02-26T18:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocOptionsManager.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.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.eclipse.jdt.launching.ExecutionArguments;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIStatus;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.preferences.JavadocPreferencePage;
public class JavadocOptionsManager {
private IFile fXmlfile;
private StatusInfo fWizardStatus;
private IJavaElement[] fSelectedElements;
private IJavaElement[] fInitialElements;
private String fAccess;
private String fDocletpath;
private String fDocletname;
private boolean fFromStandard;
private String fStylesheet;
private String fAdditionalParams;
private String fVMParams;
private String fOverview;
private String fTitle;
private String[] fHRefs;
private IPath[] fSourcepath;
private IPath[] fClasspath;
private boolean fNotree;
private boolean fNoindex;
private boolean fSplitindex;
private boolean fNonavbar;
private boolean fNodeprecated;
private boolean fNoDeprecatedlist;
private boolean fAuthor;
private boolean fVersion;
private boolean fUse;
private boolean fJDK14Mode;
private boolean fOpenInBrowser;
private RecentSettingsStore fRecentSettings;
//add-on for multi-project version
private String fDestination;
private String fAntpath;
public final String PRIVATE= "private"; //$NON-NLS-1$
public final String PROTECTED= "protected"; //$NON-NLS-1$
public final String PACKAGE= "package"; //$NON-NLS-1$
public final String PUBLIC= "public"; //$NON-NLS-1$
public final String USE= "use"; //$NON-NLS-1$
public final String NOTREE= "notree"; //$NON-NLS-1$
public final String NOINDEX= "noindex"; //$NON-NLS-1$
public final String NONAVBAR= "nonavbar"; //$NON-NLS-1$
public final String NODEPRECATED= "nodeprecated"; //$NON-NLS-1$
public final String NODEPRECATEDLIST= "nodeprecatedlist"; //$NON-NLS-1$
public final String VERSION= "version"; //$NON-NLS-1$
public final String AUTHOR= "author"; //$NON-NLS-1$
public final String SPLITINDEX= "splitindex"; //$NON-NLS-1$
public final String STYLESHEETFILE= "stylesheetfile"; //$NON-NLS-1$
public final String OVERVIEW= "overview"; //$NON-NLS-1$
public final String DOCLETNAME= "docletname"; //$NON-NLS-1$
public final String DOCLETPATH= "docletpath"; //$NON-NLS-1$
public final String SOURCEPATH= "sourcepath"; //$NON-NLS-1$
public final String CLASSPATH= "classpath"; //$NON-NLS-1$
public final String DESTINATION= "destdir"; //$NON-NLS-1$
public final String OPENINBROWSER= "openinbrowser"; //$NON-NLS-1$
public final String VISIBILITY= "access"; //$NON-NLS-1$
public final String PACKAGENAMES= "packagenames"; //$NON-NLS-1$
public final String SOURCEFILES= "sourcefiles"; //$NON-NLS-1$
public final String EXTRAOPTIONS= "additionalparam"; //$NON-NLS-1$
public final String VMOPTIONS= "vmparam"; //$NON-NLS-1$
//public final String JAVADOCCOMMAND= "javadoccommand"; //$NON-NLS-1$
public final String TITLE= "doctitle"; //$NON-NLS-1$
public final String HREF= "href"; //$NON-NLS-1$
public final String NAME= "name"; //$NON-NLS-1$
public final String PATH= "path"; //$NON-NLS-1$
public final String FROMSTANDARD= "fromStandard"; //$NON-NLS-1$
public final String ANTPATH= "antpath"; //$NON-NLS-1$
public final String SOURCE= "source"; //$NON-NLS-1$
private final String SECTION_JAVADOC= "javadoc"; //$NON-NLS-1$
public JavadocOptionsManager(IFile xmlJavadocFile, IDialogSettings dialogSettings, List currSelection) {
fXmlfile= xmlJavadocFile;
fWizardStatus= new StatusInfo();
IDialogSettings javadocSection= dialogSettings.getSection(SECTION_JAVADOC); //$NON-NLS-1$
fRecentSettings= new RecentSettingsStore(javadocSection);
if (xmlJavadocFile != null) {
try {
JavadocReader reader= new JavadocReader(xmlJavadocFile.getContents());
Element element= reader.readXML();
if (element != null) {
loadFromXML(element);
return;
}
fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectCE.warning")); //$NON-NLS-1$
} catch (CoreException e) {
JavaPlugin.log(e);
fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectCE.warning")); //$NON-NLS-1$
} catch (IOException e) {
JavaPlugin.log(e);
fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectIOE.warning")); //$NON-NLS-1$
} catch (SAXException e) {
fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectSAXE.warning")); //$NON-NLS-1$
}
}
if (javadocSection != null) {
loadFromDialogStore(javadocSection, currSelection);
} else {
loadDefaults(currSelection);
}
}
/*
* Returns the the Java project that is parent top all selected elements or null if
* the elements are from several projects.
*/
private IJavaProject getSingleProjectFromInitialSelection() {
IJavaProject res= null;
for (int i= 0; i < fInitialElements.length; i++) {
IJavaProject curr= fInitialElements[i].getJavaProject();
if (res == null) {
res= curr;
} else if (!res.equals(curr)) {
return null;
}
}
return res;
}
private void loadFromDialogStore(IDialogSettings settings, List sel) {
fInitialElements= getInitialElementsFromSelection(sel);
IJavaProject project= getSingleProjectFromInitialSelection();
fAccess= settings.get(VISIBILITY);
if (fAccess == null)
fAccess= PROTECTED;
//this is defaulted to false.
fFromStandard= settings.getBoolean(FROMSTANDARD);
//doclet is loaded even if the standard doclet is being used
fDocletpath= settings.get(DOCLETPATH);
fDocletname= settings.get(DOCLETNAME);
if (fDocletpath == null || fDocletname == null) {
fFromStandard= true;
fDocletpath= ""; //$NON-NLS-1$
fDocletname= ""; //$NON-NLS-1$
}
if (project != null) {
fAntpath= getRecentSettings().getAntpath(project);
} else {
fAntpath= settings.get(ANTPATH);
if (fAntpath == null) {
fAntpath= ""; //$NON-NLS-1$
}
}
if (project != null) {
fDestination= getRecentSettings().getDestination(project);
} else {
fDestination= settings.get(DESTINATION);
if (fDestination == null) {
fDestination= ""; //$NON-NLS-1$
}
}
fTitle= settings.get(TITLE);
if (fTitle == null)
fTitle= ""; //$NON-NLS-1$
fStylesheet= settings.get(STYLESHEETFILE);
if (fStylesheet == null)
fStylesheet= ""; //$NON-NLS-1$
fVMParams= settings.get(VMOPTIONS);
if (fVMParams == null)
fVMParams= ""; //$NON-NLS-1$
fAdditionalParams= settings.get(EXTRAOPTIONS);
if (fAdditionalParams == null)
fAdditionalParams= ""; //$NON-NLS-1$
fOverview= settings.get(OVERVIEW);
if (fOverview == null)
fOverview= ""; //$NON-NLS-1$
fUse= loadBoolean(settings.get(USE));
fAuthor= loadBoolean(settings.get(AUTHOR));
fVersion= loadBoolean(settings.get(VERSION));
fNodeprecated= loadBoolean(settings.get(NODEPRECATED));
fNoDeprecatedlist= loadBoolean(settings.get(NODEPRECATEDLIST));
fNonavbar= loadBoolean(settings.get(NONAVBAR));
fNoindex= loadBoolean(settings.get(NOINDEX));
fNotree= loadBoolean(settings.get(NOTREE));
fSplitindex= loadBoolean(settings.get(SPLITINDEX));
fOpenInBrowser= loadBoolean(settings.get(OPENINBROWSER));
fJDK14Mode= loadBoolean(settings.get(SOURCE));
if (project != null) {
fHRefs= getRecentSettings().getHRefs(project);
} else {
fHRefs= new String[0];
}
}
//loads defaults for wizard (nothing is stored)
private void loadDefaults(List sel) {
fInitialElements= getInitialElementsFromSelection(sel);
IJavaProject project= getSingleProjectFromInitialSelection();
if (project != null) {
fAntpath= getRecentSettings().getAntpath(project);
fDestination= getRecentSettings().getDestination(project);
fHRefs= getRecentSettings().getHRefs(project);
} else {
fAntpath= ""; //$NON-NLS-1$
fDestination= ""; //$NON-NLS-1$
fHRefs= new String[0];
}
fAccess= PUBLIC;
fDocletname= ""; //$NON-NLS-1$
fDocletpath= ""; //$NON-NLS-1$
fTitle= ""; //$NON-NLS-1$
fStylesheet= ""; //$NON-NLS-1$
fVMParams= ""; //$NON-NLS-1$
fAdditionalParams= ""; //$NON-NLS-1$
fOverview= ""; //$NON-NLS-1$
fUse= true;
fAuthor= true;
fVersion= true;
fNodeprecated= false;
fNoDeprecatedlist= false;
fNonavbar= false;
fNoindex= false;
fNotree= false;
fSplitindex= true;
fOpenInBrowser= false;
fJDK14Mode= false;
//by default it is empty all project map to the empty string
fFromStandard= true;
}
private void loadFromXML(Element element) {
fAccess= element.getAttribute(VISIBILITY);
if (fAccess.length() == 0)
fAccess= PROTECTED;
//Since the selected packages are stored we must locate the project
String destination= element.getAttribute(DESTINATION);
fDestination= makeAbsolutePathFromRelative(destination).toOSString();
fFromStandard= true;
fDocletname= ""; //$NON-NLS-1$
fDocletpath= ""; //$NON-NLS-1$
if (destination.length() == 0) { //$NON-NLS-1$
NodeList list= element.getChildNodes();
for (int i= 0; i < list.getLength(); i++) {
Node child= list.item(i);
if (child.getNodeName().equals("doclet")) { //$NON-NLS-1$
fDocletpath= ((Element) child).getAttribute(PATH);
fDocletname= ((Element) child).getAttribute(NAME);
if (fDocletpath.length() != 0 || fDocletname.length() != 0) {
fFromStandard= false;
} else {
fDocletname= ""; //$NON-NLS-1$
fDocletpath= ""; //$NON-NLS-1$
}
break;
}
}
}
fInitialElements= getSelectedElementsFromAnt(element);
//find all the links stored in the ant script
NodeList children= element.getChildNodes();
fHRefs= new String[children.getLength()];
for (int i= 0; i < fHRefs.length; i++) {
Node child= children.item(i);
if (child.getNodeName().equals("link")) { //$NON-NLS-1$
fHRefs[i]= ((Element) child).getAttribute(HREF);
}
}
//get tree elements
IPath p= fXmlfile.getLocation();
if (p != null)
fAntpath= p.toOSString();
else
fAntpath= ""; //$NON-NLS-1$
fStylesheet= element.getAttribute(STYLESHEETFILE);
fTitle= element.getAttribute(TITLE);
fAdditionalParams= element.getAttribute(EXTRAOPTIONS);
fOverview= element.getAttribute(OVERVIEW);
fUse= loadBoolean(element.getAttribute(USE));
fAuthor= loadBoolean(element.getAttribute(AUTHOR));
fVersion= loadBoolean(element.getAttribute(VERSION));
fNodeprecated= loadBoolean(element.getAttribute(NODEPRECATED));
fNoDeprecatedlist= loadBoolean(element.getAttribute(NODEPRECATEDLIST));
fNonavbar= loadBoolean(element.getAttribute(NONAVBAR));
fNoindex= loadBoolean(element.getAttribute(NOINDEX));
fNotree= loadBoolean(element.getAttribute(NOTREE));
fSplitindex= loadBoolean(element.getAttribute(SPLITINDEX));
}
/*
* Method creates an absolute path to the project. If the path is already
* absolute it returns the path. If it encounters any difficulties in
* creating the absolute path, the method returns null.
*
* @param pathStr
* @return IPath
*/
private IPath makeAbsolutePathFromRelative(String pathStr) {
IPath path= new Path(pathStr);
if (!path.isAbsolute()) {
if (fXmlfile == null) {
return null;
}
IPath basePath= fXmlfile.getParent().getLocation(); // relative to the ant file location
if (basePath == null) {
return null;
}
return basePath.append(pathStr);
}
return path;
}
private IContainer[] getSourceContainers(Element element) {
String sourcePaths= element.getAttribute(SOURCEPATH);
StringTokenizer tokenizer= new StringTokenizer(sourcePaths, ","); //$NON-NLS-1$
ArrayList res= new ArrayList();
IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
while (tokenizer.hasMoreTokens()) {
IPath path= makeAbsolutePathFromRelative(tokenizer.nextToken().trim());
if (path != null) {
IContainer[] containers= root.findContainersForLocation(path);
for (int i= 0; i < containers.length; i++) {
res.add(containers[i]);
}
}
}
return (IContainer[]) res.toArray(new IContainer[res.size()]);
}
private IJavaElement[] getSelectedElementsFromAnt(Element element) {
List res= new ArrayList();
// get all the packages listed in the ANT file
String packagenames= element.getAttribute(PACKAGENAMES);
if (packagenames != null) {
IContainer[] containers= getSourceContainers(element);
StringTokenizer tokenizer= new StringTokenizer(packagenames, ","); //$NON-NLS-1$
while (tokenizer.hasMoreTokens()) {
IPath relPackagePath= new Path(tokenizer.nextToken().trim().replace('.', '/'));
for (int i= 0; i < containers.length; i++) {
IContainer curr= containers[i];
IResource resource= curr.findMember(relPackagePath);
if (resource != null) {
IJavaElement javaElem= JavaCore.create(resource);
if (javaElem instanceof IPackageFragment) {
res.add(javaElem);
}
}
}
}
}
//get all CompilationUnites listed in the ANT file
String sourcefiles= element.getAttribute(SOURCEFILES);
if (sourcefiles != null) {
IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
StringTokenizer tokenizer= new StringTokenizer(sourcefiles, ","); //$NON-NLS-1$
while (tokenizer.hasMoreTokens()) {
String name= tokenizer.nextToken().trim();
if (name.endsWith(".java")) { //$NON-NLS-1$
IPath path= makeAbsolutePathFromRelative(name);
//if unable to create an absolute path the the resource skip it
if (path != null) {
IFile[] files= root.findFilesForLocation(path);
for (int i= 0; i < files.length; i++) {
IJavaElement el= JavaCore.createCompilationUnitFrom(files[i]);
if (el != null) {
res.add(el);
}
}
}
}
}
}
return (IJavaElement[]) res.toArray(new IJavaElement[res.size()]);
}
//it is possible that the package list is empty
public StatusInfo getWizardStatus() {
return fWizardStatus;
}
public IJavaElement[] getInitialElements() {
return fInitialElements;
}
public IJavaElement[] getSourceElements() {
return fSelectedElements;
}
public String getAccess() {
return fAccess;
}
public String getAntpath() {
return fAntpath;
}
public boolean isFromStandard() {
return fFromStandard;
}
public String getDestination() {
return fDestination;
}
public String getDocletPath() {
return fDocletpath;
}
public String getDocletName() {
return fDocletname;
}
public String getStyleSheet() {
return fStylesheet;
}
public String getOverview() {
return fOverview;
}
public String getAdditionalParams() {
return fAdditionalParams;
}
public String getVMParams() {
return fVMParams;
}
public IPath[] getClasspath() {
return fClasspath;
}
public IPath[] getSourcepath() {
return fSourcepath;
}
public String getTitle() {
return fTitle;
}
public boolean doOpenInBrowser() {
return fOpenInBrowser;
}
public String[] getHRefs() {
return fHRefs;
}
public boolean getBoolean(String flag) {
if (flag.equals(AUTHOR))
return fAuthor;
else if (flag.equals(VERSION))
return fVersion;
else if (flag.equals(USE))
return fUse;
else if (flag.equals(NODEPRECATED))
return fNodeprecated;
else if (flag.equals(NODEPRECATEDLIST))
return fNoDeprecatedlist;
else if (flag.equals(NOINDEX))
return fNoindex;
else if (flag.equals(NOTREE))
return fNotree;
else if (flag.equals(SPLITINDEX))
return fSplitindex;
else if (flag.equals(NONAVBAR))
return fNonavbar;
else
return false;
}
private boolean loadBoolean(String value) {
if (value == null || value.length() == 0) //$NON-NLS-1$
return false;
else {
if (value.equals("true")) //$NON-NLS-1$
return true;
else
return false;
}
}
private String flatPathList(IPath[] paths) {
StringBuffer buf= new StringBuffer();
for (int i= 0; i < paths.length; i++) {
if (i > 0) {
buf.append(File.pathSeparatorChar);
}
buf.append(paths[i].toOSString());
}
return buf.toString();
}
public void getArgumentArray(List vmArgs, List toolArgs) {
//bug 38692
vmArgs.add(JavadocPreferencePage.getJavaDocCommand());
if (fFromStandard) {
toolArgs.add("-d"); //$NON-NLS-1$
toolArgs.add(fDestination);
} else {
if (fAdditionalParams.length() + fVMParams.length() != 0) {
ExecutionArguments tokens= new ExecutionArguments(fVMParams, fAdditionalParams); //$NON-NLS-1$
String[] vmArgsArray= tokens.getVMArgumentsArray();
for (int i= 0; i < vmArgsArray.length; i++) {
vmArgs.add(vmArgsArray[i]);
}
String[] argsArray= tokens.getProgramArgumentsArray();
for (int i= 0; i < argsArray.length; i++) {
toolArgs.add(argsArray[i]);
}
}
toolArgs.add("-doclet"); //$NON-NLS-1$
toolArgs.add(fDocletname);
toolArgs.add("-docletpath"); //$NON-NLS-1$
toolArgs.add(fDocletpath);
}
toolArgs.add("-sourcepath"); //$NON-NLS-1$
toolArgs.add(flatPathList(fSourcepath));
toolArgs.add("-classpath"); //$NON-NLS-1$
toolArgs.add(flatPathList(fClasspath));
toolArgs.add("-" + fAccess); //$NON-NLS-1$
if (fFromStandard) {
if (fJDK14Mode) {
toolArgs.add("-source"); //$NON-NLS-1$
toolArgs.add("1.4"); //$NON-NLS-1$
}
if (fUse)
toolArgs.add("-use"); //$NON-NLS-1$
if (fVersion)
toolArgs.add("-version"); //$NON-NLS-1$
if (fAuthor)
toolArgs.add("-author"); //$NON-NLS-1$
if (fNonavbar)
toolArgs.add("-nonavbar"); //$NON-NLS-1$
if (fNoindex)
toolArgs.add("-noindex"); //$NON-NLS-1$
if (fNotree)
toolArgs.add("-notree"); //$NON-NLS-1$
if (fNodeprecated)
toolArgs.add("-nodeprecated"); //$NON-NLS-1$
if (fNoDeprecatedlist)
toolArgs.add("-nodeprecatedlist"); //$NON-NLS-1$
if (fSplitindex)
toolArgs.add("-splitindex"); //$NON-NLS-1$
if (fTitle.length() != 0) { //$NON-NLS-1$
toolArgs.add("-doctitle"); //$NON-NLS-1$
toolArgs.add(fTitle);
}
if (fStylesheet.length() != 0) { //$NON-NLS-1$
toolArgs.add("-stylesheetfile"); //$NON-NLS-1$
toolArgs.add(fStylesheet);
}
if (fAdditionalParams.length() + fVMParams.length() != 0) {
ExecutionArguments tokens= new ExecutionArguments(fVMParams, fAdditionalParams); //$NON-NLS-1$
String[] vmArgsArray= tokens.getVMArgumentsArray();
for (int i= 0; i < vmArgsArray.length; i++) {
vmArgs.add(vmArgsArray[i]);
}
String[] argsArray= tokens.getProgramArgumentsArray();
for (int i= 0; i < argsArray.length; i++) {
toolArgs.add(argsArray[i]);
}
}
for (int i= 0; i < fHRefs.length; i++) {
toolArgs.add("-link"); //$NON-NLS-1$
toolArgs.add(fHRefs[i]);
}
} //end standard options
if (fOverview.length() != 0) { //$NON-NLS-1$
toolArgs.add("-overview"); //$NON-NLS-1$
toolArgs.add(fOverview);
}
for (int i= 0; i < fSelectedElements.length; i++) {
IJavaElement curr= fSelectedElements[i];
if (curr instanceof IPackageFragment) {
toolArgs.add(curr.getElementName());
} else if (curr instanceof ICompilationUnit) {
IPath p= curr.getResource().getLocation();
if (p != null)
toolArgs.add(p.toOSString());
}
}
}
public void createXML(IJavaProject[] projects) throws CoreException {
FileOutputStream objectStreamOutput= null;
//@change
//for now only writting ant files for single project selection
String antpath= fAntpath;
try {
if (antpath.length() > 0) {
File file= new File(antpath);
IPath antPath= new Path(antpath);
IPath antDir= antPath.removeLastSegments(1);
IPath basePath= null;
IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
if (root.findFilesForLocation(antPath).length > 0) {
basePath= antDir; // only do relative path if ant file is stored in the workspace
}
antDir.toFile().mkdirs();
objectStreamOutput= new FileOutputStream(file);
JavadocWriter writer= new JavadocWriter(objectStreamOutput, basePath, projects);
writer.writeXML(this);
}
} catch (IOException e) {
String message= JavadocExportMessages.getString("JavadocOptionsManager.createXM.error"); //$NON-NLS-1$
throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, message, e));
} catch (ParserConfigurationException e) {
String message= JavadocExportMessages.getString("JavadocOptionsManager.createXM.error"); //$NON-NLS-1$
throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, message, e));
} catch (TransformerException e) {
String message= JavadocExportMessages.getString("JavadocOptionsManager.createXM.error"); //$NON-NLS-1$
throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, message, e));
} finally {
if (objectStreamOutput != null) {
try {
objectStreamOutput.close();
} catch (IOException e) {
}
}
}
}
public void updateDialogSettings(IDialogSettings dialogSettings, IJavaProject[] checkedProjects) {
IDialogSettings settings= dialogSettings.addNewSection(SECTION_JAVADOC);
settings.put(FROMSTANDARD, fFromStandard);
settings.put(DOCLETNAME, fDocletname);
settings.put(DOCLETPATH, fDocletpath);
settings.put(VISIBILITY, fAccess);
settings.put(USE, fUse);
settings.put(AUTHOR, fAuthor);
settings.put(VERSION, fVersion);
settings.put(NODEPRECATED, fNodeprecated);
settings.put(NODEPRECATEDLIST, fNoDeprecatedlist);
settings.put(SPLITINDEX, fSplitindex);
settings.put(NOINDEX, fNoindex);
settings.put(NOTREE, fNotree);
settings.put(NONAVBAR, fNonavbar);
settings.put(OPENINBROWSER, fOpenInBrowser);
settings.put(SOURCE, fJDK14Mode);
if (fAntpath.length() != 0) //$NON-NLS-1$
settings.put(ANTPATH, fAntpath);
if (fDestination.length() != 0) //$NON-NLS-1$
settings.put(DESTINATION, fDestination);
if (fAdditionalParams.length() != 0) //$NON-NLS-1$
settings.put(EXTRAOPTIONS, fAdditionalParams);
if (fVMParams.length() != 0) //$NON-NLS-1$
settings.put(VMOPTIONS, fVMParams);
if (fOverview.length() != 0) //$NON-NLS-1$
settings.put(OVERVIEW, fOverview);
if (fStylesheet.length() != 0) //$NON-NLS-1$
settings.put(STYLESHEETFILE, fStylesheet);
if (fTitle.length() != 0) //$NON-NLS-1$
settings.put(TITLE, fTitle);
if (checkedProjects.length == 1) {
updateRecentSettings(checkedProjects[0]);
}
getRecentSettings().store(settings);
}
public void setAccess(String access) {
fAccess= access;
}
public void setDestination(String destination) {
fDestination= destination;
}
public void setDocletPath(String docletpath) {
fDocletpath= docletpath;
}
public void setDocletName(String docletname) {
fDocletname= docletname;
}
public void setStyleSheet(String stylesheet) {
fStylesheet= stylesheet;
}
public void setOverview(String overview) {
fOverview= overview;
}
public void setAdditionalParams(String params) {
fAdditionalParams= params;
}
public void setVMParams(String params) {
fVMParams= params;
}
public void setGeneralAntpath(String antpath) {
fAntpath= antpath;
}
public void setClasspath(IPath[] classpath) {
fClasspath= classpath;
}
public void setSourcepath(IPath[] sourcepath) {
fSourcepath= sourcepath;
}
public void setSelectedElements(IJavaElement[] elements) {
fSelectedElements= elements;
}
public void setFromStandard(boolean fromStandard) {
fFromStandard= fromStandard;
}
public void setTitle(String title) {
fTitle= title;
}
public void setOpenInBrowser(boolean openInBrowser) {
fOpenInBrowser= openInBrowser;
}
public void setHRefs(String[] hrefs) {
fHRefs= hrefs;
}
public void setBoolean(String flag, boolean value) {
if (flag.equals(AUTHOR))
fAuthor= value;
else if (flag.equals(USE))
fUse= value;
else if (flag.equals(VERSION))
fVersion= value;
else if (flag.equals(NODEPRECATED))
fNodeprecated= value;
else if (flag.equals(NODEPRECATEDLIST))
fNoDeprecatedlist= value;
else if (flag.equals(NOINDEX))
fNoindex= value;
else if (flag.equals(NOTREE))
fNotree= value;
else if (flag.equals(SPLITINDEX))
fSplitindex= value;
else if (flag.equals(NONAVBAR))
fNonavbar= value;
}
public boolean isJDK14Mode() {
return fJDK14Mode;
}
public void setJDK14Mode(boolean jdk14Mode) {
fJDK14Mode= jdk14Mode;
}
private IJavaElement[] getInitialElementsFromSelection(List candidates) {
ArrayList res= new ArrayList();
for (int i= 0; i < candidates.size(); i++) {
try {
IJavaElement elem= getSelectableJavaElement(candidates.get(i));
if (elem != null) {
res.add(elem);
}
} catch (JavaModelException ignore) {
// ignore this
}
}
return (IJavaElement[]) res.toArray(new IJavaElement[res.size()]);
}
private IJavaElement getSelectableJavaElement(Object obj) throws JavaModelException {
IJavaElement je= null;
if (obj instanceof IAdaptable) {
je= (IJavaElement) ((IAdaptable) obj).getAdapter(IJavaElement.class);
}
if (je != null) {
switch (je.getElementType()) {
case IJavaElement.JAVA_MODEL :
case IJavaElement.JAVA_PROJECT :
case IJavaElement.CLASS_FILE :
break;
case IJavaElement.PACKAGE_FRAGMENT_ROOT :
if (containsCompilationUnits((IPackageFragmentRoot) je)) {
return je;
}
break;
case IJavaElement.PACKAGE_FRAGMENT :
if (containsCompilationUnits((IPackageFragment) je)) {
return je;
}
break;
default :
ICompilationUnit cu= (ICompilationUnit) je.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
return cu;
}
}
IJavaProject project= je.getJavaProject();
if (isValidProject(project))
return project;
}
return null;
}
private boolean isValidProject(IJavaProject project) throws JavaModelException {
if (project != null && project.exists()) {
IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
for (int i= 0; i < roots.length; i++) {
if (containsCompilationUnits(roots[i])) {
return true;
}
}
}
return false;
}
private boolean containsCompilationUnits(IPackageFragmentRoot root) throws JavaModelException {
if (root.getKind() != IPackageFragmentRoot.K_SOURCE) {
return false;
}
IJavaElement[] elements= root.getChildren();
for (int i= 0; i < elements.length; i++) {
if (elements[i] instanceof IPackageFragment) {
IPackageFragment fragment= (IPackageFragment) elements[i];
if (containsCompilationUnits(fragment)) {
return true;
}
}
}
return false;
}
private boolean containsCompilationUnits(IPackageFragment pack) throws JavaModelException {
return pack.getCompilationUnits().length > 0;
}
public RecentSettingsStore getRecentSettings() {
return fRecentSettings;
}
/**
* @param project
*/
public void updateRecentSettings(IJavaProject project) {
fRecentSettings.setProjectSettings(project, fDestination, fAntpath, fHRefs);
}
}
|
53,201 |
Bug 53201 NPE when re-running newly generated javadoc.xml
| null |
resolved fixed
|
4acbc5c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-02T10:53:37Z | 2004-02-26T18:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocWriter.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.javadocexport;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
public class JavadocWriter {
private static final char PATH_SEPARATOR= '/'; // use forward slash for all platforms
private OutputStream fOutputStream;
private IJavaProject[] fJavaProjects;
private IPath fBasePath;
/**
* Create a JavadocWriter on the given output stream.
* It is the client's responsibility to close the output stream.
* @param basePath The base path to which all path will be made relative (if
* possible). If <code>null</code>, paths are not made relative.
*/
public JavadocWriter(OutputStream outputStream, IPath basePath, IJavaProject[] projects) {
Assert.isNotNull(outputStream);
fOutputStream= new BufferedOutputStream(outputStream);
fBasePath= basePath;
fJavaProjects= projects;
}
public void writeXML(JavadocOptionsManager store) throws ParserConfigurationException, TransformerException {
DocumentBuilder docBuilder= null;
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
factory.setValidating(false);
docBuilder= factory.newDocumentBuilder();
Document document= docBuilder.newDocument();
// Create the document
Element project= document.createElement("project"); //$NON-NLS-1$
document.appendChild(project);
project.setAttribute("default", "javadoc"); //$NON-NLS-1$ //$NON-NLS-2$
Element javadocTarget= document.createElement("target"); //$NON-NLS-1$
project.appendChild(javadocTarget);
javadocTarget.setAttribute("name", "javadoc"); //$NON-NLS-1$ //$NON-NLS-2$
Element xmlJavadocDesc= document.createElement("javadoc"); //$NON-NLS-1$
javadocTarget.appendChild(xmlJavadocDesc);
if (!store.isFromStandard())
xmlWriteDoclet(store, document, xmlJavadocDesc);
else
xmlWriteJavadocStandardParams(store, document, xmlJavadocDesc);
// Write the document to the stream
Transformer transformer=TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); //$NON-NLS-1$ //$NON-NLS-2$
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(fOutputStream);
transformer.transform(source, result);
}
//writes ant file, for now only worry about one project
private void xmlWriteJavadocStandardParams(JavadocOptionsManager store, Document document, Element xmlJavadocDesc) throws DOMException {
String destination= getPathString(new Path(store.getDestination()));
xmlJavadocDesc.setAttribute(store.DESTINATION, destination);
xmlJavadocDesc.setAttribute(store.VISIBILITY, store.getAccess());
if (store.isJDK14Mode()) {
xmlJavadocDesc.setAttribute(store.SOURCE, "1.4"); //$NON-NLS-1$
}
xmlJavadocDesc.setAttribute(store.USE, booleanToString(store.getBoolean("use"))); //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.NOTREE, booleanToString(store.getBoolean("notree"))); //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.NONAVBAR, booleanToString(store.getBoolean("nonavbar"))); //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.NOINDEX, booleanToString(store.getBoolean("noindex"))); //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.SPLITINDEX, booleanToString(store.getBoolean("splitindex"))); //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.AUTHOR, booleanToString(store.getBoolean("author"))); //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.VERSION, booleanToString(store.getBoolean("version"))); //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.NODEPRECATEDLIST, booleanToString(store.getBoolean("nodeprecatedlist"))); //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.NODEPRECATED, booleanToString(store.getBoolean("nodeprecated"))); //$NON-NLS-1$
//set the packages and source files
List packages= new ArrayList();
List sourcefiles= new ArrayList();
sortSourceElement(store.getSourceElements(), sourcefiles, packages);
if (!packages.isEmpty())
xmlJavadocDesc.setAttribute(store.PACKAGENAMES, toSeparatedList(packages));
if (!sourcefiles.isEmpty())
xmlJavadocDesc.setAttribute(store.SOURCEFILES, toSeparatedList(sourcefiles));
xmlJavadocDesc.setAttribute(store.SOURCEPATH, getPathString(store.getSourcepath()));
xmlJavadocDesc.setAttribute(store.CLASSPATH, getPathString(store.getClasspath()));
String str= store.getOverview();
if (str.length() > 0) //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.OVERVIEW, str);
str= store.getStyleSheet();
if (str.length() > 0) //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.STYLESHEETFILE, str);
str= store.getTitle();
if (str.length() > 0) //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.TITLE, str);
str= store.getAdditionalParams();
if (str.length() > 0) //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.EXTRAOPTIONS, str);
String[] hrefs= store.getHRefs();
for (int i= 0; i < hrefs.length; i++) {
Element links= document.createElement("link"); //$NON-NLS-1$
xmlJavadocDesc.appendChild(links);
links.setAttribute(store.HREF, hrefs[i]);
}
}
private void sortSourceElement(IJavaElement[] iJavaElements, List sourcefiles, List packages) {
for (int i= 0; i < iJavaElements.length; i++) {
IJavaElement element= iJavaElements[i];
IPath p= element.getResource().getLocation();
if (p == null)
continue;
if (element instanceof ICompilationUnit) {
String relative= getPathString(p);
sourcefiles.add(relative);
} else if (element instanceof IPackageFragment) {
packages.add(element.getElementName());
}
}
}
private String getPathString(IPath[] paths) {
StringBuffer buf= new StringBuffer();
for (int i= 0; i < paths.length; i++) {
if (buf.length() != 0) {
buf.append(File.pathSeparatorChar);
}
buf.append(getPathString(paths[i]));
}
if (buf.length() == 0) {
buf.append('.');
}
return buf.toString();
}
private boolean hasSameDevice(IPath p1, IPath p2) {
String dev= p1.getDevice();
if (dev == null) {
return p2.getDevice() == null;
}
return dev.equals(p2.getDevice());
}
//make the path relative to the base path
private String getPathString(IPath fullPath) {
if (fBasePath == null || !hasSameDevice(fullPath, fBasePath)) {
return fullPath.toOSString();
}
int matchingSegments= fBasePath.matchingFirstSegments(fullPath);
if (fBasePath.segmentCount() == matchingSegments) {
return getRelativePath(fullPath, matchingSegments);
}
for (int i= 0; i < fJavaProjects.length; i++) {
IProject proj= fJavaProjects[i].getProject();
IPath projLoc= proj.getLocation();
if (projLoc.segmentCount() <= matchingSegments && projLoc.isPrefixOf(fullPath)) {
return getRelativePath(fullPath, matchingSegments);
}
}
IPath workspaceLoc= ResourcesPlugin.getWorkspace().getRoot().getLocation();
if (workspaceLoc.segmentCount() <= matchingSegments && workspaceLoc.isPrefixOf(fullPath)) {
return getRelativePath(fullPath, matchingSegments);
}
return fullPath.toOSString();
}
private String getRelativePath(IPath fullPath, int matchingSegments) {
StringBuffer res= new StringBuffer();
int backSegments= fBasePath.segmentCount() - matchingSegments;
while (backSegments > 0) {
res.append(".."); //$NON-NLS-1$
res.append(PATH_SEPARATOR);
backSegments--;
}
int segCount= fullPath.segmentCount();
for (int i= matchingSegments; i < segCount; i++) {
if (i > matchingSegments) {
res.append(PATH_SEPARATOR);
}
res.append(fullPath.segment(i));
}
return res.toString();
}
private void xmlWriteDoclet(JavadocOptionsManager store, Document document, Element xmlJavadocDesc) throws DOMException {
//set the packages and source files
List packages= new ArrayList();
List sourcefiles= new ArrayList();
sortSourceElement(store.getSourceElements(), sourcefiles, packages);
if (!packages.isEmpty())
xmlJavadocDesc.setAttribute(store.PACKAGENAMES, toSeparatedList(packages));
if (!sourcefiles.isEmpty())
xmlJavadocDesc.setAttribute(store.SOURCEFILES, toSeparatedList(sourcefiles));
xmlJavadocDesc.setAttribute(store.SOURCEPATH, getPathString(store.getSourcepath()));
xmlJavadocDesc.setAttribute(store.CLASSPATH, getPathString(store.getClasspath()));
xmlJavadocDesc.setAttribute(store.VISIBILITY, store.getAccess());
Element doclet= document.createElement("doclet"); //$NON-NLS-1$
xmlJavadocDesc.appendChild(doclet);
doclet.setAttribute(store.NAME, store.getDocletName());
doclet.setAttribute(store.PATH, store.getDocletPath());
String str= store.getOverview();
if (str.length() > 0) //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.OVERVIEW, str);
str= store.getAdditionalParams();
if (str.length() > 0) //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.EXTRAOPTIONS, str);
}
private String toSeparatedList(List packages) {
StringBuffer buf= new StringBuffer();
Iterator iter= packages.iterator();
int nAdded= 0;
while (iter.hasNext()) {
if (nAdded > 0) {
buf.append(',');
}
nAdded++;
String curr= (String) iter.next();
buf.append(curr);
}
return buf.toString();
}
private String booleanToString(boolean bool) {
if (bool)
return "true"; //$NON-NLS-1$
else
return "false"; //$NON-NLS-1$
}
public void close() throws IOException {
if (fOutputStream != null) {
fOutputStream.close();
}
}
}
|
51,895 |
Bug 51895 Error when recovering javadoc archive path for a jar
|
1. add swt.jar to the Java build path of a project 2. open the properties dialog for this jar from the package explorer 3. change the javadoc location to : [x] javadoc in archive archive path: <path_to_eclipse>/plugins/org.eclipse.platform/doc/isv/doc.zip (in my case '/home/luc/host/eclipse/plugins/org.eclipse.platform/doc/isv/doc.zip') path within archive: reference/api 4. close the properties dialog 5. reopen the properties dialog The leading slash is missing, the dialog display the error 'the archive is missing '
|
resolved fixed
|
4e039e0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-02T11:36:01Z | 2004-02-12T21:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavadocConfigurationBlock.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.preferences;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipFile;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.wizards.datatransfer.ZipFileStructureProvider;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.OpenBrowserUtil;
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.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
public class JavadocConfigurationBlock {
private static final String FILE_IMPORT_MASK= "*.jar;*.zip"; //$NON-NLS-1$
private static final String ERROR_DIALOG_TITLE= "Error Dialog"; //$NON-NLS-1$
private StringDialogField fURLField;
private StringDialogField fArchiveField;
private StringDialogField fArchivePathField;
private URL fInitialURL;
private SelectionButtonDialogField fValidateURLButton;
private SelectionButtonDialogField fValidateArchiveButton;
private SelectionButtonDialogField fBrowseFolder;
private SelectionButtonDialogField fURLRadioButton;
private SelectionButtonDialogField fArchiveRadioButton;
private SelectionButtonDialogField fBrowseArchive;
private SelectionButtonDialogField fBrowseArchivePath;
private Shell fShell;
private IStatusChangeListener fContext;
private IStatus fURLStatus;
private IStatus fArchiveStatus;
private IStatus fArchivePathStatus;
private URL fURLResult;
private URL fArchiveURLResult;
boolean fIsForSource;
public JavadocConfigurationBlock(Shell shell, IStatusChangeListener context, URL initURL, boolean forSource) {
fShell= shell;
fContext= context;
fInitialURL= initURL;
fIsForSource= forSource;
JDocConfigurationAdapter adapter= new JDocConfigurationAdapter();
if (!forSource) {
fURLRadioButton= new SelectionButtonDialogField(SWT.RADIO);
fURLRadioButton.setDialogFieldListener(adapter);
fURLRadioButton.setLabelText(PreferencesMessages.getString("JavadocConfigurationBlock.location.type.path.label")); //$NON-NLS-1$
}
fURLField= new StringDialogField();
fURLField.setDialogFieldListener(adapter);
fURLField.setLabelText(PreferencesMessages.getString("JavadocConfigurationBlock.location.path.label")); //$NON-NLS-1$
fBrowseFolder= new SelectionButtonDialogField(SWT.PUSH);
fBrowseFolder.setDialogFieldListener(adapter);
fBrowseFolder.setLabelText(PreferencesMessages.getString("JavadocConfigurationBlock.browse.button")); //$NON-NLS-1$
fValidateURLButton= new SelectionButtonDialogField(SWT.PUSH);
fValidateURLButton.setDialogFieldListener(adapter);
fValidateURLButton.setLabelText(PreferencesMessages.getString("JavadocConfigurationBlock.validate.button")); //$NON-NLS-1$
if (!forSource) {
fArchiveRadioButton= new SelectionButtonDialogField(SWT.RADIO);
fArchiveRadioButton.setDialogFieldListener(adapter);
fArchiveRadioButton.setLabelText(PreferencesMessages.getString("JavadocConfigurationBlock.location.type.jar.label")); //$NON-NLS-1$
fArchiveField= new StringDialogField();
fArchiveField.setDialogFieldListener(adapter);
fArchiveField.setLabelText(PreferencesMessages.getString("JavadocConfigurationBlock.location.jar.label")); //$NON-NLS-1$
fBrowseArchive= new SelectionButtonDialogField(SWT.PUSH);
fBrowseArchive.setDialogFieldListener(adapter);
fBrowseArchive.setLabelText(PreferencesMessages.getString("JavadocConfigurationBlock.browse.button")); //$NON-NLS-1$
fArchivePathField= new StringDialogField();
fArchivePathField.setDialogFieldListener(adapter);
fArchivePathField.setLabelText(PreferencesMessages.getString("JavadocConfigurationBlock.jar.path.label")); //$NON-NLS-1$
fBrowseArchivePath= new SelectionButtonDialogField(SWT.PUSH);
fBrowseArchivePath.setDialogFieldListener(adapter);
fBrowseArchivePath.setLabelText(PreferencesMessages.getString("JavadocConfigurationBlock.browse.button")); //$NON-NLS-1$
fValidateArchiveButton= new SelectionButtonDialogField(SWT.PUSH);
fValidateArchiveButton.setDialogFieldListener(adapter);
fValidateArchiveButton.setLabelText(PreferencesMessages.getString("JavadocConfigurationBlock.validate.button")); //$NON-NLS-1$
}
fURLStatus= new StatusInfo();
fArchiveStatus= new StatusInfo();
fArchivePathStatus= new StatusInfo();
initializeSelections();
}
public Control createContents(Composite parent) {
fShell= parent.getShell();
PixelConverter converter= new PixelConverter(parent);
Composite topComp= new Composite(parent, SWT.NONE);
GridLayout topLayout= new GridLayout();
topLayout.numColumns= 3;
topLayout.marginWidth= 0;
topLayout.marginHeight= 0;
topComp.setLayout(topLayout);
// Add the first radio button for the path
if (!fIsForSource) {
fURLRadioButton.doFillIntoGrid(topComp, 3);
}
fURLField.doFillIntoGrid(topComp, 2);
LayoutUtil.setWidthHint(fURLField.getTextControl(null), converter.convertWidthInCharsToPixels(50));
LayoutUtil.setHorizontalGrabbing(fURLField.getTextControl(null));
fBrowseFolder.doFillIntoGrid(topComp, 1);
DialogField.createEmptySpace(topComp, 2);
fValidateURLButton.doFillIntoGrid(topComp, 1);
//DialogField.createEmptySpace(topComp, 3);
if (!fIsForSource) {
// Add the second radio button for the jar/zip
fArchiveRadioButton.doFillIntoGrid(topComp, 3);
// Add the jar/zip field
fArchiveField.doFillIntoGrid(topComp, 2);
LayoutUtil.setWidthHint(fArchiveField.getTextControl(null), converter.convertWidthInCharsToPixels(50));
LayoutUtil.setHorizontalGrabbing(fArchiveField.getTextControl(null));
fBrowseArchive.doFillIntoGrid(topComp, 1);
// Add the path chooser for the jar/zip
fArchivePathField.doFillIntoGrid(topComp, 2);
LayoutUtil.setWidthHint(fArchivePathField.getTextControl(null), converter.convertWidthInCharsToPixels(50));
LayoutUtil.setHorizontalGrabbing(fArchivePathField.getTextControl(null));
fBrowseArchivePath.doFillIntoGrid(topComp, 1);
DialogField.createEmptySpace(topComp, 2);
fValidateArchiveButton.doFillIntoGrid(topComp, 1);
int indent= converter.convertWidthInCharsToPixels(2);
LayoutUtil.setHorizontalIndent(fArchiveField.getLabelControl(null), indent);
LayoutUtil.setHorizontalIndent(fArchivePathField.getLabelControl(null), indent);
LayoutUtil.setHorizontalIndent(fURLField.getLabelControl(null), indent);
fURLRadioButton.attachDialogFields(new DialogField[] {fURLField, fBrowseFolder, fValidateURLButton });
fArchiveRadioButton.attachDialogFields(new DialogField[] {fArchiveField, fBrowseArchive, fArchivePathField, fBrowseArchivePath, fValidateArchiveButton });
}
return topComp;
}
private void initializeSelections() {
String initialValue = fInitialURL != null ? fInitialURL.toExternalForm() : ""; //$NON-NLS-1$
if (fIsForSource) {
fURLField.setText(initialValue);
return;
}
String prefix= JavaDocLocations.ARCHIVE_PREFIX;
boolean isArchive= initialValue.startsWith(prefix); //$NON-NLS-1$
fURLRadioButton.setSelection(!isArchive);
fArchiveRadioButton.setSelection(isArchive);
if (isArchive) {
String jarPath;
String insidePath= ""; //$NON-NLS-1$
int excIndex= initialValue.indexOf('!');
if (excIndex == -1) {
jarPath= initialValue.substring(prefix.length());
} else {
jarPath= initialValue.substring(prefix.length(), excIndex);
insidePath= initialValue.substring(excIndex + 1);
if (insidePath.length() > 0 && insidePath.charAt(0) == '/') {
insidePath= insidePath.substring(1);
}
}
fArchivePathField.setText(insidePath);
fArchiveField.setText(jarPath);
} else {
fURLField.setText(initialValue);
}
}
public void setFocus() {
fURLField.postSetFocusOnDialogField(fShell.getDisplay());
}
public void performDefaults() {
initializeSelections();
}
public URL getJavadocLocation() {
if (fIsForSource || fURLRadioButton.isSelected()) {
return fURLResult;
}
return fArchiveURLResult;
}
private class EntryValidator implements Runnable {
private String fInvalidMessage= PreferencesMessages.getString("JavadocConfigurationBlock.InvalidLocation.message"); //$NON-NLS-1$
private String fValidMessage= PreferencesMessages.getString("JavadocConfigurationBlock.ValidLocation.message"); //$NON-NLS-1$
private String fTitle= PreferencesMessages.getString("JavadocConfigurationBlock.MessageDialog.title"); //$NON-NLS-1$
private String fUnable= PreferencesMessages.getString("JavadocConfigurationBlock.UnableToValidateLocation.message"); //$NON-NLS-1$
public void run() {
URL location= getJavadocLocation();
if (location == null) {
MessageDialog.openInformation(fShell, fTitle, fInvalidMessage); //$NON-NLS-1$
return;
}
try {
String protocol = location.getProtocol();
if (protocol.equals("http") || protocol.equals("jar")) { //$NON-NLS-1$ //$NON-NLS-2$
validateURL(location);
} else if (protocol.equals("file")) { //$NON-NLS-1$
validateFile(location);
} else {
MessageDialog.openInformation(fShell, fTitle, fUnable); //$NON-NLS-1$
}
} catch (MalformedURLException e) {
MessageDialog.openInformation(fShell, fTitle, fUnable); //$NON-NLS-1$
}
}
public void spawnInBrowser(URL url) {
OpenBrowserUtil.open(url, fShell.getDisplay(), fTitle);
}
private void validateFile(URL location) throws MalformedURLException {
File folder = new File(location.getFile());
if (folder.isDirectory()) {
File indexFile= new File(folder, "index.html"); //$NON-NLS-1$
if (indexFile.isFile()) {
File packageList= new File(folder, "package-list"); //$NON-NLS-1$
if (packageList.exists()) {
if (MessageDialog.openConfirm(fShell, fTitle, fValidMessage)) { //$NON-NLS-1$
spawnInBrowser(indexFile.toURL());
}
return;
}
}
}
MessageDialog.openInformation(fShell, fTitle, fInvalidMessage); //$NON-NLS-1$
}
private void validateURL(URL location) throws MalformedURLException {
IPath path= new Path(location.toExternalForm());
IPath index = path.append("index.html"); //$NON-NLS-1$
IPath packagelist = path.append("package-list"); //$NON-NLS-1$
URL indexURL = new URL(index.toString());
URL packagelistURL = new URL(packagelist.toString());
InputStream in1= null;
InputStream in2= null;
try {
in1= indexURL.openConnection().getInputStream();
in2= packagelistURL.openConnection().getInputStream();
if (MessageDialog.openConfirm(fShell, fTitle, fValidMessage))
spawnInBrowser(indexURL);
} catch (IOException e) {
MessageDialog.openInformation(fShell, fTitle, fInvalidMessage);
} finally {
if (in1 != null) { try { in1.close(); } catch (IOException e) {} }
if (in2 != null) { try { in2.close(); } catch (IOException e) {} }
}
}
}
private class JDocConfigurationAdapter implements IDialogFieldListener {
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
jdocDialogFieldChanged(field);
}
}
private void jdocDialogFieldChanged(DialogField field) {
if (field == fURLField) {
fURLStatus= updateURLStatus();
statusChanged();
} else if (field == fArchiveField) {
fArchiveStatus= updateArchiveStatus();
statusChanged();
} else if (field == fArchivePathField) {
fArchivePathStatus= updateArchivePathStatus();
statusChanged();
} else if (field == fValidateURLButton || field == fValidateArchiveButton) {
EntryValidator validator= new EntryValidator();
BusyIndicator.showWhile(fShell.getDisplay(), validator);
} else if (field == fBrowseFolder) {
String url= chooseJavaDocFolder();
if (url != null) {
fURLField.setText(url);
}
} else if (field == fBrowseArchive) {
String jarPath= chooseArchive();
if (jarPath != null) {
fArchiveField.setText(jarPath);
}
} else if (field == fBrowseArchivePath) {
String archivePath= chooseArchivePath();
if (archivePath != null) {
fArchivePathField.setText(archivePath);
}
} else if (field == fURLRadioButton || field == fArchiveRadioButton) {
statusChanged();
}
}
private void statusChanged() {
IStatus status;
boolean isURL= fIsForSource || fURLRadioButton.isSelected();
if (isURL) {
status= fURLStatus;
} else {
status= StatusUtil.getMoreSevere(fArchiveStatus, fArchivePathStatus);
}
if (!fIsForSource) {
fBrowseArchivePath.setEnabled(!isURL && fArchiveStatus.isOK() && fArchiveField.getText().length() > 0);
}
fContext.statusChanged(status);
}
private String chooseArchivePath() {
final String[] res= new String[] { null };
BusyIndicator.showWhile(fShell.getDisplay(), new Runnable() {
public void run() {
res[0]= internalChooseArchivePath();
}
});
return res[0];
}
private String internalChooseArchivePath() {
ZipFile zipFile= null;
try {
zipFile= new ZipFile(fArchiveField.getText());
ZipFileStructureProvider provider= new ZipFileStructureProvider(zipFile);
ILabelProvider lp= new ZipDialogLabelProvider(provider);
ZipDialogContentProvider cp= new ZipDialogContentProvider(provider);
ViewerSorter sorter= new ViewerSorter() {};
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(fShell, lp, cp);
dialog.setAllowMultiple(false);
dialog.setValidator(new ZipDialogValidator());
dialog.setTitle(PreferencesMessages.getString("JavadocConfigurationBlock.browse_jarorzip_path.title")); //$NON-NLS-1$
dialog.setMessage(PreferencesMessages.getString("JavadocConfigurationBlock.location_in_jarorzip.message")); //$NON-NLS-1$
dialog.setSorter(sorter);
String init= fArchivePathField.getText();
if (init.length() == 0) {
init= "docs/api"; //$NON-NLS-1$
}
dialog.setInitialSelection(cp.findElement(new Path(init)));
dialog.setInput(this);
if (dialog.open() == Window.OK) {
String name= provider.getFullPath(dialog.getFirstResult());
return new Path(name).removeTrailingSeparator().toString();
}
} catch (IOException e) {
JavaPlugin.log(e);
} finally {
if (zipFile != null) {
try {
zipFile.close();
} catch (IOException e1) {
// ignore
}
}
}
return null;
}
private String chooseArchive() {
FileDialog dialog= new FileDialog(fShell, SWT.OPEN);
dialog.setFilterExtensions(new String[] { FILE_IMPORT_MASK });
dialog.setText(PreferencesMessages.getString("JavadocConfigurationBlock.zipImportSource.title")); //$NON-NLS-1$
String currentSourceString= fArchiveField.getText();
int lastSeparatorIndex= currentSourceString.lastIndexOf(File.separator);
if (lastSeparatorIndex != -1)
dialog.setFilterPath(currentSourceString.substring(0, lastSeparatorIndex));
return dialog.open();
}
/**
* Display an error dialog with the specified message.
*
* @param message the error message
*/
protected void displayErrorDialog(String message) {
MessageDialog.openError(fShell, ERROR_DIALOG_TITLE, message); //$NON-NLS-1$
}
private String chooseJavaDocFolder() {
String initPath= ""; //$NON-NLS-1$
if (fURLResult != null && "file".equals(fURLResult.getProtocol())) { //$NON-NLS-1$
initPath= (new File(fURLResult.getFile())).getPath();
}
DirectoryDialog dialog= new DirectoryDialog(fShell);
dialog.setText(PreferencesMessages.getString("JavadocConfigurationBlock.javadocFolderDialog.label")); //$NON-NLS-1$
dialog.setMessage(PreferencesMessages.getString("JavadocConfigurationBlock.javadocFolderDialog.message")); //$NON-NLS-1$
dialog.setFilterPath(initPath);
String result= dialog.open();
if (result != null) {
try {
URL url= new File(result).toURL();
return url.toExternalForm();
} catch (MalformedURLException e) {
JavaPlugin.log(e);
}
}
return null;
}
private IStatus updateURLStatus() {
StatusInfo status= new StatusInfo();
fURLResult= null;
try {
String jdocLocation= fURLField.getText();
if (jdocLocation.length() == 0) {
return status;
}
if (jdocLocation.length() > 0) {
URL url= new URL(jdocLocation);
if ("file".equals(url.getProtocol())) { //$NON-NLS-1$
if (url.getFile() == null) {
status.setError(PreferencesMessages.getString("JavadocConfigurationBlock.error.notafolder")); //$NON-NLS-1$
return status;
} else {
File dir= new File(url.getFile());
if (!dir.isDirectory()) {
status.setError(PreferencesMessages.getString("JavadocConfigurationBlock.error.notafolder")); //$NON-NLS-1$
return status;
}
File packagesFile= new File(dir, "package-list"); //$NON-NLS-1$
if (!packagesFile.exists()) {
status.setWarning(PreferencesMessages.getString("JavadocConfigurationBlock.warning.packagelistnotfound")); //$NON-NLS-1$
// only a warning, go on
}
}
}
fURLResult= url;
}
} catch (MalformedURLException e) {
status.setError(PreferencesMessages.getString("JavadocConfigurationBlock.MalformedURL.error")); //$NON-NLS-1$
return status;
}
return status;
}
private IStatus updateArchiveStatus() {
try {
fArchiveURLResult= null;
StatusInfo status= new StatusInfo();
String jdocLocation= fArchiveField.getText();
if (jdocLocation.length() > 0) {
File jarFile= new File(jdocLocation);
if (jarFile.isDirectory()) {
status.setError(PreferencesMessages.getString("JavadocConfigurationBlock.error.notafile")); //$NON-NLS-1$
return status;
}
if (!jarFile.exists()) {
status.setError(PreferencesMessages.getString("JavadocConfigurationBlock.error.notafile")); //$NON-NLS-1$
return status;
}
fArchiveURLResult= getArchiveURL();
}
return status;
} catch (MalformedURLException e) {
StatusInfo status= new StatusInfo();
status.setError(e.getMessage()); //$NON-NLS-1$
return status;
}
}
private IStatus updateArchivePathStatus() {
// no validation yet
try {
fArchiveURLResult= getArchiveURL();
} catch (MalformedURLException e) {
fArchiveURLResult= null;
StatusInfo status= new StatusInfo();
status.setError(e.getMessage()); //$NON-NLS-1$
//status.setError(PreferencesMessages.getString("JavadocConfigurationBlock.MalformedURL.error")); //$NON-NLS-1$
return status;
}
return new StatusInfo();
}
private URL getArchiveURL() throws MalformedURLException {
String jarLoc= fArchiveField.getText();
String innerPath= fArchivePathField.getText().trim();
StringBuffer buf= new StringBuffer();
buf.append("jar:"); //$NON-NLS-1$
buf.append(new File(jarLoc).toURL().toExternalForm());
buf.append('!');
if (innerPath.length() > 0) {
if (innerPath.charAt(0) != '/') {
buf.append('/');
}
buf.append(innerPath);
} else {
buf.append('/');
}
return new URL(buf.toString());
}
/**
* An adapter for presenting a zip file in a tree viewer.
*/
private static class ZipDialogContentProvider implements ITreeContentProvider {
private ZipFileStructureProvider fProvider;
public ZipDialogContentProvider(ZipFileStructureProvider provider) {
fProvider= provider;
}
public Object findElement(IPath path) {
String[] segments= path.segments();
Object elem= fProvider.getRoot();
for (int i= 0; i < segments.length && elem != null; i++) {
List list= fProvider.getChildren(elem);
String name= segments[i];
elem= null;
for (int k= 0; k < list.size(); k++) {
Object curr= list.get(k);
if (fProvider.isFolder(curr) && name.equals(fProvider.getLabel(curr))) {
elem= curr;
break;
}
}
}
return elem;
}
private Object recursiveFind(Object element, String name) {
if (name.equals(fProvider.getLabel(element))) {
return element;
}
List list= fProvider.getChildren(element);
if (list != null) {
for (int k= 0; k < list.size(); k++) {
Object res= recursiveFind(list.get(k), name);
if (res != null) {
return res;
}
}
}
return null;
}
public Object findFileByName(String name) {
return recursiveFind(fProvider.getRoot(), name);
}
/* non java-doc
* @see ITreeContentProvider#inputChanged
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
/* non java-doc
* @see ITreeContentProvider#getParent
*/
public Object getParent(Object element) {
if (element.equals(fProvider.getRoot())) {
return null;
}
IPath path= new Path(fProvider.getFullPath(element));
if (path.segmentCount() > 0) {
return findElement(path.removeLastSegments(1));
}
return fProvider.getRoot();
}
/* non java-doc
* @see ITreeContentProvider#hasChildren
*/
public boolean hasChildren(Object element) {
List list= fProvider.getChildren(element);
if (list != null) {
for (int i= 0; i < list.size(); i++) {
if (fProvider.isFolder(list.get(i))) {
return true;
}
}
}
return false;
}
/* non java-doc
* @see ITreeContentProvider#getChildren
*/
public Object[] getChildren(Object element) {
List list= fProvider.getChildren(element);
ArrayList res= new ArrayList();
if (list != null) {
for (int i= 0; i < list.size(); i++) {
Object curr= list.get(i);
if (fProvider.isFolder(curr)) {
res.add(curr);
}
}
}
return res.toArray();
}
/* non java-doc
* @see ITreeContentProvider#getElements
*/
public Object[] getElements(Object element) {
return new Object[] {fProvider.getRoot() };
}
/* non java-doc
* @see IContentProvider#dispose
*/
public void dispose() {
}
}
private static class ZipDialogLabelProvider extends LabelProvider {
private final Image IMG_JAR=
JavaUI.getSharedImages().getImage(org.eclipse.jdt.ui.ISharedImages.IMG_OBJS_JAR);
private final Image IMG_FOLDER=
PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER);
private ZipFileStructureProvider fProvider;
public ZipDialogLabelProvider(ZipFileStructureProvider provider) {
fProvider= provider;
}
public Image getImage(Object element) {
if (element == fProvider.getRoot()) {
return IMG_JAR;
} else {
return IMG_FOLDER;
}
}
public String getText(Object element) {
if (element == fProvider.getRoot()) {
return fProvider.getZipFile().getName();
}
return fProvider.getLabel(element);
}
}
private static class ZipDialogValidator implements ISelectionStatusValidator {
public ZipDialogValidator() {
super();
}
/*
* @see ISelectionValidator#validate(Object[])
*/
public IStatus validate(Object[] selection) {
String message= ""; //$NON-NLS-1$
return new StatusInfo(IStatus.INFO, message);
}
}
}
|
53,530 |
Bug 53530 Call Hierarchy: change "Location" column header to line
|
Hi Jesper. What do you think about changing the second column header in the Location View to "Line" and dropping the prefix "line " from the table cells? This would allow to make the column narrower (the repeated "line " is not really interesting).
|
resolved fixed
|
ccf40d8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-03T20:35:50Z | 2004-03-02T20:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/LocationLabelProvider.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.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.corext.callhierarchy.CallLocation;
class LocationLabelProvider extends LabelProvider implements ITableLabelProvider {
private static final int COLUMN_ICON= 0;
private static final int COLUMN_LINE= 1;
private static final int COLUMN_INFO= 2;
LocationLabelProvider() {
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object)
*/
public String getText(Object element) {
return getColumnText(element, COLUMN_INFO);
}
public Image getImage(Object element) {
return getColumnImage(element, COLUMN_ICON);
}
/**
* @param string
* @return String
*/
private String removeWhitespaceOutsideStringLiterals(CallLocation callLocation) {
StringBuffer buf = new StringBuffer();
boolean withinString = false;
String s= callLocation.getCallText();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '"') {
withinString = !withinString;
}
if (withinString) {
buf.append(ch);
} else if (Character.isWhitespace(ch)) {
if ((buf.length() == 0) ||
!Character.isWhitespace(buf.charAt(buf.length() - 1))) {
if (ch != ' ') {
ch = ' ';
}
buf.append(ch);
}
} else {
buf.append(ch);
}
}
return buf.toString();
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
*/
public Image getColumnImage(Object element, int columnIndex) {
if (columnIndex == COLUMN_ICON) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_SEARCH_OCCURRENCE);
}
return null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
*/
public String getColumnText(Object element, int columnIndex) {
if (element instanceof CallLocation) {
CallLocation callLocation= (CallLocation) element;
switch (columnIndex) {
case COLUMN_LINE:
int lineNumber= callLocation.getLineNumber();
if (lineNumber == CallLocation.UNKNOWN_LINE_NUMBER) {
return CallHierarchyMessages.getString("LocationLabelProvider.unknown");//$NON-NLS-1$
} else {
String[] values= {String.valueOf(lineNumber)};
return CallHierarchyMessages.getFormattedString("LocationLabelProvider.lineNumber", values);//$NON-NLS-1$
}
case COLUMN_INFO:
return removeWhitespaceOutsideStringLiterals(callLocation);
}
}
return ""; //$NON-NLS-1$
}
}
|
53,530 |
Bug 53530 Call Hierarchy: change "Location" column header to line
|
Hi Jesper. What do you think about changing the second column header in the Location View to "Line" and dropping the prefix "line " from the table cells? This would allow to make the column narrower (the repeated "line " is not really interesting).
|
resolved fixed
|
ccf40d8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-03T20:35:50Z | 2004-03-02T20:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/LocationViewer.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 org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLayoutData;
import org.eclipse.jface.viewers.ColumnPixelData;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
class LocationViewer extends TableViewer {
private final String columnHeaders[] = {
CallHierarchyMessages.getString("LocationViewer.ColumnIcon.header"),//$NON-NLS-1$
CallHierarchyMessages.getString("LocationViewer.ColumnLine.header"),//$NON-NLS-1$
CallHierarchyMessages.getString("LocationViewer.ColumnInfo.header")}; //$NON-NLS-1$
private ColumnLayoutData columnLayouts[] = {
new ColumnPixelData(19, false),
new ColumnWeightData(75),
new ColumnWeightData(300)};
LocationViewer(Composite parent) {
super(createTable(parent));
setContentProvider(new ArrayContentProvider());
setLabelProvider(new LocationLabelProvider());
setInput(new ArrayList());
createColumns();
JavaUIHelp.setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_VIEW);
}
/**
* Creates the table control.
*/
private static Table createTable(Composite parent) {
return new Table(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION);
}
private void createColumns() {
TableLayout layout = new TableLayout();
getTable().setLayout(layout);
getTable().setHeaderVisible(true);
for (int i = 0; i < columnHeaders.length; i++) {
layout.addColumnData(columnLayouts[i]);
TableColumn tc = new TableColumn(getTable(), SWT.NONE,i);
tc.setResizable(columnLayouts[i].resizable);
tc.setText(columnHeaders[i]);
}
}
/**
* 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(getControl());
getControl().setMenu(menu);
viewSite.registerContextMenu(popupId, menuMgr, this);
}
/**
*
*/
void clearViewer() {
setInput(""); //$NON-NLS-1$
}
}
|
49,838 |
Bug 49838 New Search: Tooltip texts should be commands
|
Tooltips usually don't describe what their widget does, but are just short commands in title case. Where the new search view e.g. says "Shows the next match", it should read "Show Next Match" (as in the old search view). This applies to all buttons.
|
resolved fixed
|
eda7316
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-04T09:38:36Z | 2004-01-12T09:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/GroupAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.search;
import org.eclipse.jface.action.Action;
public class GroupAction extends Action {
private int fGrouping;
private JavaSearchResultPage fPage;
public GroupAction(String label, JavaSearchResultPage page, int grouping) {
super(label);
fPage= page;
fGrouping= grouping;
}
public void run() {
fPage.setGrouping(fGrouping);
}
public int getGrouping() {
return fGrouping;
}
}
|
49,838 |
Bug 49838 New Search: Tooltip texts should be commands
|
Tooltips usually don't describe what their widget does, but are just short commands in title case. Where the new search view e.g. says "Shows the next match", it should read "Show Next Match" (as in the old search view). This applies to all buttons.
|
resolved fixed
|
eda7316
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-04T09:38:36Z | 2004-01-12T09:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchResultPage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.search;
import java.util.HashMap;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.search.ui.IContextMenuConstants;
import org.eclipse.search.ui.ISearchResultViewPart;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.search.ui.text.AbstractTextSearchViewPage;
import org.eclipse.search.ui.text.Match;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
public class JavaSearchResultPage extends AbstractTextSearchViewPage {
private NewSearchViewActionGroup fActionGroup;
private JavaSearchContentProvider fContentProvider;
private int fCurrentSortOrder;
private SortAction fSortByNameAction;
private SortAction fSortByParentName;
private SortAction fSortByPathAction;
private GroupAction fGroupTypeAction;
private GroupAction fGroupFileAction;
private GroupAction fGroupPackageAction;
private GroupAction fGroupProjectAction;
private int fCurrentGrouping;
public JavaSearchResultPage() {
fSortByNameAction= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByName"), this, JavaSearchResultLabelProvider.SHOW_ELEMENT_CONTAINER); //$NON-NLS-1$
fSortByPathAction= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByPath"), this, JavaSearchResultLabelProvider.SHOW_PATH); //$NON-NLS-1$
fSortByParentName= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByParentName"), this, JavaSearchResultLabelProvider.SHOW_CONTAINER_ELEMENT); //$NON-NLS-1$
fCurrentSortOrder= JavaSearchResultLabelProvider.SHOW_ELEMENT_CONTAINER;
initGroupingActions();
}
private void initGroupingActions() {
fGroupProjectAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_project"), this, LevelTreeContentProvider.LEVEL_PROJECT); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(fGroupProjectAction, "prj_mode.gif"); //$NON-NLS-1$
fGroupPackageAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_package"), this, LevelTreeContentProvider.LEVEL_PACKAGE); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(fGroupPackageAction, "package_mode.gif"); //$NON-NLS-1$
fGroupFileAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_file"), this, LevelTreeContentProvider.LEVEL_FILE); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(fGroupFileAction, "file_mode.gif"); //$NON-NLS-1$
fGroupTypeAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_type"), this, LevelTreeContentProvider.LEVEL_TYPE); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(fGroupTypeAction, "class_obj.gif"); //$NON-NLS-1$
fCurrentGrouping= LevelTreeContentProvider.LEVEL_PACKAGE;
}
public void setViewPart(ISearchResultViewPart part) {
// TODO Auto-generated method stub
super.setViewPart(part);
fActionGroup= new NewSearchViewActionGroup(part);
}
public void showMatch(Match match, int offset, int length) throws PartInitException {
IEditorPart editor= null;
Object element= match.getElement();
if (element instanceof IJavaElement) {
IJavaElement javaElement= (IJavaElement) element;
try {
editor= EditorUtility.openInEditor(javaElement, false);
} catch (PartInitException e1) {
return;
} catch (JavaModelException e1) {
return;
}
} else if (element instanceof IFile) {
editor= IDE.openEditor(JavaPlugin.getActivePage(), (IFile) element, false);
}
if (!(editor instanceof ITextEditor)) {
if (element instanceof IFile) {
IFile file= (IFile) element;
showWithMarker(editor, file, offset, length);
}
} else {
ITextEditor textEditor= (ITextEditor) editor;
textEditor.selectAndReveal(offset, length);
}
}
private void showWithMarker(IEditorPart editor, IFile file, int offset, int length) throws PartInitException {
try {
IMarker marker= file.createMarker(SearchUI.SEARCH_MARKER);
HashMap attributes= new HashMap(4);
attributes.put(IMarker.CHAR_START, new Integer(offset));
attributes.put(IMarker.CHAR_END, new Integer(offset + length));
marker.setAttributes(attributes);
IDE.gotoMarker(editor, marker);
marker.delete();
} catch (CoreException e) {
throw new PartInitException(SearchMessages.getString("JavaSearchResultPage.error.marker"), e); //$NON-NLS-1$
}
}
protected void fillContextMenu(IMenuManager mgr) {
super.fillContextMenu(mgr);
addSortActions(mgr);
fActionGroup.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
fActionGroup.fillContextMenu(mgr);
}
private void addSortActions(IMenuManager mgr) {
if (!isFlatLayout())
return;
MenuManager sortMenu= new MenuManager(SearchMessages.getString("JavaSearchResultPage.sortBylabel")); //$NON-NLS-1$
sortMenu.add(fSortByNameAction);
sortMenu.add(fSortByPathAction);
sortMenu.add(fSortByParentName);
fSortByNameAction.setChecked(fCurrentSortOrder == fSortByNameAction.getSortOrder());
fSortByPathAction.setChecked(fCurrentSortOrder == fSortByPathAction.getSortOrder());
fSortByParentName.setChecked(fCurrentSortOrder == fSortByParentName.getSortOrder());
mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, sortMenu);
}
protected void fillToolbar(IToolBarManager tbm) {
super.fillToolbar(tbm);
if (!isFlatLayout())
addGroupActions(tbm);
}
private void addGroupActions(IToolBarManager mgr) {
mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, fGroupProjectAction);
mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, fGroupPackageAction);
mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, fGroupFileAction);
mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, fGroupTypeAction);
updateGroupingActions();
}
private void updateGroupingActions() {
fGroupProjectAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_PROJECT);
fGroupPackageAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_PACKAGE);
fGroupFileAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_FILE);
fGroupTypeAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_TYPE);
}
public void dispose() {
fActionGroup.dispose();
super.dispose();
}
protected void elementsChanged(Object[] objects) {
if (fContentProvider != null)
fContentProvider.elementsChanged(objects);
}
protected void clear() {
if (fContentProvider != null)
fContentProvider.clear();
}
protected void configureTableViewer(TableViewer viewer) {
viewer.setLabelProvider(new DelegatingLabelProvider(this, new JavaSearchResultLabelProvider()));
fContentProvider=new JavaSearchTableContentProvider(viewer);
viewer.setContentProvider(fContentProvider);
setSortOrder(fCurrentSortOrder);
}
protected void configureTreeViewer(AbstractTreeViewer viewer) {
viewer.setSorter(new ViewerSorter());
viewer.setLabelProvider(new PostfixLabelProvider(this));
fContentProvider= new LevelTreeContentProvider(viewer, fCurrentGrouping);
viewer.setContentProvider(fContentProvider);
}
void setSortOrder(int order) {
fCurrentSortOrder= order;
StructuredViewer viewer= getViewer();
DelegatingLabelProvider lpWrapper= (DelegatingLabelProvider) viewer.getLabelProvider();
((JavaSearchResultLabelProvider)lpWrapper.getLabelProvider()).setOrder(order);
if (order == JavaSearchResultLabelProvider.SHOW_ELEMENT_CONTAINER) {
viewer.setSorter(new NameSorter());
} else if (order == JavaSearchResultLabelProvider.SHOW_PATH) {
viewer.setSorter(new PathSorter());
} else
viewer.setSorter(new ParentSorter());
}
public void init(IPageSite site) {
super.init(site);
fActionGroup.fillActionBars(site.getActionBars());
}
/**
* Precondition here: the viewer must be shwing a tree with a LevelContentProvider.
* @param order
*/
void setGrouping(int grouping) {
fCurrentGrouping= grouping;
StructuredViewer viewer= getViewer();
LevelTreeContentProvider cp= (LevelTreeContentProvider) viewer.getContentProvider();
cp.setLevel(grouping);
updateGroupingActions();
}
protected StructuredViewer getViewer() {
// override so that it's visible in the package.
return super.getViewer();
}
}
|
51,654 |
Bug 51654 [formatting] formatter removes last line with block comments
|
The formatter seems to remove anything contained on the line with the end block comment. before formating: example: /* style.process( xmlinput, new XSLTResultTarget(response.getWriter())); */ After formating: /* * style.process( xmlinput, */ If I put the end block comment on the next line if format properly. I am using all the default settings for 3.0M6
|
verified fixed
|
300dd9c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-04T10:12:30Z | 2004-02-11T17:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/MultiCommentLine.java
|
/*****************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*****************************************************************************/
package org.eclipse.jdt.internal.ui.text.comment;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.jdt.internal.ui.text.javadoc.IHtmlTagConstants;
import org.eclipse.jdt.internal.ui.text.javadoc.IJavaDocTagConstants;
import org.eclipse.jdt.internal.ui.text.javadoc.ILinkTagConstants;
/**
* Multi-line comment line in a comment region.
*
* @since 3.0
*/
public class MultiCommentLine extends CommentLine implements ICommentAttributes, IHtmlTagConstants, ILinkTagConstants, IJavaDocTagConstants {
/** Line prefix of multi-line comment content lines */
public static final String MULTI_COMMENT_CONTENT_PREFIX= " * "; //$NON-NLS-1$
/** Line prefix of multi-line comment end lines */
public static final String MULTI_COMMENT_END_PREFIX= " */"; //$NON-NLS-1$
/** Line prefix of multi-line comment content lines */
public static final String MULTI_COMMENT_START_PREFIX= "/* "; //$NON-NLS-1$
/** The reference indentation of this line */
private String fIndentation= ""; //$NON-NLS-1$
/** The javadoc tag lookup. */
private static final Set fgTagLookup;
static {
fgTagLookup= new HashSet();
for (int i= 0; i < JAVADOC_BREAK_TAGS.length; i++) {
fgTagLookup.add(JAVADOC_BREAK_TAGS[i]);
}
for (int i= 0; i < JAVADOC_SINGLE_BREAK_TAG.length; i++) {
fgTagLookup.add(JAVADOC_SINGLE_BREAK_TAG[i]);
}
for (int i= 0; i < JAVADOC_CODE_TAGS.length; i++) {
fgTagLookup.add(JAVADOC_CODE_TAGS[i]);
}
for (int i= 0; i < JAVADOC_IMMUTABLE_TAGS.length; i++) {
fgTagLookup.add(JAVADOC_IMMUTABLE_TAGS[i]);
}
for (int i= 0; i < JAVADOC_NEWLINE_TAGS.length; i++) {
fgTagLookup.add(JAVADOC_NEWLINE_TAGS[i]);
}
for (int i= 0; i < JAVADOC_SEPARATOR_TAGS.length; i++) {
fgTagLookup.add(JAVADOC_SEPARATOR_TAGS[i]);
}
}
/**
* Creates a new multi-line comment line.
*
* @param region
* Comment region to create the line for
*/
protected MultiCommentLine(final CommentRegion region) {
super(region);
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#adapt(org.eclipse.jdt.internal.ui.text.comment.CommentLine)
*/
protected void adapt(final CommentLine previous) {
if (!hasAttribute(COMMENT_ROOT) && !hasAttribute(COMMENT_PARAMETER) && !previous.hasAttribute(COMMENT_BLANKLINE))
fIndentation= previous.getIndentation();
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#append(org.eclipse.jdt.internal.ui.text.comment.CommentRange)
*/
protected void append(final CommentRange range) {
final MultiCommentRegion parent= (MultiCommentRegion)getParent();
if (range.hasAttribute(COMMENT_PARAMETER))
setAttribute(COMMENT_PARAMETER);
else if (range.hasAttribute(COMMENT_ROOT))
setAttribute(COMMENT_ROOT);
else if (range.hasAttribute(COMMENT_BLANKLINE))
setAttribute(COMMENT_BLANKLINE);
final int ranges= getSize();
if (ranges == 1) {
if (parent.isIndentRoots()) {
final CommentRange first= getFirst();
final String common= parent.getText(first.getOffset(), first.getLength()) + CommentRegion.COMMENT_RANGE_DELIMITER;
if (hasAttribute(COMMENT_ROOT))
fIndentation= common;
else if (hasAttribute(COMMENT_PARAMETER)) {
if (parent.isIndentDescriptions())
fIndentation= common + "\t"; //$NON-NLS-1$
else
fIndentation= common;
}
}
}
super.append(range);
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#getContentLinePrefix()
*/
protected String getContentPrefix() {
return MULTI_COMMENT_CONTENT_PREFIX;
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#getEndLinePrefix()
*/
protected String getEndingPrefix() {
return MULTI_COMMENT_END_PREFIX;
}
/**
* Returns the reference indentation to use for this line.
*
* @return The reference indentation for this line
*/
protected final String getIndentation() {
return fIndentation;
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#getStartLinePrefix()
*/
protected String getStartingPrefix() {
return MULTI_COMMENT_START_PREFIX;
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#scanLine(int)
*/
protected void scanLine(final int line) {
final CommentRegion parent= getParent();
final String start= getStartingPrefix().trim();
final String end= getEndingPrefix().trim();
final String content= getContentPrefix().trim();
final int lines= parent.getSize();
final CommentRange range= getFirst();
int offset= 0;
int postfix= 0;
String text= parent.getText(range.getOffset(), range.getLength());
if (line == 0) {
offset= text.indexOf(start);
if (offset >= 0) {
offset += start.length();
range.trimBegin(offset);
postfix= text.lastIndexOf(end);
if (postfix > offset)
range.setLength(postfix - offset);
else {
postfix= text.lastIndexOf(content);
if (postfix >= offset) {
range.setLength(postfix - offset);
parent.setBorder(BORDER_UPPER);
if (postfix > offset) {
text= parent.getText(range.getOffset(), range.getLength());
final IRegion region= trimLine(text, content);
range.move(region.getOffset());
range.setLength(region.getLength());
}
}
}
}
} else if (line == lines - 1) {
offset= text.indexOf(content);
if (offset >= 0) {
range.trimBegin(offset + 1);
if (text.startsWith(end, offset))
range.setLength(0);
else {
postfix= text.lastIndexOf(end);
if (postfix > offset) {
range.trimEnd(-end.length());
text= parent.getText(range.getOffset(), range.getLength());
final IRegion region= trimLine(text, content);
if (region.getOffset() != 0 || region.getLength() != text.length()) {
range.move(region.getOffset());
range.setLength(region.getLength());
parent.setBorder(BORDER_UPPER);
parent.setBorder(BORDER_LOWER);
}
}
}
}
} else {
offset= text.indexOf(content);
if (offset >= 0) {
offset += content.length();
range.trimBegin(offset);
}
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#tokenizeLine(int)
*/
protected void tokenizeLine(int line) {
int offset= 0;
int index= offset;
final CommentRegion parent= getParent();
final CommentRange range= getFirst();
final int begin= range.getOffset();
final String content= parent.getText(begin, range.getLength());
final int length= content.length();
while (offset < length && Character.isWhitespace(content.charAt(offset)))
offset++;
CommentRange result= null;
if (offset >= length && !parent.isClearLines() && (line > 0 && line < parent.getSize() - 1)) {
result= new CommentRange(begin, 0);
result.setAttribute(COMMENT_BLANKLINE);
result.setAttribute(COMMENT_FIRST_TOKEN);
parent.append(result);
}
int attribute= COMMENT_FIRST_TOKEN;
while (offset < length) {
while (offset < length && Character.isWhitespace(content.charAt(offset)))
offset++;
index= offset;
if (index < length) {
if (content.charAt(index) == HTML_TAG_PREFIX) {
// in order to avoid recognizign any < in a comment, even those which are part of e.g.
// java source code, we validate the tag content to be one of the recognized
// tags (structural, breaks, pre, code).
int tag= ++index;
while (index < length && content.charAt(index) != HTML_TAG_POSTFIX && content.charAt(index) != HTML_TAG_PREFIX)
index++;
if (index < length && content.charAt(index) == HTML_TAG_POSTFIX && isValidTag(content.substring(tag, index))) {
index++;
attribute |= COMMENT_HTML; // only set html attribute if postfix found
} else {
// no tag - do the usual thing from the original offset
index= tag;
while (index < length && !Character.isWhitespace(content.charAt(index)) && content.charAt(index) != HTML_TAG_PREFIX && !content.startsWith(LINK_TAG_PREFIX, index))
index++;
}
} else if (content.startsWith(LINK_TAG_PREFIX, index)) {
while (index < length && content.charAt(index) != LINK_TAG_POSTFIX)
index++;
if (index < length && content.charAt(index) == LINK_TAG_POSTFIX)
index++;
attribute |= COMMENT_OPEN | COMMENT_CLOSE;
} else {
while (index < length && !Character.isWhitespace(content.charAt(index)) && content.charAt(index) != HTML_TAG_PREFIX && !content.startsWith(LINK_TAG_PREFIX, index))
index++;
}
}
if (index - offset > 0) {
result= new CommentRange(begin + offset, index - offset);
result.setAttribute(attribute);
parent.append(result);
offset= index;
}
attribute= 0;
}
}
/**
* Checks whether <code>tag</code> is a valid tag content (text inside the angular
* brackets <, >).
* <p>
* The algorithm is to see if the tag trimmed of whitespace and an optional slash
* starts with one of our recognized tags.
*
* @param tag
* @return <code>true</code> if <code>tag</code> is a valid tag content
*/
private boolean isValidTag(String tag) {
// strip the slash
if (tag.startsWith("/")) //$NON-NLS-1$
tag= tag.substring(1, tag.length());
// strip ws
tag= tag.trim();
// extract first token
int i= 0;
while (i < tag.length() && !Character.isWhitespace(tag.charAt(i)))
i++;
tag= tag.substring(0, i);
// see if it's a tag
return isTagName(tag.toLowerCase());
}
/**
* Checks whether <code>tag</code> is one of the configured tags.
*
* @param tag the tag to check
* @return <code>true</code> if <code>tag</code> is a configured tag name
*/
private boolean isTagName(String tag) {
return fgTagLookup.contains(tag);
}
/**
* Removes all leading and trailing occurrences from <code>line</code>.
*
* @param line
* The string to remove the occurrences of <code>trimmable</code>
* @param trimmable
* The string to remove from <code>line</code>
* @return The region of the trimmed substring within <code>line</code>
*/
protected final IRegion trimLine(final String line, final String trimmable) {
final int trim= trimmable.length();
int offset= 0;
int length= line.length() - trim;
while (line.startsWith(trimmable, offset))
offset += trim;
while (line.startsWith(trimmable, length))
length -= trim;
return new Region(offset, length + trim);
}
}
|
51,670 |
Bug 51670 New java search page is blank until next button pressed
|
2.0 20040211 16:00 I've enabled the new search view and find that often the search will complete and the window will be empty. Although I know that some matches should exist, I press the next button and items suddenly appear in view and are expanded. Sorry for the lack of repeatable steps, but it does happen quite frequently.
|
resolved fixed
|
1dc1fe8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-05T09:52:08Z | 2004-02-11T17:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/LevelTreeContentProvider.java
| |
53,704 |
Bug 53704 M7: JUnit assumes that development mode includes "bin" folders
|
JUnitLaunchConfiguration.java, starting at line 127: if (BootLoader.inDevelopmentMode()) { // assumption is that the output folder is called bin! List junitEntries= new ArrayList(); junitEntries.add(Platform.asLocalURL(new URL(url, "bin")).getFile()); //$NON-NLS-1$ If the plug-in is in the workspace as binary, or with linked content only, the bin folder does not exist, and line 130 quits with an IOException.
|
resolved fixed
|
cfcfd26
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-05T18:41:33Z | 2004-03-04T03:13:20Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/launcher/JUnitLaunchConfiguration.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.junit.launcher;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import org.eclipse.core.boot.BootLoader;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPluginDescriptor;
import org.eclipse.core.runtime.IPluginRegistry;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.internal.junit.ui.JUnitPlugin;
import org.eclipse.jdt.launching.ExecutionArguments;
import org.eclipse.jdt.launching.VMRunnerConfiguration;
/**
* Launch configuration delegate for a plain JUnit test.
*/
public class JUnitLaunchConfiguration extends JUnitBaseLaunchConfiguration {
public static final String ID_JUNIT_APPLICATION= "org.eclipse.jdt.junit.launchconfig"; //$NON-NLS-1$
/**
* Add a VMRunner with a class path that includes org.eclipse.jdt.junit plugin.
* In addition it adds the port for the RemoteTestRunner as an argument
*/
protected VMRunnerConfiguration createVMRunner(ILaunchConfiguration configuration, IType[] testTypes, int port, String runMode) throws CoreException {
String[] classPath= createClassPath(configuration);
String progArgs= getProgramArguments(configuration);
VMRunnerConfiguration vmConfig= new VMRunnerConfiguration("org.eclipse.jdt.internal.junit.runner.RemoteTestRunner", classPath); //$NON-NLS-1$
String testName= configuration.getAttribute(JUnitBaseLaunchConfiguration.TESTNAME_ATTR, ""); //$NON-NLS-1$
// insert the program arguments
Vector argv= new Vector(10);
ExecutionArguments execArgs = new ExecutionArguments("", progArgs); //$NON-NLS-1$
String[] pa= execArgs.getProgramArgumentsArray();
for (int i= 0; i < pa.length; i++) {
argv.add(pa[i]);
}
argv.add("-version"); //$NON-NLS-1$
argv.add("3"); //$NON-NLS-1$
argv.add("-port"); //$NON-NLS-1$
argv.add(Integer.toString(port));
//argv("-debugging");
if (keepAlive(configuration) && runMode.equals(ILaunchManager.DEBUG_MODE))
argv.add(0, "-keepalive"); //$NON-NLS-1$
// a testname was specified just run the single test
if (testName.length() > 0) {
argv.add("-test"); //$NON-NLS-1$
argv.add(testTypes[0].getFullyQualifiedName()+":"+testName); //$NON-NLS-1$
} else if (testTypes.length > 1) {
String fileName= createTestNamesFile(testTypes);
argv.add("-testNameFile"); //$NON-NLS-1$
argv.add(fileName);
} else {
argv.add("-classNames"); //$NON-NLS-1$
for (int i= 0; i < testTypes.length; i++)
argv.add(testTypes[i].getFullyQualifiedName());
}
String[] args= new String[argv.size()];
argv.copyInto(args);
vmConfig.setProgramArguments(args);
return vmConfig;
}
private String createTestNamesFile(IType[] testTypes) throws CoreException {
try {
File file= File.createTempFile("testNames", ".txt"); //$NON-NLS-1$ //$NON-NLS-2$
file.deleteOnExit();
BufferedWriter bw= null;
try {
bw= new BufferedWriter(new FileWriter(file));
for (int i= 0; i < testTypes.length; i++) {
String testName= testTypes[i].getFullyQualifiedName();
bw.write(testName);
bw.newLine();
}
} finally {
if (bw != null) {
bw.close();
}
}
return file.getAbsolutePath();
} catch (IOException e) {
throw new CoreException(new Status(IStatus.ERROR, JUnitPlugin.PLUGIN_ID, IStatus.ERROR, "", e)); //$NON-NLS-1$
}
}
private String[] createClassPath(ILaunchConfiguration configuration) throws CoreException {
IPluginRegistry registry= Platform.getPluginRegistry();
IPluginDescriptor descriptor= registry.getPluginDescriptor("org.eclipse.jdt.junit.runtime"); //$NON-NLS-1$
URL runtimeURL= descriptor.getInstallURL();
URL url= JUnitPlugin.getDefault().getDescriptor().getInstallURL();
String[] cp= getClasspath(configuration);
String[] classPath= null;
try {
if (BootLoader.inDevelopmentMode()) {
// assumption is that the output folder is called bin!
List junitEntries= new ArrayList();
junitEntries.add(Platform.asLocalURL(new URL(url, "bin")).getFile()); //$NON-NLS-1$
junitEntries.add(Platform.asLocalURL(new URL(runtimeURL, "bin")).getFile()); //$NON-NLS-1$
try {
junitEntries.add(Platform.asLocalURL(new URL(url, "junitsupport.jar")).getFile()); //$NON-NLS-1$
} catch (IOException e) {
// fall through
}
try {
junitEntries.add(Platform.asLocalURL(new URL(runtimeURL, "junitruntime.jar")).getFile()); //$NON-NLS-1$
} catch (IOException e1) {
// fall through
}
classPath= new String[cp.length + junitEntries.size()];
Object[] jea= junitEntries.toArray();
System.arraycopy(cp, 0, classPath, 0, cp.length);
System.arraycopy(jea, 0, classPath, cp.length, jea.length);
} else {
classPath= new String[cp.length + 2];
System.arraycopy(cp, 0, classPath, 2, cp.length);
classPath[0]= Platform.asLocalURL(new URL(url, "junitsupport.jar")).getFile(); //$NON-NLS-1$
classPath[1]= Platform.asLocalURL(new URL(runtimeURL, "junitruntime.jar")).getFile(); //$NON-NLS-1$
}
} catch (IOException e) {
JUnitPlugin.log(e); // TODO abort run and inform user
}
return classPath;
}
}
|
53,477 |
Bug 53477 AnonymousClassDeclaration has wrong range
|
I200400226 public class K { class Inner { } void make() { new K(){}.new Inner(){/*x*/}; } } The AnonymousClassDeclaration whose implementation is marked by /*x*/ should have a range covering "{/*x*/}". Currently, getStartPosition() and getLength() return a range covering "{}.new Inner(){/*x*/}". (For Markus' memory: This makes NodeFinder return a wrong node, causing problems in ChangeSignatureRefactoring test A_testAll51_in)
|
verified fixed
|
cc475b8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-08T10:07:38Z | 2004-03-02T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
53,477 |
Bug 53477 AnonymousClassDeclaration has wrong range
|
I200400226 public class K { class Inner { } void make() { new K(){}.new Inner(){/*x*/}; } } The AnonymousClassDeclaration whose implementation is marked by /*x*/ should have a range covering "{/*x*/}". Currently, getStartPosition() and getLength() return a range covering "{}.new Inner(){/*x*/}". (For Markus' memory: This makes NodeFinder return a wrong node, causing problems in ChangeSignatureRefactoring test A_testAll51_in)
|
verified fixed
|
cc475b8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-08T10:07:38Z | 2004-03-02T09:33:20Z |
cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java
| |
53,839 |
Bug 53839 new search: remember the sort options
|
I20040302 the group-by capabilties and the buttons are great. So good that I would want the group-by setting to be remembered across sessions.
|
resolved fixed
|
149c64a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-08T14:42:19Z | 2004-03-05T09:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPlugin.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;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdapterManager;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IPluginDescriptor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.text.templates.ContextTypeRegistry;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.ui.texteditor.ConfigurationElementSorter;
import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants;
import org.eclipse.ui.texteditor.MarkerAnnotationPreferences;
import org.eclipse.jdt.core.IBufferFactory;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.core.DefaultWorkingCopyOwner;
import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations;
import org.eclipse.jdt.internal.corext.refactoring.base.Refactoring;
import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType;
import org.eclipse.jdt.internal.corext.template.java.JavaContextType;
import org.eclipse.jdt.internal.corext.template.java.JavaDocContextType;
import org.eclipse.jdt.internal.corext.util.AllTypesCache;
import org.eclipse.jdt.internal.ui.browsing.LogicalPackage;
import org.eclipse.jdt.internal.ui.javaeditor.ClassFileDocumentProvider;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider;
import org.eclipse.jdt.internal.ui.javaeditor.CustomBufferFactory;
import org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider;
import org.eclipse.jdt.internal.ui.javaeditor.WorkingCopyManager;
import org.eclipse.jdt.internal.ui.javaeditor.filebuffers.CompilationUnitDocumentProvider2;
import org.eclipse.jdt.internal.ui.javaeditor.filebuffers.CustomBufferFactory2;
import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferenceCache;
import org.eclipse.jdt.internal.ui.preferences.MockupPreferenceStore;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemMarkerManager;
/**
* Represents the java plugin. It provides a series of convenience methods such as
* access to the workbench, keeps track of elements shared by all editors and viewers
* of the plugin such as document providers and find-replace-dialogs.
*/
public class JavaPlugin extends AbstractUIPlugin {
/** temporarily */
public static final boolean USE_WORKING_COPY_OWNERS= true;
/** temporarily */
public static final boolean USE_FILE_BUFFERS= true;
private static JavaPlugin fgJavaPlugin;
private IWorkingCopyManager fWorkingCopyManager;
private IBufferFactory fBufferFactory;
private ICompilationUnitDocumentProvider fCompilationUnitDocumentProvider;
private ClassFileDocumentProvider fClassFileDocumentProvider;
private JavaTextTools fJavaTextTools;
private ProblemMarkerManager fProblemMarkerManager;
private ImageDescriptorRegistry fImageDescriptorRegistry;
private JavaElementAdapterFactory fJavaElementAdapterFactory;
private MarkerAdapterFactory fMarkerAdapterFactory;
private EditorInputAdapterFactory fEditorInputAdapterFactory;
private ResourceAdapterFactory fResourceAdapterFactory;
private LogicalPackageAdapterFactory fLogicalPackageAdapterFactory;
private MembersOrderPreferenceCache fMembersOrderPreferenceCache;
private IPropertyChangeListener fFontPropertyChangeListener;
/**
* Property change listener on this plugin's preference store.
*
* @since 3.0
*/
private IPropertyChangeListener fPropertyChangeListener;
private JavaEditorTextHoverDescriptor[] fJavaEditorTextHoverDescriptors;
/**
* Mockup preference store for firing events and registering listeners on project setting changes.
* FIXME: Temporary solution.
*
* @since 3.0
*/
private MockupPreferenceStore fMockupPreferenceStore;
/** The template context type registry. */
private static ContextTypeRegistry fgContextTypeRegistry;
public static JavaPlugin getDefault() {
return fgJavaPlugin;
}
public static IWorkspace getWorkspace() {
return ResourcesPlugin.getWorkspace();
}
public static IWorkbenchPage getActivePage() {
return getDefault().internalGetActivePage();
}
public static IWorkbenchWindow getActiveWorkbenchWindow() {
return getDefault().getWorkbench().getActiveWorkbenchWindow();
}
public static Shell getActiveWorkbenchShell() {
IWorkbenchWindow window= getActiveWorkbenchWindow();
if (window != null) {
return window.getShell();
}
return null;
}
/**
* Returns an array of all editors that have an unsaved content. If the identical content is
* presented in more than one editor, only one of those editor parts is part of the result.
*
* @return an array of all dirty editor parts.
*/
public static IEditorPart[] getDirtyEditors() {
Set inputs= new HashSet();
List result= new ArrayList(0);
IWorkbench workbench= 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];
IEditorInput input= ep.getEditorInput();
if (!inputs.contains(input)) {
inputs.add(input);
result.add(ep);
}
}
}
}
return (IEditorPart[])result.toArray(new IEditorPart[result.size()]);
}
/**
* Returns an array of all instanciated editors.
*/
public static IEditorPart[] getInstanciatedEditors() {
List result= new ArrayList(0);
IWorkbench workbench= getDefault().getWorkbench();
IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
for (int windowIndex= 0; windowIndex < windows.length; windowIndex++) {
IWorkbenchPage[] pages= windows[windowIndex].getPages();
for (int pageIndex= 0; pageIndex < pages.length; pageIndex++) {
IEditorReference[] references= pages[pageIndex].getEditorReferences();
for (int refIndex= 0; refIndex < references.length; refIndex++) {
IEditorPart editor= references[refIndex].getEditor(false);
if (editor != null)
result.add(editor);
}
}
}
return (IEditorPart[])result.toArray(new IEditorPart[result.size()]);
}
public static String getPluginId() {
return getDefault().getDescriptor().getUniqueIdentifier();
}
public static void log(IStatus status) {
getDefault().getLog().log(status);
}
public static void logErrorMessage(String message) {
log(new Status(IStatus.ERROR, getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null));
}
public static void logErrorStatus(String message, IStatus status) {
if (status == null) {
logErrorMessage(message);
return;
}
MultiStatus multi= new MultiStatus(getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null);
multi.add(status);
log(multi);
}
public static void log(Throwable e) {
log(new Status(IStatus.ERROR, getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, JavaUIMessages.getString("JavaPlugin.internal_error"), e)); //$NON-NLS-1$
}
public static boolean isDebug() {
return getDefault().isDebugging();
}
public static ImageDescriptorRegistry getImageDescriptorRegistry() {
return getDefault().internalGetImageDescriptorRegistry();
}
public JavaPlugin(IPluginDescriptor descriptor) {
super(descriptor);
fgJavaPlugin= this;
}
/* (non - Javadoc)
* Method declared in Plugin
*/
public void startup() throws CoreException {
super.startup();
registerAdapters();
if (USE_WORKING_COPY_OWNERS)
DefaultWorkingCopyOwner.PRIMARY.factory= getBufferFactory();
installPreferenceStoreBackwardsCompatibility();
AllTypesCache.initialize();
}
/**
* Installs backwards compatibility for the preference store.
*/
private void installPreferenceStoreBackwardsCompatibility() {
/*
* Installs backwards compatibility: propagate the Java editor font from a
* pre-2.1 plug-in to the Platform UI's preference store to preserve
* the Java editor font from a pre-2.1 workspace. This is done only
* once.
*/
String fontPropagatedKey= "fontPropagated"; //$NON-NLS-1$
if (getPreferenceStore().contains(JFaceResources.TEXT_FONT) && !getPreferenceStore().isDefault(JFaceResources.TEXT_FONT)) {
if (!getPreferenceStore().getBoolean(fontPropagatedKey))
PreferenceConverter.setValue(PlatformUI.getWorkbench().getPreferenceStore(), PreferenceConstants.EDITOR_TEXT_FONT, PreferenceConverter.getFontDataArray(getPreferenceStore(), JFaceResources.TEXT_FONT));
}
getPreferenceStore().setValue(fontPropagatedKey, true);
/*
* Backwards compatibility: set the Java editor font in this plug-in's
* preference store to let older versions access it. Since 2.1 the
* Java editor font is managed by the workbench font preference page.
*/
PreferenceConverter.putValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry().getFontData(PreferenceConstants.EDITOR_TEXT_FONT));
fFontPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (PreferenceConstants.EDITOR_TEXT_FONT.equals(event.getProperty()))
PreferenceConverter.putValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry().getFontData(PreferenceConstants.EDITOR_TEXT_FONT));
}
};
JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener);
/*
* Backwards compatibility: propagate the Java editor tab width from a
* pre-3.0 plug-in to the new preference key. This is done only once.
*/
final String oldTabWidthKey= PreferenceConstants.EDITOR_TAB_WIDTH;
final String newTabWidthKey= ExtendedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH;
String tabWidthPropagatedKey= "tabWidthPropagated"; //$NON-NLS-1$
if (getPreferenceStore().contains(oldTabWidthKey) && !getPreferenceStore().isDefault(oldTabWidthKey)) {
if (!getPreferenceStore().getBoolean(tabWidthPropagatedKey))
getPreferenceStore().setValue(newTabWidthKey, getPreferenceStore().getInt(oldTabWidthKey));
}
getPreferenceStore().setValue(tabWidthPropagatedKey, true);
/*
* Backwards compatibility: set the Java editor tab width in this plug-in's
* preference store with the old key to let older versions access it.
* Since 3.0 the tab width is managed by the extended texteditor and
* uses a new key.
*/
getPreferenceStore().putValue(oldTabWidthKey, getPreferenceStore().getString(newTabWidthKey));
fPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (newTabWidthKey.equals(event.getProperty()))
getPreferenceStore().putValue(oldTabWidthKey, getPreferenceStore().getString(newTabWidthKey));
}
};
getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
}
/**
* Uninstalls backwards compatibility for the preference store.
*/
private void uninstallPreferenceStoreBackwardsCompatibility() {
JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
}
/* (non - Javadoc)
* Method declared in AbstractUIPlugin
*/
protected ImageRegistry createImageRegistry() {
return JavaPluginImages.getImageRegistry();
}
/* (non - Javadoc)
* Method declared in Plugin
*/
public void shutdown() throws CoreException {
AllTypesCache.terminate();
if (fImageDescriptorRegistry != null)
fImageDescriptorRegistry.dispose();
unregisterAdapters();
super.shutdown();
if (fWorkingCopyManager != null) {
fWorkingCopyManager.shutdown();
fWorkingCopyManager= null;
}
if (fCompilationUnitDocumentProvider != null) {
fCompilationUnitDocumentProvider.shutdown();
fCompilationUnitDocumentProvider= null;
}
if (fJavaTextTools != null) {
fJavaTextTools.dispose();
fJavaTextTools= null;
}
JavaDocLocations.shutdownJavadocLocations();
uninstallPreferenceStoreBackwardsCompatibility();
Refactoring.getUndoManager().shutdown();
}
private IWorkbenchPage internalGetActivePage() {
IWorkbenchWindow window= getWorkbench().getActiveWorkbenchWindow();
if (window == null)
return null;
return getWorkbench().getActiveWorkbenchWindow().getActivePage();
}
public synchronized IBufferFactory getBufferFactory() {
if (fBufferFactory == null)
fBufferFactory= USE_FILE_BUFFERS ? (IBufferFactory) new CustomBufferFactory2() : (IBufferFactory) new CustomBufferFactory();
return fBufferFactory;
}
public synchronized ICompilationUnitDocumentProvider getCompilationUnitDocumentProvider() {
if (fCompilationUnitDocumentProvider == null)
fCompilationUnitDocumentProvider= USE_FILE_BUFFERS ? (ICompilationUnitDocumentProvider) new CompilationUnitDocumentProvider2() : (ICompilationUnitDocumentProvider) new CompilationUnitDocumentProvider();
return fCompilationUnitDocumentProvider;
}
public synchronized ClassFileDocumentProvider getClassFileDocumentProvider() {
if (fClassFileDocumentProvider == null)
fClassFileDocumentProvider= new ClassFileDocumentProvider();
return fClassFileDocumentProvider;
}
public synchronized IWorkingCopyManager getWorkingCopyManager() {
if (fWorkingCopyManager == null) {
ICompilationUnitDocumentProvider provider= getCompilationUnitDocumentProvider();
fWorkingCopyManager= new WorkingCopyManager(provider);
}
return fWorkingCopyManager;
}
/**
* Returns the mockup preference store for firing events and registering listeners on project setting changes. Temporary solution.
*/
public MockupPreferenceStore getMockupPreferenceStore() {
if (fMockupPreferenceStore == null)
fMockupPreferenceStore= new MockupPreferenceStore();
return fMockupPreferenceStore;
}
public synchronized ProblemMarkerManager getProblemMarkerManager() {
if (fProblemMarkerManager == null)
fProblemMarkerManager= new ProblemMarkerManager();
return fProblemMarkerManager;
}
public synchronized JavaTextTools getJavaTextTools() {
if (fJavaTextTools == null)
fJavaTextTools= new JavaTextTools(getPreferenceStore(), JavaCore.getPlugin().getPluginPreferences());
return fJavaTextTools;
}
public synchronized MembersOrderPreferenceCache getMemberOrderPreferenceCache() {
if (fMembersOrderPreferenceCache == null)
fMembersOrderPreferenceCache= new MembersOrderPreferenceCache();
return fMembersOrderPreferenceCache;
}
/**
* Returns all Java editor text hovers contributed to the workbench.
*
* @return an array of JavaEditorTextHoverDescriptor
* @since 2.1
*/
public JavaEditorTextHoverDescriptor[] getJavaEditorTextHoverDescriptors() {
if (fJavaEditorTextHoverDescriptors == null) {
fJavaEditorTextHoverDescriptors= JavaEditorTextHoverDescriptor.getContributedHovers();
ConfigurationElementSorter sorter= new ConfigurationElementSorter() {
/**
* {@inheritDoc}
*/
public IConfigurationElement getConfigurationElement(Object object) {
return ((JavaEditorTextHoverDescriptor)object).getConfigurationElement();
}
};
sorter.sort(fJavaEditorTextHoverDescriptors);
}
return fJavaEditorTextHoverDescriptors;
}
/**
* Resets the Java editor text hovers contributed to the workbench.
* <p>
* This will force a rebuild of the descriptors the next time
* a client asks for them.
* </p>
*
* @return an array of JavaEditorTextHoverDescriptor
* @since 2.1
*/
public void resetJavaEditorTextHoverDescriptors() {
fJavaEditorTextHoverDescriptors= null;
}
/**
* Creates the Java plugin standard groups in a context menu.
*/
public static void createStandardGroups(IMenuManager menu) {
if (!menu.isEmpty())
return;
menu.add(new Separator(IContextMenuConstants.GROUP_NEW));
menu.add(new GroupMarker(IContextMenuConstants.GROUP_GOTO));
menu.add(new Separator(IContextMenuConstants.GROUP_OPEN));
menu.add(new GroupMarker(IContextMenuConstants.GROUP_SHOW));
menu.add(new Separator(IContextMenuConstants.GROUP_REORGANIZE));
menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE));
menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH));
menu.add(new Separator(IContextMenuConstants.GROUP_BUILD));
menu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS));
menu.add(new Separator(IContextMenuConstants.GROUP_VIEWER_SETUP));
menu.add(new Separator(IContextMenuConstants.GROUP_PROPERTIES));
}
/**
* Returns the template context type registry for the java plugin.
*
* @return the template context type registry for the java plugin
*/
public static ContextTypeRegistry getTemplateContextRegistry() {
if (fgContextTypeRegistry == null) {
fgContextTypeRegistry= new ContextTypeRegistry();
fgContextTypeRegistry.addContextType(new JavaContextType());
fgContextTypeRegistry.addContextType(new JavaDocContextType());
CodeTemplateContextType.registerContextTypes(fgContextTypeRegistry);
}
return fgContextTypeRegistry;
}
/**
* @see AbstractUIPlugin#initializeDefaultPreferences
*/
protected void initializeDefaultPreferences(IPreferenceStore store) {
super.initializeDefaultPreferences(store);
MarkerAnnotationPreferences.initializeDefaultValues(store);
PreferenceConstants.initializeDefaultValues(store);
}
private synchronized ImageDescriptorRegistry internalGetImageDescriptorRegistry() {
if (fImageDescriptorRegistry == null)
fImageDescriptorRegistry= new ImageDescriptorRegistry();
return fImageDescriptorRegistry;
}
private void registerAdapters() {
fJavaElementAdapterFactory= new JavaElementAdapterFactory();
fMarkerAdapterFactory= new MarkerAdapterFactory();
fEditorInputAdapterFactory= new EditorInputAdapterFactory();
fResourceAdapterFactory= new ResourceAdapterFactory();
fLogicalPackageAdapterFactory= new LogicalPackageAdapterFactory();
IAdapterManager manager= Platform.getAdapterManager();
manager.registerAdapters(fJavaElementAdapterFactory, IJavaElement.class);
manager.registerAdapters(fMarkerAdapterFactory, IMarker.class);
manager.registerAdapters(fEditorInputAdapterFactory, IEditorInput.class);
manager.registerAdapters(fResourceAdapterFactory, IResource.class);
manager.registerAdapters(fLogicalPackageAdapterFactory, LogicalPackage.class);
}
private void unregisterAdapters() {
IAdapterManager manager= Platform.getAdapterManager();
manager.unregisterAdapters(fJavaElementAdapterFactory);
manager.unregisterAdapters(fMarkerAdapterFactory);
manager.unregisterAdapters(fEditorInputAdapterFactory);
manager.unregisterAdapters(fResourceAdapterFactory);
manager.unregisterAdapters(fLogicalPackageAdapterFactory);
}
}
|
53,839 |
Bug 53839 new search: remember the sort options
|
I20040302 the group-by capabilties and the buttons are great. So good that I would want the group-by setting to be remembered across sessions.
|
resolved fixed
|
149c64a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-08T14:42:19Z | 2004-03-05T09:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchResultPage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.search;
import java.util.HashMap;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.search.ui.IContextMenuConstants;
import org.eclipse.search.ui.ISearchResultViewPart;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.search.ui.text.AbstractTextSearchViewPage;
import org.eclipse.search.ui.text.Match;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
public class JavaSearchResultPage extends AbstractTextSearchViewPage {
private NewSearchViewActionGroup fActionGroup;
private JavaSearchContentProvider fContentProvider;
private int fCurrentSortOrder;
private SortAction fSortByNameAction;
private SortAction fSortByParentName;
private SortAction fSortByPathAction;
private GroupAction fGroupTypeAction;
private GroupAction fGroupFileAction;
private GroupAction fGroupPackageAction;
private GroupAction fGroupProjectAction;
private int fCurrentGrouping;
public JavaSearchResultPage() {
fSortByNameAction= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByName"), this, JavaSearchResultLabelProvider.SHOW_ELEMENT_CONTAINER); //$NON-NLS-1$
fSortByPathAction= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByPath"), this, JavaSearchResultLabelProvider.SHOW_PATH); //$NON-NLS-1$
fSortByParentName= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByParentName"), this, JavaSearchResultLabelProvider.SHOW_CONTAINER_ELEMENT); //$NON-NLS-1$
fCurrentSortOrder= JavaSearchResultLabelProvider.SHOW_ELEMENT_CONTAINER;
initGroupingActions();
}
private void initGroupingActions() {
fGroupProjectAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_project"), SearchMessages.getString("JavaSearchResultPage.groupby_project.tooltip"), this, LevelTreeContentProvider.LEVEL_PROJECT); //$NON-NLS-1$ //$NON-NLS-2$
JavaPluginImages.setLocalImageDescriptors(fGroupProjectAction, "prj_mode.gif"); //$NON-NLS-1$
fGroupPackageAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_package"), SearchMessages.getString("JavaSearchResultPage.groupby_package.tooltip"), this, LevelTreeContentProvider.LEVEL_PACKAGE); //$NON-NLS-1$ //$NON-NLS-2$
JavaPluginImages.setLocalImageDescriptors(fGroupPackageAction, "package_mode.gif"); //$NON-NLS-1$
fGroupFileAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_file"), SearchMessages.getString("JavaSearchResultPage.groupby_file.tooltip"), this, LevelTreeContentProvider.LEVEL_FILE); //$NON-NLS-1$ //$NON-NLS-2$
JavaPluginImages.setLocalImageDescriptors(fGroupFileAction, "file_mode.gif"); //$NON-NLS-1$
fGroupTypeAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_type"), SearchMessages.getString("JavaSearchResultPage.groupby_type.tooltip"), this, LevelTreeContentProvider.LEVEL_TYPE); //$NON-NLS-1$ //$NON-NLS-2$
JavaPluginImages.setLocalImageDescriptors(fGroupTypeAction, "class_obj.gif"); //$NON-NLS-1$
fCurrentGrouping= LevelTreeContentProvider.LEVEL_PACKAGE;
}
public void setViewPart(ISearchResultViewPart part) {
// TODO Auto-generated method stub
super.setViewPart(part);
fActionGroup= new NewSearchViewActionGroup(part);
}
public void showMatch(Match match, int offset, int length) throws PartInitException {
IEditorPart editor= null;
Object element= match.getElement();
if (element instanceof IJavaElement) {
IJavaElement javaElement= (IJavaElement) element;
try {
editor= EditorUtility.openInEditor(javaElement, false);
} catch (PartInitException e1) {
return;
} catch (JavaModelException e1) {
return;
}
} else if (element instanceof IFile) {
editor= IDE.openEditor(JavaPlugin.getActivePage(), (IFile) element, false);
}
if (!(editor instanceof ITextEditor)) {
if (element instanceof IFile) {
IFile file= (IFile) element;
showWithMarker(editor, file, offset, length);
}
} else {
ITextEditor textEditor= (ITextEditor) editor;
textEditor.selectAndReveal(offset, length);
}
}
private void showWithMarker(IEditorPart editor, IFile file, int offset, int length) throws PartInitException {
try {
IMarker marker= file.createMarker(SearchUI.SEARCH_MARKER);
HashMap attributes= new HashMap(4);
attributes.put(IMarker.CHAR_START, new Integer(offset));
attributes.put(IMarker.CHAR_END, new Integer(offset + length));
marker.setAttributes(attributes);
IDE.gotoMarker(editor, marker);
marker.delete();
} catch (CoreException e) {
throw new PartInitException(SearchMessages.getString("JavaSearchResultPage.error.marker"), e); //$NON-NLS-1$
}
}
protected void fillContextMenu(IMenuManager mgr) {
super.fillContextMenu(mgr);
addSortActions(mgr);
fActionGroup.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
fActionGroup.fillContextMenu(mgr);
}
private void addSortActions(IMenuManager mgr) {
if (!isFlatLayout())
return;
MenuManager sortMenu= new MenuManager(SearchMessages.getString("JavaSearchResultPage.sortBylabel")); //$NON-NLS-1$
sortMenu.add(fSortByNameAction);
sortMenu.add(fSortByPathAction);
sortMenu.add(fSortByParentName);
fSortByNameAction.setChecked(fCurrentSortOrder == fSortByNameAction.getSortOrder());
fSortByPathAction.setChecked(fCurrentSortOrder == fSortByPathAction.getSortOrder());
fSortByParentName.setChecked(fCurrentSortOrder == fSortByParentName.getSortOrder());
mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, sortMenu);
}
protected void fillToolbar(IToolBarManager tbm) {
super.fillToolbar(tbm);
if (!isFlatLayout())
addGroupActions(tbm);
}
private void addGroupActions(IToolBarManager mgr) {
mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, fGroupProjectAction);
mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, fGroupPackageAction);
mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, fGroupFileAction);
mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, fGroupTypeAction);
updateGroupingActions();
}
private void updateGroupingActions() {
fGroupProjectAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_PROJECT);
fGroupPackageAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_PACKAGE);
fGroupFileAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_FILE);
fGroupTypeAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_TYPE);
}
public void dispose() {
fActionGroup.dispose();
super.dispose();
}
protected void elementsChanged(Object[] objects) {
if (fContentProvider != null)
fContentProvider.elementsChanged(objects);
}
protected void clear() {
if (fContentProvider != null)
fContentProvider.clear();
}
protected void configureTableViewer(TableViewer viewer) {
viewer.setLabelProvider(new DelegatingLabelProvider(this, new JavaSearchResultLabelProvider()));
fContentProvider=new JavaSearchTableContentProvider(viewer);
viewer.setContentProvider(fContentProvider);
setSortOrder(fCurrentSortOrder);
}
protected void configureTreeViewer(AbstractTreeViewer viewer) {
viewer.setSorter(new ViewerSorter());
viewer.setLabelProvider(new PostfixLabelProvider(this));
fContentProvider= new LevelTreeContentProvider(viewer, fCurrentGrouping);
viewer.setContentProvider(fContentProvider);
}
void setSortOrder(int order) {
fCurrentSortOrder= order;
StructuredViewer viewer= getViewer();
DelegatingLabelProvider lpWrapper= (DelegatingLabelProvider) viewer.getLabelProvider();
((JavaSearchResultLabelProvider)lpWrapper.getLabelProvider()).setOrder(order);
if (order == JavaSearchResultLabelProvider.SHOW_ELEMENT_CONTAINER) {
viewer.setSorter(new NameSorter());
} else if (order == JavaSearchResultLabelProvider.SHOW_PATH) {
viewer.setSorter(new PathSorter());
} else
viewer.setSorter(new ParentSorter());
}
public void init(IPageSite site) {
super.init(site);
fActionGroup.fillActionBars(site.getActionBars());
}
/**
* Precondition here: the viewer must be shwing a tree with a LevelContentProvider.
* @param order
*/
void setGrouping(int grouping) {
fCurrentGrouping= grouping;
StructuredViewer viewer= getViewer();
LevelTreeContentProvider cp= (LevelTreeContentProvider) viewer.getContentProvider();
cp.setLevel(grouping);
updateGroupingActions();
}
protected StructuredViewer getViewer() {
// override so that it's visible in the package.
return super.getViewer();
}
}
|
50,460 |
Bug 50460 [templates] Template toarray not proposed
|
I200401130800 return new DelegatingValidationStateChange(to<code assist>); observe: poposals don't contain an entry for the toarray templete
|
verified fixed
|
5fde219
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-08T15:07:54Z | 2004-01-23T09:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/template/contentassist/TemplateEngine.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.template.contentassist;
import java.util.ArrayList;
import org.eclipse.swt.graphics.Point;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.link.LinkedEnvironment;
import org.eclipse.jface.text.templates.ContextType;
import org.eclipse.jface.text.templates.GlobalVariables;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.template.java.CompilationUnitContext;
import org.eclipse.jdt.internal.corext.template.java.CompilationUnitContextType;
import org.eclipse.jdt.internal.corext.template.java.Templates;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
public class TemplateEngine {
private static final String $_LINE_SELECTION= "${" + GlobalVariables.LineSelection.NAME + "}"; //$NON-NLS-1$ //$NON-NLS-2$
private static final String $_WORD_SELECTION= "${" + GlobalVariables.WordSelection.NAME + "}"; //$NON-NLS-1$ //$NON-NLS-2$
/** The context type. */
private ContextType fContextType;
/** The result proposals. */
private ArrayList fProposals= new ArrayList();
/**
* Creates the template engine for a particular context type.
* See <code>TemplateContext</code> for supported context types.
*/
public TemplateEngine(ContextType contextType) {
Assert.isNotNull(contextType);
fContextType= contextType;
}
/**
* Empties the collector.
*
* @param unit the compilation unit (may be <code>null</code>)
*/
public void reset() {
fProposals.clear();
}
/**
* Returns the array of matching templates.
*/
public TemplateProposal[] getResults() {
return (TemplateProposal[]) fProposals.toArray(new TemplateProposal[fProposals.size()]);
}
/**
* Inspects the context of the compilation unit around <code>completionPosition</code>
* and feeds the collector with proposals.
* @param viewer the text viewer
* @param completionPosition the context position in the document of the text viewer
* @param compilationUnit the compilation unit (may be <code>null</code>)
*/
public void complete(ITextViewer viewer, int completionPosition, ICompilationUnit compilationUnit)
throws JavaModelException
{
IDocument document= viewer.getDocument();
// prohibit recursion
if (LinkedEnvironment.hasEnvironment(document))
return;
if (!(fContextType instanceof CompilationUnitContextType))
return;
Point selection= viewer.getSelectedRange();
// remember selected text
String selectedText= null;
if (selection.y != 0) {
try {
selectedText= document.get(selection.x, selection.y);
} catch (BadLocationException e) {}
}
CompilationUnitContext context= ((CompilationUnitContextType) fContextType).createContext(document, completionPosition, selection.y, compilationUnit);
context.setVariable("selection", selectedText); //$NON-NLS-1$
int start= context.getStart();
int end= context.getEnd();
IRegion region= new Region(start, end - start);
Template[] templates= Templates.getInstance().getTemplates();
if (selection.y == 0) {
for (int i= 0; i != templates.length; i++)
if (context.canEvaluate(templates[i]))
fProposals.add(new TemplateProposal(templates[i], context, region, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_TEMPLATE)));
} else {
if (context.getKey().length() == 0)
context.setForceEvaluation(true);
boolean multipleLinesSelected= areMultipleLinesSelected(viewer);
for (int i= 0; i != templates.length; i++) {
Template template= templates[i];
if (context.canEvaluate(template) &&
template.getContextTypeName().equals(context.getContextType().getName()) &&
(!multipleLinesSelected && template.getPattern().indexOf($_WORD_SELECTION) != -1 || (multipleLinesSelected && template.getPattern().indexOf($_LINE_SELECTION) != -1)))
{
fProposals.add(new TemplateProposal(templates[i], context, region, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_TEMPLATE)));
}
}
}
}
/**
* Returns <code>true</code> if one line is completely selected or if multiple lines are selected.
* Being completely selected means that all characters except the new line characters are
* selected.
*
* @return <code>true</code> if one or multiple lines are selected
* @since 2.1
*/
private boolean areMultipleLinesSelected(ITextViewer viewer) {
if (viewer == null)
return false;
Point s= viewer.getSelectedRange();
if (s.y == 0)
return false;
try {
IDocument document= viewer.getDocument();
int startLine= document.getLineOfOffset(s.x);
int endLine= document.getLineOfOffset(s.x + s.y);
IRegion line= document.getLineInformation(startLine);
return startLine != endLine || (s.x == line.getOffset() && s.y == line.getLength());
} catch (BadLocationException x) {
return false;
}
}
}
|
53,350 |
Bug 53350 ClassCastException during refactoring
|
build i0226, winxp, j9sc20031212 I was moving a class definition from an interface to a class and I got an exception. Will attach log file. example structure: package api; public interface IFoo { public class Node { ... } public class INode { ... } } package internal; public class Foo { ... } I moved the declaration of "Node" to "Foo" via the context menu in the outline view. (Refactor -> Move)
|
resolved fixed
|
c03b9fe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-08T20:47:34Z | 2004-02-28T20:26:40Z |
org.eclipse.jdt.ui/core
| |
53,350 |
Bug 53350 ClassCastException during refactoring
|
build i0226, winxp, j9sc20031212 I was moving a class definition from an interface to a class and I got an exception. Will attach log file. example structure: package api; public interface IFoo { public class Node { ... } public class INode { ... } } package internal; public class Foo { ... } I moved the declaration of "Node" to "Foo" via the context menu in the outline view. (Refactor -> Move)
|
resolved fixed
|
c03b9fe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-08T20:47:34Z | 2004-02-28T20:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/MoveStaticMembersRefactoring.java
| |
54,094 |
Bug 54094 Assertion failed in auto indent strategy
|
(in HEAD) The snippet editor subclasses the JavaSourceViewerConfiguration, and inherits its autoindent strategy. This is causing the following exception, when I attempt to enter a carriage return at the end of a snippet editor. For example, my editor cantained the following text. Placing the cursor at the end and pressing 'Enter' results in the stack trace. Should we not use the indent strategy? or can JUI allow us to continue using it? java.util.Vector v = null; v.add("Sam"); for (int i = 0; i < 100; i++) { } v.toString() org.eclipse.jface.text.Assert$AssertionFailedException: Assertion failed: at org.eclipse.jface.text.Assert.isTrue(Assert.java:175) at org.eclipse.jface.text.Assert.isTrue(Assert.java:160) at org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner.scanForward (JavaHeuristicScanner.java:638) at org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner.findNonWhitespaceForwardI nAnyPartition(JavaHeuristicScanner.java:607) at org.eclipse.jdt.internal.ui.text.JavaIndenter.skipToPreviousListItemOrListStart (JavaIndenter.java:759) at org.eclipse.jdt.internal.ui.text.JavaIndenter.findReferencePosition (JavaIndenter.java:559) at org.eclipse.jdt.internal.ui.text.JavaIndenter.findReferencePosition (JavaIndenter.java:405) at org.eclipse.jdt.internal.ui.text.JavaIndenter.getReferenceIndentation (JavaIndenter.java:105) at org.eclipse.jdt.internal.ui.text.JavaIndenter.computeIndentation (JavaIndenter.java:138) at org.eclipse.jdt.internal.ui.text.JavaIndenter.computeIndentation (JavaIndenter.java:124) at org.eclipse.jdt.internal.ui.text.java.JavaAutoIndentStrategy.smartIndentAfterNe wLine(JavaAutoIndentStrategy.java:261) at org.eclipse.jdt.internal.ui.text.java.JavaAutoIndentStrategy.customizeDocumentC ommand(JavaAutoIndentStrategy.java:996) at org.eclipse.jface.text.TextViewer.customizeDocumentCommand (TextViewer.java:3132) at org.eclipse.jface.text.TextViewer.handleVerifyEvent (TextViewer.java:3160) at org.eclipse.jface.text.TextViewer$TextVerifyListener.verifyText (TextViewer.java:322) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:193) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:833) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:857) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:842) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:650) at org.eclipse.swt.custom.StyledText.modifyContent (StyledText.java:5951) at org.eclipse.swt.custom.StyledText.sendKeyEvent(StyledText.java:6935) at org.eclipse.swt.custom.StyledText.doContent(StyledText.java:2557) at org.eclipse.swt.custom.StyledText.handleKey(StyledText.java:5304) at org.eclipse.swt.custom.StyledText.handleKeyDown (StyledText.java:5327) at org.eclipse.swt.custom.StyledText$7.handleEvent (StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:833) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:857) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:842) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1716) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1712) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3037) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2940) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2880) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1376) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2031) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1509) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1480) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:257) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:48) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:260) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:173) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:106) 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:305) at org.eclipse.core.launcher.Main.run(Main.java:745) at org.eclipse.core.launcher.Main.main(Main.java:713)
|
resolved fixed
|
e9427f5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-09T09:41:10Z | 2004-03-08T21:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaIndenter.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Uses the {@link org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner}to
* get the indentation level for a certain position in a document.
*
* <p>
* An instance holds some internal position in the document and is therefore
* not threadsafe.
* </p>
*
* @since 3.0
*/
public class JavaIndenter {
/** The document being scanned. */
private IDocument fDocument;
/** The indentation accumulated by <code>findPreviousIndenationUnit</code>. */
private int fIndent;
/**
* The absolute (character-counted) indentation offset for special cases
* (method defs, array initializers)
*/
private int fAlign;
/** The stateful scanposition for the indentation methods. */
private int fPosition;
/** The previous position. */
private int fPreviousPos;
/** The most recent token. */
private int fToken;
/** The line of <code>fPosition</code>. */
private int fLine;
/**
* The scanner we will use to scan the document. It has to be installed
* on the same document as the one we get.
*/
private JavaHeuristicScanner fScanner;
/**
* Creates a new instance.
*
* @param document the document to scan
* @param scanner the {@link JavaHeuristicScanner} to be used for scanning
* the document. It must be installed on the same <code>IDocument</code>.
*/
public JavaIndenter(IDocument document, JavaHeuristicScanner scanner) {
Assert.isNotNull(document);
Assert.isNotNull(scanner);
fDocument= document;
fScanner= scanner;
}
/**
* Computes the indentation at the reference point of <code>position</code>.
*
* @param offset the offset in the document
* @return a String which reflects the indentation at the line in which the
* reference position to <code>offset</code> resides, or <code>null</code>
* if it cannot be determined
*/
public StringBuffer getReferenceIndentation(int offset) {
return getReferenceIndentation(offset, false);
}
/**
* Computes the indentation at the reference point of <code>position</code>.
*
* @param offset the offset in the document
* @param assumeOpeningBrace <code>true</code> if an opening brace should be assumed
* @return a String which reflects the indentation at the line in which the
* reference position to <code>offset</code> resides, or <code>null</code>
* if it cannot be determined
*/
private StringBuffer getReferenceIndentation(int offset, boolean assumeOpeningBrace) {
int unit;
if (assumeOpeningBrace)
unit= findReferencePosition(offset, Symbols.TokenLBRACE);
else
unit= findReferencePosition(offset, peekChar(offset));
// if we were unable to find anything, return null
if (unit == JavaHeuristicScanner.NOT_FOUND)
return null;
return getLeadingWhitespace(unit);
}
/**
* Computes the indentation at <code>offset</code>.
*
* @param offset the offset in the document
* @return a String which reflects the correct indentation for the line in
* which offset resides, or <code>null</code> if it cannot be
* determined
*/
public StringBuffer computeIndentation(int offset) {
return computeIndentation(offset, false);
}
/**
* Computes the indentation at <code>offset</code>.
*
* @param offset the offset in the document
* @param assumeOpeningBrace <code>true</code> if an opening brace should be assumed
* @return a String which reflects the correct indentation for the line in
* which offset resides, or <code>null</code> if it cannot be
* determined
*/
public StringBuffer computeIndentation(int offset, boolean assumeOpeningBrace) {
StringBuffer indent= getReferenceIndentation(offset, assumeOpeningBrace);
// handle special alignment
if (fAlign != JavaHeuristicScanner.NOT_FOUND) {
try {
// a special case has been detected.
IRegion line= fDocument.getLineInformationOfOffset(fAlign);
int lineOffset= line.getOffset();
return createIndent(lineOffset, fAlign);
} catch (BadLocationException e) {
return null;
}
}
if (indent == null)
return null;
// add additional indent
indent.append(createIndent(fIndent));
if (fIndent < 0)
unindent(indent);
return indent;
}
/**
* Returns the indentation of the line at <code>offset</code> as a
* <code>StringBuffer</code>. If the offset is not valid, the empty string
* is returned.
*
* @param offset the offset in the document
* @return the indentation (leading whitespace) of the line in which
* <code>offset</code> is located
*/
private StringBuffer getLeadingWhitespace(int offset) {
StringBuffer indent= new StringBuffer();
try {
IRegion line= fDocument.getLineInformationOfOffset(offset);
int lineOffset= line.getOffset();
int nonWS= fScanner.findNonWhitespaceForwardInAnyPartition(lineOffset, lineOffset + line.getLength());
indent.append(fDocument.get(lineOffset, nonWS - lineOffset));
return indent;
} catch (BadLocationException e) {
return indent;
}
}
/**
* Reduces indentation in <code>indent</code> by one indentation unit.
*
* @param indent the indentation to be modified
*/
private void unindent(StringBuffer indent) {
CharSequence oneIndent= createIndent();
int i= indent.lastIndexOf(oneIndent.toString()); //$NON-NLS-1$
if (i != -1) {
indent.delete(i, i + oneIndent.length());
}
}
/**
* Creates an indentation string of the length indent - start + 1,
* consisting of the content in <code>fDocument</code> in the range
* [start, indent), with every character replaced by a space except for
* tabs, which are kept as such.
*
* <p>Every run of the number of spaces that make up a tab are replaced
* by a tab character.</p>
*
* @return the indentation corresponding to the document content specified
* by <code>start</code> and <code>indent</code>
*/
private StringBuffer createIndent(int start, int indent) {
final int tabLen= prefTabLength();
StringBuffer ret= new StringBuffer();
try {
int spaces= 0;
while (start < indent) {
char ch= fDocument.getChar(start);
if (ch == '\t') {
ret.append('\t');
spaces= 0;
} else if (tabLen == -1){
ret.append(' ');
} else {
spaces++;
if (spaces == tabLen) {
ret.append('\t');
spaces= 0;
}
}
start++;
}
// remainder
if (spaces == tabLen)
ret.append('\t');
else
while (spaces-- > 0)
ret.append(' ');
} catch (BadLocationException e) {
}
return ret;
}
/**
* Creates a string that represents the given number of indents (can be
* spaces or tabs..)
*
* @param indent the requested indentation level.
*
* @return the indentation specified by <code>indent</code>
*/
private StringBuffer createIndent(int indent) {
StringBuffer oneIndent= createIndent();
StringBuffer ret= new StringBuffer();
while (indent-- > 0)
ret.append(oneIndent);
return ret;
}
/**
* Creates a string that represents one indent (can be
* spaces or tabs..)
*
* @return one indentation
*/
private StringBuffer createIndent() {
// get a sensible default when running without the infrastructure for testing
StringBuffer oneIndent= new StringBuffer();
JavaCore plugin= JavaCore.getJavaCore();
if (plugin == null) {
oneIndent.append('\t');
} else {
if (JavaCore.SPACE.equals(JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) {
int tabLen= Integer.parseInt(JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE));
for (int i= 0; i < tabLen; i++)
oneIndent.append(' ');
} else if (JavaCore.TAB.equals(JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR)))
oneIndent.append('\t');
else
oneIndent.append('\t'); // default
}
return oneIndent;
}
/**
* Returns the reference position regarding to indentation for <code>offset</code>,
* or <code>NOT_FOUND</code>. This method calls
* {@link #findReferencePosition(int, int) findReferencePosition(offset, nextChar)} where
* <code>nextChar</code> is the next character after <code>offset</code>.
*
* @param offset the offset for which the reference is computed
* @return the reference statement relative to which <code>offset</code>
* should be indented, or {@link JavaHeuristicScanner#NOT_FOUND}
*/
public int findReferencePosition(int offset) {
return findReferencePosition(offset, peekChar(offset));
}
/**
* Peeks the next char in the document that comes after <code>offset</code>
* on the same line as <code>offset</code>.
*
* @param offset the offset into document
* @return the token symbol of the next element, or TokenEOF if there is none
*/
private int peekChar(int offset) {
if (offset < fDocument.getLength()) {
try {
IRegion line= fDocument.getLineInformationOfOffset(offset);
int lineOffset= line.getOffset();
int next= fScanner.nextToken(offset, lineOffset + line.getLength());
return next;
} catch (BadLocationException e) {
}
}
return Symbols.TokenEOF;
}
/**
* Returns the reference position regarding to indentation for <code>position</code>,
* or <code>NOT_FOUND</code>.
*
* <p>If <code>peekNextChar</code> is <code>true</code>, the next token after
* <code>offset</code> is read and taken into account when computing the
* indentation. Currently, if the next token is the first token on the line
* (i.e. only preceded by whitespace), the following tokens are specially
* handled:
* <ul>
* <li><code>switch</code> labels are indented relative to the switch block</li>
* <li>opening curly braces are aligned correctly with the introducing code</li>
* <li>closing curly braces are aligned properly with the introducing code of
* the matching opening brace</li>
* <li>closing parenthesis' are aligned with their opening peer</li>
* <li>the <code>else</code> keyword is aligned with its <code>if</code>, anything
* else is aligned normally (i.e. with the base of any introducing statements).</li>
* <li>if there is no token on the same line after <code>offset</code>, the indentation
* is the same as for an <code>else</code> keyword</li>
* </ul>
*
* @param offset the offset for which the reference is computed
* @param nextToken the next token to assume in the document
* @return the reference statement relative to which <code>offset</code>
* should be indented, or {@link JavaHeuristicScanner#NOT_FOUND}
*/
public int findReferencePosition(int offset, int nextToken) {
boolean danglingElse= false;
boolean unindent= false;
boolean indent= false;
boolean matchBrace= false;
boolean matchParen= false;
boolean matchCase= false;
// account for unindenation characters already typed in, but after position
// if they are on a line by themselves, the indentation gets adjusted
// accordingly
//
// also account for a dangling else
if (offset < fDocument.getLength()) {
try {
IRegion line= fDocument.getLineInformationOfOffset(offset);
int lineOffset= line.getOffset();
int prevPos= Math.max(offset - 1, 0);
boolean isFirstTokenOnLine= fDocument.get(lineOffset, prevPos + 1 - lineOffset).trim().length() == 0;
int prevToken= fScanner.previousToken(prevPos, JavaHeuristicScanner.UNBOUND);
boolean bracelessBlockStart= fScanner.isBracelessBlockStart(prevPos, JavaHeuristicScanner.UNBOUND);
switch (nextToken) {
case Symbols.TokenEOF:
case Symbols.TokenELSE:
danglingElse= true;
break;
case Symbols.TokenCASE:
case Symbols.TokenDEFAULT:
if (isFirstTokenOnLine)
matchCase= true;
break;
case Symbols.TokenLBRACE: // for opening-brace-on-new-line style
if (bracelessBlockStart && !prefIndentBracesForBlocks())
unindent= true;
else if ((prevToken == Symbols.TokenCOLON || prevToken == Symbols.TokenEQUAL || prevToken == Symbols.TokenRBRACKET) && !prefIndentBracesForArrays())
unindent= true;
else if (!bracelessBlockStart && prefIndentBracesForMethods())
indent= true;
break;
case Symbols.TokenRBRACE: // closing braces get unindented
if (isFirstTokenOnLine)
matchBrace= true;
break;
case Symbols.TokenRPAREN:
if (isFirstTokenOnLine)
matchParen= true;
break;
}
} catch (BadLocationException e) {
}
} else {
// assume an else could come if we are at the end of file
danglingElse= true;
}
int ref= findReferencePosition(offset, danglingElse, matchBrace, matchParen, matchCase);
if (unindent)
fIndent--;
if (indent)
fIndent++;
return ref;
}
/**
* Returns the reference position regarding to indentation for <code>position</code>,
* or <code>NOT_FOUND</code>.<code>fIndent</code> will contain the
* relative indentation (in indentation units, not characters) after the
* call. If there is a special alignment (e.g. for a method declaration
* where parameters should be aligned), <code>fAlign</code> will contain
* the absolute position of the alignment reference in <code>fDocument</code>,
* otherwise <code>fAlign</code> is set to <code>JavaHeuristicScanner.NOT_FOUND</code>.
*
* @param offset the offset for which the reference is computed
* @param danglingElse whether a dangling else should be assumed at <code>position</code>
* @param matchBrace whether the position of the matching brace should be
* returned instead of doing code analysis
* @param matchParen whether the position of the matching parenthesis
* should be returned instead of doing code analysis
* @param matchCase whether the position of a switch statement reference
* should be returned (either an earlier case statement or the
* switch block brace)
* @return the reference statement relative to which <code>position</code>
* should be indented, or {@link JavaHeuristicScanner#NOT_FOUND}
*/
public int findReferencePosition(int offset, boolean danglingElse, boolean matchBrace, boolean matchParen, boolean matchCase) {
fIndent= 0; // the indentation modification
fAlign= JavaHeuristicScanner.NOT_FOUND;
fPosition= offset;
// forward cases
// an unindentation happens sometimes if the next token is special, namely on braces, parens and case labels
// align braces, but handle the case where we align with the method declaration start instead of
// the opening brace.
if (matchBrace) {
if (skipScope(Symbols.TokenLBRACE, Symbols.TokenRBRACE)) {
try {
// align with the opening brace that is on a line by its own
int lineOffset= fDocument.getLineOffset(fLine);
if (lineOffset <= fPosition && fDocument.get(lineOffset, fPosition - lineOffset).trim().length() == 0)
return fPosition;
} catch (BadLocationException e) {
// concurrent modification - walk default path
}
// if the opening brace is not on the start of the line, skip to the start
int pos= skipToStatementStart(true, true);
fIndent= 0; // indent is aligned with reference position
return pos;
} else {
// if we can't find the matching brace, the heuristic is to unindent
// by one against the normal position
int pos= findReferencePosition(offset, danglingElse, false, matchParen, matchCase);
fIndent--;
return pos;
}
}
// align parenthesis'
if (matchParen) {
if (skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN))
return fPosition;
else {
// if we can't find the matching paren, the heuristic is to unindent
// by one against the normal position
int pos= findReferencePosition(offset, danglingElse, matchBrace, false, matchCase);
fIndent--;
return pos;
}
}
// the only reliable way to get case labels aligned (due to many different styles of using braces in a block)
// is to go for another case statement, or the scope opening brace
if (matchCase) {
return matchCaseAlignment();
}
nextToken();
switch (fToken) {
case Symbols.TokenRBRACE:
// skip the block and fall through
// if we can't complete the scope, reset the scan position
int pos= fPosition;
if (!skipScope())
fPosition= pos;
case Symbols.TokenSEMICOLON:
// this is the 90% case: after a statement block
// the end of the previous statement / block previous.end
// search to the end of the statement / block before the previous; the token just after that is previous.start
return skipToStatementStart(danglingElse, false);
// scope introduction: special treat who special is
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
return handleScopeIntroduction(offset + 1);
case Symbols.TokenEOF:
// trap when hitting start of document
return 0;
case Symbols.TokenEQUAL:
// indent assignments
fIndent= prefAssignmentIndent();
return fPosition;
case Symbols.TokenCOLON:
// TODO handle ternary deep indentation
fIndent= prefCaseBlockIndent();
return fPosition;
case Symbols.TokenQUESTIONMARK:
if (prefTernaryDeepAlign()) {
setFirstElementAlignment(fPosition, offset + 1);
return fPosition;
} else {
fIndent= prefTernaryIndent();
return fPosition;
}
// indentation for blockless introducers:
case Symbols.TokenDO:
case Symbols.TokenWHILE:
case Symbols.TokenELSE:
fIndent= prefSimpleIndent();
return fPosition;
case Symbols.TokenRPAREN:
if (skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN)) {
int scope= fPosition;
nextToken();
if (fToken == Symbols.TokenIF || fToken == Symbols.TokenWHILE || fToken == Symbols.TokenFOR) {
fIndent= prefSimpleIndent();
return fPosition;
}
fPosition= scope;
if (looksLikeMethodDecl()) {
return skipToStatementStart(danglingElse, false);
}
}
fPosition= offset;
// else: fall through to default
case Symbols.TokenCOMMA:
// inside a list of some type
// easy if there is already a list item before with its own indentation - we just align
// if not: take the start of the list ( LPAREN, LBRACE, LBRACKET ) and either align or
// indent by list-indent
default:
// inside whatever we don't know about: similar to the list case:
// if we are inside a continued expression, then either align with a previous line that has indentation
// or indent from the expression start line (either a scope introducer or the start of the expr).
return skipToPreviousListItemOrListStart();
}
}
/**
* Skips to the start of a statement that ends at the current position.
*
* @param danglingElse whether to indent aligned with the last <code>if</code>
* @param isInBlock whether the current position is inside a block, which limits the search scope to the next scope introducer
* @return the reference offset of the start of the statement
*/
private int skipToStatementStart(boolean danglingElse, boolean isInBlock) {
while (true) {
nextToken();
if (isInBlock) {
switch (fToken) {
// exit on all block introducers
case Symbols.TokenIF:
case Symbols.TokenELSE:
case Symbols.TokenSYNCHRONIZED:
case Symbols.TokenCOLON:
case Symbols.TokenSTATIC:
case Symbols.TokenCATCH:
case Symbols.TokenDO:
case Symbols.TokenWHILE:
case Symbols.TokenFINALLY:
case Symbols.TokenFOR:
case Symbols.TokenTRY:
return fPosition;
case Symbols.TokenSWITCH:
fIndent= prefCaseIndent();
return fPosition;
}
}
switch (fToken) {
// scope introduction through: LPAREN, LBRACE, LBRACKET
// search stop on SEMICOLON, RBRACE, COLON, EOF
// -> the next token is the start of the statement (i.e. previousPos when backward scanning)
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
case Symbols.TokenSEMICOLON:
case Symbols.TokenEOF:
return fPreviousPos;
case Symbols.TokenCOLON:
int pos= fPreviousPos;
if (!isConditional())
return pos;
break;
case Symbols.TokenRBRACE:
// RBRACE is a little tricky: it can be the end of an array definition, but
// usually it is the end of a previous block
pos= fPreviousPos; // store state
if (skipScope() && looksLikeArrayInitializerIntro())
continue; // it's an array
else
return pos; // it's not - do as with all the above
// scopes: skip them
case Symbols.TokenRPAREN:
case Symbols.TokenRBRACKET:
pos= fPreviousPos;
if (skipScope())
break;
else
return pos;
// IF / ELSE: align the position after the conditional block with the if
// so we are ready for an else, except if danglingElse is false
// in order for this to work, we must skip an else to its if
case Symbols.TokenIF:
if (danglingElse)
return fPosition;
else
break;
case Symbols.TokenELSE:
// skip behind the next if, as we have that one covered
pos= fPosition;
if (skipNextIF())
break;
else
return pos;
case Symbols.TokenDO:
// align the WHILE position with its do
return fPosition;
case Symbols.TokenWHILE:
// this one is tricky: while can be the start of a while loop
// or the end of a do - while
pos= fPosition;
if (hasMatchingDo()) {
// continue searching from the DO on
break;
} else {
// continue searching from the WHILE on
fPosition= pos;
break;
}
default:
// keep searching
}
}
}
/**
* Returns true if the colon at the current position is part of a conditional
* (ternary) expression, false otherwise.
*
* @return true if the colon at the current position is part of a conditional
*/
private boolean isConditional() {
while (true) {
nextToken();
switch (fToken) {
// search for case, otherwise return true
case Symbols.TokenIDENT:
continue;
case Symbols.TokenCASE:
return false;
default:
return true;
}
}
}
/**
* Returns as a reference any previous <code>switch</code> labels (<code>case</code>
* or <code>default</code>) or the offset of the brace that scopes the switch
* statement. Sets <code>fIndent</code> to <code>prefCaseIndent</code> upon
* a match.
*
* @return the reference offset for a <code>switch</code> label
*/
private int matchCaseAlignment() {
while (true) {
nextToken();
switch (fToken) {
// invalid cases: another case label or an LBRACE must come before a case
// -> bail out with the current position
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACKET:
case Symbols.TokenEOF:
return fPosition;
case Symbols.TokenLBRACE:
// opening brace of switch statement
fIndent= prefCaseIndent();
return fPosition;
case Symbols.TokenCASE:
case Symbols.TokenDEFAULT:
// align with previous label
fIndent= 0;
return fPosition;
// scopes: skip them
case Symbols.TokenRPAREN:
case Symbols.TokenRBRACKET:
case Symbols.TokenRBRACE:
skipScope();
break;
default:
// keep searching
continue;
}
}
}
/**
* Returns the reference position for a list element. The algorithm
* tries to match any previous indentation on the same list. If there is none,
* the reference position returned is determined depending on the type of list:
* The indentation will either match the list scope introducer (e.g. for
* method declarations), so called deep indents, or simply increase the
* indentation by a number of standard indents. See also {@link #handleScopeIntroduction(int)}.
*
* @return the reference position for a list item: either a previous list item
* that has its own indentation, or the list introduction start.
*/
private int skipToPreviousListItemOrListStart() {
int startLine= fLine;
int startPosition= fPosition;
while (true) {
nextToken();
// if any line item comes with its own indentation, adapt to it
if (fLine < startLine) {
try {
int lineOffset= fDocument.getLineOffset(startLine);
fAlign= fScanner.findNonWhitespaceForwardInAnyPartition(lineOffset, startPosition + 1);
} catch (BadLocationException e) {
// ignore and return just the position
}
return startPosition;
}
switch (fToken) {
// scopes: skip them
case Symbols.TokenRPAREN:
case Symbols.TokenRBRACKET:
case Symbols.TokenRBRACE:
skipScope();
break;
// scope introduction: special treat who special is
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
return handleScopeIntroduction(startPosition + 1);
case Symbols.TokenSEMICOLON:
return fPosition;
case Symbols.TokenQUESTIONMARK:
if (prefTernaryDeepAlign()) {
setFirstElementAlignment(fPosition - 1, fPosition + 1);
return fPosition;
} else {
fIndent= prefTernaryIndent();
return fPosition;
}
case Symbols.TokenEOF:
return 0;
}
}
}
/**
* Skips a scope and positions the cursor (<code>fPosition</code>) on the
* token that opens the scope. Returns <code>true</code> if a matching peer
* could be found, <code>false</code> otherwise. The current token when calling
* must be one out of <code>Symbols.TokenRPAREN</code>, <code>Symbols.TokenRBRACE</code>,
* and <code>Symbols.TokenRBRACKET</code>.
*
* @return <code>true</code> if a matching peer was found, <code>false</code> otherwise
*/
private boolean skipScope() {
switch (fToken) {
case Symbols.TokenRPAREN:
return skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN);
case Symbols.TokenRBRACKET:
return skipScope(Symbols.TokenLBRACKET, Symbols.TokenRBRACKET);
case Symbols.TokenRBRACE:
return skipScope(Symbols.TokenLBRACE, Symbols.TokenRBRACE);
default:
Assert.isTrue(false);
return false;
}
}
/**
* Handles the introduction of a new scope. The current token must be one out
* of <code>Symbols.TokenLPAREN</code>, <code>Symbols.TokenLBRACE</code>,
* and <code>Symbols.TokenLBRACKET</code>. Returns as the reference position
* either the token introducing the scope or - if available - the first
* java token after that.
*
* <p>Depending on the type of scope introduction, the indentation will align
* (deep indenting) with the reference position (<code>fAlign</code> will be
* set to the reference position) or <code>fIndent</code> will be set to
* the number of indentation units.
* </p>
*
* @param bound the bound for the search for the first token after the scope
* introduction.
* @return
*/
private int handleScopeIntroduction(int bound) {
switch (fToken) {
// scope introduction: special treat who special is
case Symbols.TokenLPAREN:
int pos= fPosition; // store
// special: method declaration deep indentation
if (looksLikeMethodDecl()) {
if (prefMethodDeclDeepIndent())
return setFirstElementAlignment(pos, bound);
else {
fIndent= prefMethodDeclIndent();
return pos;
}
} else {
fPosition= pos;
if (looksLikeMethodCall()) {
if (prefMethodCallDeepIndent())
return setFirstElementAlignment(pos, bound);
else {
fIndent= prefMethodCallIndent();
return pos;
}
} else if (prefParenthesisDeepIndent())
return setFirstElementAlignment(pos, bound);
}
// normal: return the parenthesis as reference
fIndent= prefParenthesisIndent();
return pos;
case Symbols.TokenLBRACE:
pos= fPosition; // store
// special: array initializer
if (looksLikeArrayInitializerIntro())
if (prefArrayDeepIndent())
return setFirstElementAlignment(pos, bound);
else
fIndent= prefArrayIndent();
else
fIndent= prefBlockIndent();
// normal: skip to the statement start before the scope introducer
// opening braces are often on differently ending indents than e.g. a method definition
fPosition= pos; // restore
return skipToStatementStart(true, true); // set to true to match the first if
case Symbols.TokenLBRACKET:
pos= fPosition; // store
// special: method declaration deep indentation
if (prefArrayDimensionsDeepIndent()) {
return setFirstElementAlignment(pos, bound);
}
// normal: return the bracket as reference
fIndent= prefBracketIndent();
return pos; // restore
default:
Assert.isTrue(false);
return -1; // dummy
}
}
/**
* Sets the deep indent offset (<code>fAlign</code>) to either the offset
* right after <code>scopeIntroducerOffset</code> or - if available - the
* first Java token after <code>scopeIntroducerOffset</code>, but before
* <code>bound</code>.
*
* @param scopeIntroducerOffset the offset of the scope introducer
* @param bound the bound for the search for another element
* @return the reference position
*/
private int setFirstElementAlignment(int scopeIntroducerOffset, int bound) {
int firstPossible= scopeIntroducerOffset + 1; // align with the first position after the scope intro
fAlign= fScanner.findNonWhitespaceForwardInAnyPartition(firstPossible, bound);
if (fAlign == JavaHeuristicScanner.NOT_FOUND)
fAlign= firstPossible;
return fAlign;
}
/**
* Returns <code>true</code> if the next token received after calling
* <code>nextToken</code> is either an equal sign or an array designator ('[]').
*
* @return <code>true</code> if the next elements look like the start of an array definition
*/
private boolean looksLikeArrayInitializerIntro() {
nextToken();
if (fToken == Symbols.TokenEQUAL || skipBrackets()) {
return true;
}
return false;
}
/**
* Skips over the next <code>if</code> keyword. The current token when calling
* this method must be an <code>else</code> keyword. Returns <code>true</code>
* if a matching <code>if</code> could be found, <code>false</code> otherwise.
* The cursor (<code>fPosition</code>) is set to the offset of the <code>if</code>
* token.
*
* @return <code>true</code> if a matching <code>if</code> token was found, <code>false</code> otherwise
*/
private boolean skipNextIF() {
Assert.isTrue(fToken == Symbols.TokenELSE);
while (true) {
nextToken();
switch (fToken) {
// scopes: skip them
case Symbols.TokenRPAREN:
case Symbols.TokenRBRACKET:
case Symbols.TokenRBRACE:
skipScope();
break;
case Symbols.TokenIF:
// found it, return
return true;
case Symbols.TokenELSE:
// recursively skip else-if blocks
skipNextIF();
break;
// shortcut scope starts
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
case Symbols.TokenEOF:
return false;
}
}
}
/**
* while(condition); is ambiguous when parsed backwardly, as it is a valid
* statement by its own, so we have to check whether there is a matching
* do. A <code>do</code> can either be separated from the while by a
* block, or by a single statement, which limits our search distance.
*
* @return <code>true</code> if the <code>while</code> currently in
* <code>fToken</code> has a matching <code>do</code>.
*/
private boolean hasMatchingDo() {
Assert.isTrue(fToken == Symbols.TokenWHILE);
nextToken();
switch (fToken) {
case Symbols.TokenRBRACE:
skipScope(); // and fall thru
case Symbols.TokenSEMICOLON:
skipToStatementStart(false, false);
return fToken == Symbols.TokenDO;
}
return false;
}
/**
* Skips brackets if the current token is a RBRACKET. There can be nothing
* but whitespace in between, this is only to be used for <code>[]</code> elements.
*
* @return <code>true</code> if a <code>[]</code> could be scanned, the
* current token is left at the LBRACKET.
*/
private boolean skipBrackets() {
if (fToken == Symbols.TokenRBRACKET) {
nextToken();
if (fToken == Symbols.TokenLBRACKET) {
return true;
}
}
return false;
}
/**
* Reads the next token in backward direction from the heuristic scanner
* and sets the fields <code>fToken, fPreviousPosition</code> and <code>fPosition</code>
* accordingly.
*/
private void nextToken() {
nextToken(fPosition);
}
/**
* Reads the next token in backward direction of <code>start</code> from
* the heuristic scanner and sets the fields <code>fToken, fPreviousPosition</code>
* and <code>fPosition</code> accordingly.
*/
private void nextToken(int start) {
fToken= fScanner.previousToken(start - 1, JavaHeuristicScanner.UNBOUND);
fPreviousPos= start;
fPosition= fScanner.getPosition() + 1;
try {
fLine= fDocument.getLineOfOffset(fPosition);
} catch (BadLocationException e) {
fLine= -1;
}
}
/**
* Returns <code>true</code> if the current tokens look like a method
* declaration header (i.e. only the return type and method name). The
* heuristic calls <code>nextToken</code> and expects an identifier
* (method name) and a type declaration (an identifier with optional
* brackets) which also covers the visibility modifier of constructors; it
* does not recognize package visible constructors.
*
* @return <code>true</code> if the current position looks like a method
* declaration header.
*/
private boolean looksLikeMethodDecl() {
/*
* TODO This heuristic does not recognize package private constructors
* since those do have neither type nor visibility keywords.
* One option would be to go over the parameter list, but that might
* be empty as well - hard to do without an AST...
*/
nextToken();
if (fToken == Symbols.TokenIDENT) { // method name
do nextToken();
while (skipBrackets()); // optional brackets for array valued return types
return fToken == Symbols.TokenIDENT; // type name
}
return false;
}
/**
* Returns <code>true</code> if the current tokens look like a method
* call header (i.e. an identifier as opposed to a keyword taking parenthesized
* parameters such as <code>if</code>).
* <p>The heuristic calls <code>nextToken</code> and expects an identifier
* (method name).
*
* @return <code>true</code> if the current position looks like a method call
* header.
*/
private boolean looksLikeMethodCall() {
nextToken();
return fToken == Symbols.TokenIDENT; // method name
}
/**
* Scans tokens for the matching opening peer. The internal cursor
* (<code>fPosition</code>) is set to the offset of the opening peer if found.
*
* @return <code>true</code> if a matching token was found, <code>false</code>
* otherwise
*/
private boolean skipScope(int openToken, int closeToken) {
int depth= 1;
while (true) {
nextToken();
if (fToken == closeToken) {
depth++;
} else if (fToken == openToken) {
depth--;
if (depth == 0)
return true;
} else if (fToken == Symbols.TokenEOF) {
return false;
}
}
}
// TODO adjust once there are per-project settings
private int prefTabLength() {
int tabLen;
JavaCore core= JavaCore.getJavaCore();
JavaPlugin plugin= JavaPlugin.getDefault();
if (core != null && plugin != null)
if (JavaCore.SPACE.equals(JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR)))
// if the formatter uses chars to mark indentation, then don't substitute any chars
tabLen= -1; // results in no tabs being substituted for space runs
else
// if the formatter uses tabs to mark indentations, use the visual setting from the editor
// to get nicely aligned indentations
tabLen= plugin.getPreferenceStore().getInt(ExtendedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH);
else
tabLen= 4; // sensible default for testing
return tabLen;
}
private boolean prefArrayDimensionsDeepIndent() {
return true; // sensible default
}
private int prefArrayIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER);
try {
if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE)
return 1;
} catch (IllegalArgumentException e) {
// ignore and return default
}
}
return prefContinuationIndent(); // default
}
private boolean prefArrayDeepIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER);
try {
return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN;
} catch (IllegalArgumentException e) {
// ignore and return default
}
}
return true;
}
private boolean prefTernaryDeepAlign() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION);
try {
return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN;
} catch (IllegalArgumentException e) {
// ignore and return default
}
}
return false;
}
private int prefTernaryIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION);
try {
if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE)
return 1;
else
return prefContinuationIndent();
} catch (IllegalArgumentException e) {
// ignore and return default
}
}
return prefContinuationIndent();
}
private int prefCaseIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
if (DefaultCodeFormatterConstants.TRUE.equals(JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH)))
return prefBlockIndent();
else
return 0;
}
return 0; // sun standard
}
private int prefAssignmentIndent() {
return prefBlockIndent();
}
private int prefCaseBlockIndent() {
if (true)
return prefBlockIndent();
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
if (DefaultCodeFormatterConstants.TRUE.equals(JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES)))
return prefBlockIndent();
else
return 0;
}
return prefBlockIndent(); // sun standard
}
private int prefSimpleIndent() {
return prefBlockIndent();
}
private int prefBracketIndent() {
return prefBlockIndent();
}
private boolean prefMethodDeclDeepIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
try {
return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN;
} catch (IllegalArgumentException e) {
// ignore and return default
}
}
return true;
}
private int prefMethodDeclIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
try {
if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE)
return 1;
else
return prefContinuationIndent();
} catch (IllegalArgumentException e) {
// ignore and return default
}
}
return 1;
}
private boolean prefMethodCallDeepIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
try {
return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN;
} catch (IllegalArgumentException e) {
// ignore and return default
}
}
return false; // sensible default
}
private int prefMethodCallIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
try {
if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE)
return 1;
else
return prefContinuationIndent();
} catch (IllegalArgumentException e) {
// ignore and return default
}
}
return 1; // sensible default
}
private boolean prefParenthesisDeepIndent() {
if (true) // don't do parenthesis deep indentation
return false;
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION);
try {
return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN;
} catch (IllegalArgumentException e) {
// ignore and return default
}
}
return false; // sensible default
}
private int prefParenthesisIndent() {
return prefContinuationIndent();
}
private int prefBlockIndent() {
return 1; // sensible default
}
private boolean prefIndentBracesForBlocks() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK);
return option.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED);
}
return false; // sensible default
}
private boolean prefIndentBracesForArrays() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER);
return option.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED);
}
return false; // sensible default
}
private boolean prefIndentBracesForMethods() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION);
return option.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED);
}
return false; // sensible default
}
private int prefContinuationIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION);
try {
return Integer.parseInt(option);
} catch (NumberFormatException e) {
// ignore and return default
}
}
return 2; // sensible default
}
}
|
54,096 |
Bug 54096 deleting elements in the outline asks for confirmation twice
|
i20040304 Deleting Java outline elements is behaving in a weird way in this build. I have a Java source open. I select some methods in the Outline view, and press <Del>. A dialog opens saying "Are you sure you want to delete these <#elems> elements?". I say "Yes", but the dialog opens for the second time. And while the dialog is showing up, the elements are removed from the outline. Of course, confirm the second deletion fails because the elemnts are not there anymore.
|
resolved fixed
|
e198917
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-09T10:07:18Z | 2004-03-08T23:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/JavaBrowsingPart.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.browsing;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.eclipse.search.ui.ISearchResultView;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
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.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.IAction;
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.MenuManager;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.*;
import org.eclipse.ui.*;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.part.IShowInSource;
import org.eclipse.ui.part.ResourceTransfer;
import org.eclipse.ui.part.ShowInContext;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageDeclaration;
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.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.ui.actions.BuildActionGroup;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.CustomFiltersActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.ImportActionGroup;
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.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup;
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.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDropAdapter;
import org.eclipse.jdt.internal.ui.search.SearchUtil;
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.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup;
abstract class JavaBrowsingPart extends ViewPart implements IMenuListener, ISelectionListener, IViewPartInputProvider {
private static final String TAG_SELECTED_ELEMENTS= "selectedElements"; //$NON-NLS-1$
private static final String TAG_SELECTED_ELEMENT= "selectedElement"; //$NON-NLS-1$
private static final String TAG_LOGICAL_PACKAGE= "logicalPackage"; //$NON-NLS-1$
private static final String TAG_SELECTED_ELEMENT_PATH= "selectedElementPath"; //$NON-NLS-1$
private JavaUILabelProvider fLabelProvider;
private ILabelProvider fTitleProvider;
private StructuredViewer fViewer;
private IMemento fMemento;
private JavaElementTypeComparator fTypeComparator;
// Actions
private WorkingSetFilterActionGroup fWorkingSetFilterActionGroup;
private boolean fHasWorkingSetFilter= true;
private boolean fHasCustomFilter= true;
private OpenEditorActionGroup fOpenEditorGroup;
private CCPActionGroup fCCPActionGroup;
private BuildActionGroup fBuildActionGroup;
private ToggleLinkingAction fToggleLinkingAction;
protected CompositeActionGroup fActionGroups;
// Filters
private CustomFiltersActionGroup fCustomFiltersActionGroup;
protected IWorkbenchPart fPreviousSelectionProvider;
protected Object fPreviousSelectedElement;
// Linking
private boolean fLinkingEnabled;
/*
* Ensure selection changed events being processed only if
* initiated by user interaction with this part.
*/
private boolean fProcessSelectionEvents= true;
private IPartListener2 fPartListener= new IPartListener2() {
public void partActivated(IWorkbenchPartReference ref) {
setSelectionFromEditor(ref);
}
public void partBroughtToTop(IWorkbenchPartReference ref) {
setSelectionFromEditor(ref);
}
public void partInputChanged(IWorkbenchPartReference ref) {
setSelectionFromEditor(ref);
}
public void partClosed(IWorkbenchPartReference ref) {
}
public void partDeactivated(IWorkbenchPartReference ref) {
}
public void partOpened(IWorkbenchPartReference ref) {
}
public void partVisible(IWorkbenchPartReference ref) {
if (ref != null && ref.getId() == getSite().getId()){
fProcessSelectionEvents= true;
IWorkbenchPage page= getSite().getWorkbenchWindow().getActivePage();
if (page != null)
selectionChanged(page.getActivePart(), page.getSelection());
}
}
public void partHidden(IWorkbenchPartReference ref) {
if (ref != null && ref.getId() == getSite().getId())
fProcessSelectionEvents= false;
}
};
public JavaBrowsingPart() {
super();
initLinkingEnabled();
}
/*
* Implements method from IViewPart.
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
/*
* Implements method from IViewPart.
*/
public void saveState(IMemento memento) {
if (fViewer == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
if (fHasWorkingSetFilter)
fWorkingSetFilterActionGroup.saveState(memento);
if (fHasCustomFilter)
fCustomFiltersActionGroup.saveState(memento);
saveSelectionState(memento);
saveLinkingEnabled(memento);
}
private void saveLinkingEnabled(IMemento memento) {
memento.putInteger(getLinkToEditorKey(), fLinkingEnabled ? 1 : 0);
}
private void saveSelectionState(IMemento memento) {
Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray();
if (elements.length > 0) {
IMemento selectionMem= memento.createChild(TAG_SELECTED_ELEMENTS);
for (int i= 0; i < elements.length; i++) {
IMemento elementMem= selectionMem.createChild(TAG_SELECTED_ELEMENT);
Object o= elements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_SELECTED_ELEMENT_PATH, ((IJavaElement) elements[i]).getHandleIdentifier());
else if (o instanceof LogicalPackage) {
IPackageFragment[] packages=((LogicalPackage)o).getFragments();
for (int j= 0; j < packages.length; j++) {
IMemento packageMem= elementMem.createChild(TAG_LOGICAL_PACKAGE);
packageMem.putString(TAG_SELECTED_ELEMENT_PATH, packages[j].getHandleIdentifier());
}
}
}
}
}
protected void restoreState(IMemento memento) {
if (fHasWorkingSetFilter)
fWorkingSetFilterActionGroup.restoreState(memento);
if (fHasCustomFilter)
fCustomFiltersActionGroup.restoreState(memento);
if (fHasCustomFilter || fHasWorkingSetFilter) {
fViewer.getControl().setRedraw(false);
fViewer.refresh();
fViewer.getControl().setRedraw(true);
}
}
private ISelection restoreSelectionState(IMemento memento) {
if (memento == null)
return null;
IMemento childMem;
childMem= memento.getChild(TAG_SELECTED_ELEMENTS);
if (childMem != null) {
ArrayList list= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_SELECTED_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
String javaElementHandle= elementMem[i].getString(TAG_SELECTED_ELEMENT_PATH);
if (javaElementHandle == null) {
// logical package
IMemento[] packagesMem= elementMem[i].getChildren(TAG_LOGICAL_PACKAGE);
LogicalPackage lp= null;
for (int j= 0; j < packagesMem.length; j++) {
javaElementHandle= packagesMem[j].getString(TAG_SELECTED_ELEMENT_PATH);
Object pack= (IPackageFragment)JavaCore.create(javaElementHandle);
if (pack instanceof IPackageFragment && ((IPackageFragment)pack).exists()) {
if (lp == null)
lp= new LogicalPackage((IPackageFragment)pack);
else
lp.add((IPackageFragment)pack);
}
}
if (lp != null)
list.add(lp);
} else {
IJavaElement element= JavaCore.create(javaElementHandle);
if (element != null && element.exists())
list.add(element);
}
}
return new StructuredSelection(list);
}
return null;
}
private void restoreLinkingEnabled(IMemento memento) {
Integer val= memento.getInteger(getLinkToEditorKey());
if (val != null) {
fLinkingEnabled= val.intValue() != 0;
}
}
/**
* Creates the search list inner viewer.
*/
public void createPartControl(Composite parent) {
Assert.isTrue(fViewer == null);
fTypeComparator= new JavaElementTypeComparator();
// Setup viewer
fViewer= createViewer(parent);
initDragAndDrop();
fLabelProvider= createLabelProvider();
fViewer.setLabelProvider(createDecoratingLabelProvider(fLabelProvider));
fViewer.setSorter(createJavaElementSorter());
fViewer.setUseHashlookup(true);
fTitleProvider= createTitleProvider();
createContextMenu();
getSite().setSelectionProvider(fViewer);
if (fMemento != null) { // initialize linking state before creating the actions
restoreLinkingEnabled(fMemento);
}
createActions(); // call before registering for selection changes
addKeyListener();
if (fMemento != null)
restoreState(fMemento);
getSite().setSelectionProvider(fViewer);
// Status line
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fViewer.addSelectionChangedListener(createStatusBarUpdater(slManager));
hookViewerListeners();
// Filters
addFilters();
// Initialize viewer input
fViewer.setContentProvider(createContentProvider());
setInitialInput();
// Initialize selecton
setInitialSelection();
fMemento= null;
// Listen to page changes
getViewSite().getPage().addPostSelectionListener(this);
getViewSite().getPage().addPartListener(fPartListener);
fillActionBars(getViewSite().getActionBars());
setHelp();
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key == IShowInSource.class) {
return getShowInSource();
}
return super.getAdapter(key);
}
/**
* Returns the <code>IShowInSource</code> for this view.
*/
protected IShowInSource getShowInSource() {
return new IShowInSource() {
public ShowInContext getShowInContext() {
return new ShowInContext(
null,
getSite().getSelectionProvider().getSelection());
}
};
}
protected DecoratingLabelProvider createDecoratingLabelProvider(JavaUILabelProvider provider) {
// XXX: Work in progress for problem decorator being a workbench decorator//
// return new ExcludingDecoratingLabelProvider(provider, decorationMgr, "org.eclipse.jdt.ui.problem.decorator"); //$NON-NLS-1$
return new DecoratingJavaLabelProvider(provider);
}
protected JavaElementSorter createJavaElementSorter() {
return new JavaElementSorter();
}
protected StatusBarUpdater createStatusBarUpdater(IStatusLineManager slManager) {
return new StatusBarUpdater(slManager);
}
protected void createContextMenu() {
MenuManager menuManager= new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(this);
Menu contextMenu= menuManager.createContextMenu(fViewer.getControl());
fViewer.getControl().setMenu(contextMenu);
getSite().registerContextMenu(menuManager, fViewer);
}
protected void initDragAndDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
// drop
Transfer[] dropTransfers= new Transfer[] {
LocalSelectionTransfer.getInstance()
};
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fViewer)
};
fViewer.addDropSupport(ops | DND.DROP_DEFAULT, dropTransfers, new DelegatingDropAdapter(dropListeners));
// Drag
Transfer[] dragTransfers= new Transfer[] {
LocalSelectionTransfer.getInstance(),
ResourceTransfer.getInstance()};
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fViewer),
new ResourceTransferDragAdapter(fViewer)
};
fViewer.addDragSupport(ops, dragTransfers, new JdtViewerDragAdapter(fViewer, dragListeners));
}
protected void fillActionBars(IActionBars actionBars) {
IToolBarManager toolBar= actionBars.getToolBarManager();
fillToolBar(toolBar);
if (fHasWorkingSetFilter)
fWorkingSetFilterActionGroup.fillActionBars(getViewSite().getActionBars());
actionBars.updateActionBars();
fActionGroups.fillActionBars(actionBars);
if (fHasCustomFilter)
fCustomFiltersActionGroup.fillActionBars(actionBars);
IMenuManager menu= actionBars.getMenuManager();
menu.add(fToggleLinkingAction);
}
//---- IWorkbenchPart ------------------------------------------------------
public void setFocus() {
fViewer.getControl().setFocus();
}
public void dispose() {
if (fViewer != null) {
getViewSite().getPage().removePostSelectionListener(this);
getViewSite().getPage().removePartListener(fPartListener);
fViewer= null;
}
if (fActionGroups != null)
fActionGroups.dispose();
if (fWorkingSetFilterActionGroup != null) {
fWorkingSetFilterActionGroup.dispose();
}
super.dispose();
}
/**
* Adds the KeyListener
*/
protected void addKeyListener() {
fViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
handleKeyReleased(event);
}
});
}
protected void handleKeyReleased(KeyEvent event) {
if (event.stateMask != 0)
return;
int key= event.keyCode;
IAction action;
if (key == SWT.F5) {
action= fBuildActionGroup.getRefreshAction();
if (action.isEnabled())
action.run();
} if (event.character == SWT.DEL) {
action= fCCPActionGroup.getDeleteAction();
if (action.isEnabled())
action.run();
}
}
//---- Adding Action to Toolbar -------------------------------------------
protected void fillToolBar(IToolBarManager tbm) {
}
/**
* 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);
IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection();
int size= selection.size();
Object element= selection.getFirstElement();
if (size == 1)
addOpenNewWindowAction(menu, element);
fActionGroups.setContext(new ActionContext(selection));
fActionGroups.fillContextMenu(menu);
fActionGroups.setContext(null);
}
private void addOpenNewWindowAction(IMenuManager menu, Object element) {
if (element instanceof IJavaElement) {
element= ((IJavaElement)element).getResource();
}
if (!(element instanceof IContainer))
return;
menu.appendToGroup(
IContextMenuConstants.GROUP_OPEN,
new PatchedOpenInNewWindowAction(getSite().getWorkbenchWindow(), (IContainer)element));
}
protected void createActions() {
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
new NewWizardsActionGroup(this.getSite()),
fOpenEditorGroup= new OpenEditorActionGroup(this),
new OpenViewActionGroup(this),
fCCPActionGroup= new CCPActionGroup(this),
new GenerateActionGroup(this),
new RefactorActionGroup(this),
new ImportActionGroup(this),
fBuildActionGroup= new BuildActionGroup(this),
new JavaSearchActionGroup(this)});
if (fHasWorkingSetFilter) {
String viewId= getConfigurationElement().getAttribute("id"); //$NON-NLS-1$
Assert.isNotNull(viewId);
IPropertyChangeListener workingSetListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
doWorkingSetChanged(event);
}
};
fWorkingSetFilterActionGroup= new WorkingSetFilterActionGroup(viewId, getShell(), workingSetListener);
fViewer.addFilter(fWorkingSetFilterActionGroup.getWorkingSetFilter());
}
// Custom filter group
if (fHasCustomFilter)
fCustomFiltersActionGroup= new CustomFiltersActionGroup(this, fViewer);
fToggleLinkingAction= new ToggleLinkingAction(this);
}
private void doWorkingSetChanged(PropertyChangeEvent event) {
String property= event.getProperty();
if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property))
updateTitle();
else if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) {
updateTitle();
fViewer.getControl().setRedraw(false);
fViewer.refresh();
fViewer.getControl().setRedraw(true);
}
}
/**
* Returns the shell to use for opening dialogs.
* Used in this class, and in the actions.
*/
Shell getShell() {
return fViewer.getControl().getShell();
}
protected final Display getDisplay() {
return fViewer.getControl().getDisplay();
}
/**
* Returns the selection provider.
*/
ISelectionProvider getSelectionProvider() {
return fViewer;
}
/**
* Answers if the given <code>element</code> is a valid
* input for this part.
*
* @param element the object to test
* @return <true> if the given element is a valid input
*/
abstract protected boolean isValidInput(Object element);
/**
* Answers if the given <code>element</code> is a valid
* element for this part.
*
* @param element the object to test
* @return <true> if the given element is a valid element
*/
protected boolean isValidElement(Object element) {
if (element == null)
return false;
element= getSuitableJavaElement(element);
if (element == null)
return false;
Object input= getViewer().getInput();
if (input == null)
return false;
if (input instanceof Collection)
return ((Collection)input).contains(element);
else
return input.equals(element);
}
private boolean isInputResetBy(Object newInput, Object input, IWorkbenchPart part) {
if (newInput == null)
return part == fPreviousSelectionProvider;
if (input instanceof IJavaElement && newInput instanceof IJavaElement)
return getTypeComparator().compare(newInput, input) > 0;
if((newInput instanceof List) && (part instanceof PackagesView))
return true;
else
return false;
}
private boolean isInputResetBy(IWorkbenchPart part) {
if (!(part instanceof JavaBrowsingPart))
return true;
Object thisInput= getViewer().getInput();
Object partInput= ((JavaBrowsingPart)part).getViewer().getInput();
if(thisInput instanceof Collection)
thisInput= ((Collection)thisInput).iterator().next();
if(partInput instanceof Collection)
partInput= ((Collection)partInput).iterator().next();
if (thisInput instanceof IJavaElement && partInput instanceof IJavaElement)
return getTypeComparator().compare(partInput, thisInput) > 0;
else
return true;
}
protected boolean isAncestorOf(Object ancestor, Object element) {
if (element instanceof IJavaElement && ancestor instanceof IJavaElement)
return !element.equals(ancestor) && internalIsAncestorOf((IJavaElement)ancestor, (IJavaElement)element);
return false;
}
private boolean internalIsAncestorOf(IJavaElement ancestor, IJavaElement element) {
if (element != null)
return element.equals(ancestor) || internalIsAncestorOf(ancestor, element.getParent());
else
return false;
}
private boolean isSearchResultView(IWorkbenchPart part) {
return SearchUtil.isSearchPlugInActivated() && (part instanceof ISearchResultView);
}
protected boolean needsToProcessSelectionChanged(IWorkbenchPart part, ISelection selection) {
if (!fProcessSelectionEvents || part == this || isSearchResultView(part)){
if (part == this)
fPreviousSelectionProvider= part;
return false;
}
return true;
}
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if (!needsToProcessSelectionChanged(part, selection))
return;
if (fToggleLinkingAction.isChecked() && (part instanceof ITextEditor)) {
setSelectionFromEditor(part, selection);
return;
}
if (!(selection instanceof IStructuredSelection))
return;
// Set selection
Object selectedElement= getSingleElementFromSelection(selection);
if (selectedElement != null && (part == null || part.equals(fPreviousSelectionProvider)) && selectedElement.equals(fPreviousSelectedElement))
return;
fPreviousSelectedElement= selectedElement;
Object currentInput= getViewer().getInput();
if (selectedElement != null && selectedElement.equals(currentInput)) {
IJavaElement elementToSelect= findElementToSelect(selectedElement);
if (elementToSelect != null && getTypeComparator().compare(selectedElement, elementToSelect) < 0)
setSelection(new StructuredSelection(elementToSelect), true);
else if (elementToSelect == null && (this instanceof MembersView)) {
setSelection(StructuredSelection.EMPTY, true);
fPreviousSelectedElement= StructuredSelection.EMPTY;
}
fPreviousSelectionProvider= part;
return;
}
// Clear input if needed
if (part != fPreviousSelectionProvider && selectedElement != null && !selectedElement.equals(currentInput) && isInputResetBy(selectedElement, currentInput, part)) {
if (!isAncestorOf(selectedElement, currentInput))
setInput(null);
fPreviousSelectionProvider= part;
return;
} else if (selection.isEmpty() && !isInputResetBy(part)) {
fPreviousSelectionProvider= part;
return;
} else if (selectedElement == null && part == fPreviousSelectionProvider) {
setInput(null);
fPreviousSelectionProvider= part;
return;
}
fPreviousSelectionProvider= part;
// Adjust input and set selection and
adjustInputAndSetSelection(selectedElement);
}
void setHasWorkingSetFilter(boolean state) {
fHasWorkingSetFilter= state;
}
void setHasCustomSetFilter(boolean state) {
fHasCustomFilter= state;
}
protected Object getInput() {
return fViewer.getInput();
}
protected void setInput(Object input) {
setViewerInput(input);
updateTitle();
}
boolean isLinkingEnabled() {
return fLinkingEnabled;
}
private void initLinkingEnabled() {
fLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(getLinkToEditorKey());
}
private void setViewerInput(Object input) {
fProcessSelectionEvents= false;
fViewer.setInput(input);
fProcessSelectionEvents= true;
}
void updateTitle() {
setTitleToolTip(getToolTipText(fViewer.getInput()));
}
/**
* Returns the tool tip text for the given element.
*/
String getToolTipText(Object element) {
String result;
if (!(element instanceof IResource)) {
result= JavaElementLabels.getTextLabel(element, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS);
} else {
IPath path= ((IResource) element).getFullPath();
if (path.isRoot()) {
result= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$
} else {
result= path.makeRelative().toString();
}
}
if (fWorkingSetFilterActionGroup == null || fWorkingSetFilterActionGroup.getWorkingSet() == null)
return result;
IWorkingSet ws= fWorkingSetFilterActionGroup.getWorkingSet();
String wsstr= JavaBrowsingMessages.getFormattedString("JavaBrowsingPart.toolTip", new String[] { ws.getName() }); //$NON-NLS-1$
if (result.length() == 0)
return wsstr;
return JavaBrowsingMessages.getFormattedString("JavaBrowsingPart.toolTip2", new String[] { result, ws.getName() }); //$NON-NLS-1$
}
public String getTitleToolTip() {
if (fViewer == null)
return super.getTitleToolTip();
return getToolTipText(fViewer.getInput());
}
protected final StructuredViewer getViewer() {
return fViewer;
}
protected final void setViewer(StructuredViewer viewer){
fViewer= viewer;
}
protected JavaUILabelProvider createLabelProvider() {
return new AppearanceAwareLabelProvider(
AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS,
AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS
);
}
protected ILabelProvider createTitleProvider() {
return new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_SMALL_ICONS);
}
protected final ILabelProvider getLabelProvider() {
return fLabelProvider;
}
protected final ILabelProvider getTitleProvider() {
return fTitleProvider;
}
/**
* Creates the the viewer of this part.
*
* @param parent the parent for the viewer
*/
protected StructuredViewer createViewer(Composite parent) {
return new ProblemTableViewer(parent, SWT.MULTI);
}
protected int getLabelProviderFlags() {
return JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_OVERLAY_ICONS |
JavaElementLabelProvider.SHOW_SMALL_ICONS | JavaElementLabelProvider.SHOW_VARIABLE | JavaElementLabelProvider.SHOW_PARAMETERS;
}
/**
* Adds filters the viewer of this part.
*/
protected void addFilters() {
// default is to have no filters
}
/**
* Creates the the content provider of this part.
*/
protected IContentProvider createContentProvider() {
return new JavaBrowsingContentProvider(true, this);
}
protected void setInitialInput() {
// Use the selection, if any
ISelection selection= getSite().getPage().getSelection();
Object input= getSingleElementFromSelection(selection);
if (!(input instanceof IJavaElement)) {
// Use the input of the page
input= getSite().getPage().getInput();
if (!(input instanceof IJavaElement) && input instanceof IAdaptable)
input= ((IAdaptable)input).getAdapter(IJavaElement.class);
}
setInput(findInputForJavaElement((IJavaElement)input));
}
protected void setInitialSelection() {
// Use the selection, if any
Object input;
IWorkbenchPage page= getSite().getPage();
ISelection selection= null;
if (page != null)
selection= page.getSelection();
if (selection instanceof ITextSelection) {
Object part= PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
if (part instanceof IEditorPart) {
setSelectionFromEditor((IEditorPart)part);
if (fViewer.getSelection() != null)
return;
}
}
// Use saved selection from memento
if (selection == null || selection.isEmpty())
selection= restoreSelectionState(fMemento);
if (selection == null || selection.isEmpty()) {
// Use the input of the page
input= getSite().getPage().getInput();
if (!(input instanceof IJavaElement)) {
if (input instanceof IAdaptable)
input= ((IAdaptable)input).getAdapter(IJavaElement.class);
else
return;
}
selection= new StructuredSelection(input);
}
selectionChanged(null, selection);
}
protected final void setHelp() {
JavaUIHelp.setHelp(fViewer, getHelpContextId());
}
/**
* Returns the context ID for the Help system
*
* @return the string used as ID for the Help context
*/
abstract protected String getHelpContextId();
/**
* Returns the preference key for the link to editor setting.
*
* @return the string used as key into the preference store
*/
abstract protected String getLinkToEditorKey();
/**
* Adds additional listeners to this view.
* This method can be overridden but should
* call super.
*/
protected void hookViewerListeners() {
fViewer.addPostSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
if (!fProcessSelectionEvents)
return;
fPreviousSelectedElement= getSingleElementFromSelection(event.getSelection());
IWorkbenchPage page= getSite().getPage();
if (page == null)
return;
if (page.equals(JavaPlugin.getActivePage()) && JavaBrowsingPart.this.equals(page.getActivePart())) {
linkToEditor((IStructuredSelection)event.getSelection());
}
}
});
fViewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
IAction open= fOpenEditorGroup.getOpenAction();
if (open.isEnabled()) {
open.run();
restoreSelection();
}
}
});
}
void restoreSelection() {
// Default is to do nothing
}
void adjustInputAndSetSelection(Object o) {
if (!(o instanceof IJavaElement)) {
setSelection(StructuredSelection.EMPTY, true);
return;
}
IJavaElement je= (IJavaElement)o;
IJavaElement elementToSelect= getSuitableJavaElement(findElementToSelect(je));
IJavaElement newInput= findInputForJavaElement(je);
IJavaElement oldInput= null;
if (getInput() instanceof IJavaElement)
oldInput= (IJavaElement)getInput();
if (elementToSelect == null && !isValidInput(newInput) && (newInput == null && !isAncestorOf(je, oldInput)))
// Clear input
setInput(null);
else if (mustSetNewInput(elementToSelect, oldInput, newInput)) {
// Adjust input to selection
setInput(newInput);
// Recompute suitable element since it depends on the viewer's input
elementToSelect= getSuitableJavaElement(elementToSelect);
}
if (elementToSelect != null && elementToSelect.exists())
setSelection(new StructuredSelection(elementToSelect), true);
else
setSelection(StructuredSelection.EMPTY, true);
}
/**
* Compute if a new input must be set.
*
* @return <code>true</code> if the input has to be set
* @since 3.0
*/
private boolean mustSetNewInput(IJavaElement elementToSelect, IJavaElement oldInput, IJavaElement newInput) {
return (newInput == null || !newInput.equals(oldInput))
&& (elementToSelect == null
|| oldInput == null
|| (!((elementToSelect instanceof IPackageDeclaration)
&& (elementToSelect.getParent().equals(oldInput.getParent()))
&& (!isAncestorOf(getViewPartInput(), elementToSelect)))));
}
/**
* Finds the closest Java element which can be used as input for
* this part and has the given Java element as child
*
* @param je the Java element for which to search the closest input
* @return the closest Java element used as input for this part
*/
protected IJavaElement findInputForJavaElement(IJavaElement je) {
if (je == null || !je.exists())
return null;
if (isValidInput(je))
return je;
return findInputForJavaElement(je.getParent());
}
protected final IJavaElement findElementToSelect(Object obj) {
if (obj instanceof IJavaElement)
return findElementToSelect((IJavaElement)obj);
return null;
}
/**
* Finds the element which has to be selected in this part.
*
* @param je the Java element which has the focus
*/
abstract protected IJavaElement findElementToSelect(IJavaElement je);
protected final Object getSingleElementFromSelection(ISelection selection) {
if (!(selection instanceof StructuredSelection) || selection.isEmpty())
return null;
Iterator iter= ((StructuredSelection)selection).iterator();
Object firstElement= iter.next();
if (!(firstElement instanceof IJavaElement)) {
if (SearchUtil.isISearchResultViewEntry(firstElement)) {
IJavaElement je= SearchUtil.getJavaElement(firstElement);
if (je != null)
return je;
firstElement= SearchUtil.getResource(firstElement);
}
if (firstElement instanceof IAdaptable) {
IJavaElement je= (IJavaElement)((IAdaptable)firstElement).getAdapter(IJavaElement.class);
if (je == null && firstElement instanceof IFile) {
IContainer parent= ((IFile)firstElement).getParent();
if (parent != null)
return (IJavaElement)parent.getAdapter(IJavaElement.class);
else return null;
} else
return je;
} else
return firstElement;
}
Object currentInput= getViewer().getInput();
if (currentInput == null || !currentInput.equals(findInputForJavaElement((IJavaElement)firstElement)))
if (iter.hasNext())
// multi selection and view is empty
return null;
else
// ok: single selection and view is empty
return firstElement;
// be nice to multi selection
while (iter.hasNext()) {
Object element= iter.next();
if (!(element instanceof IJavaElement))
return null;
if (!currentInput.equals(findInputForJavaElement((IJavaElement)element)))
return null;
}
return firstElement;
}
/**
* Gets the typeComparator.
* @return Returns a JavaElementTypeComparator
*/
protected Comparator getTypeComparator() {
return fTypeComparator;
}
/**
* Links to editor (if option enabled)
*/
private void linkToEditor(IStructuredSelection selection) {
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 void setSelectionFromEditor(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
setSelectionFromEditor(part);
}
void setSelectionFromEditor(IWorkbenchPart part) {
if (!linkBrowsingViewSelectionToEditor())
return;
if (part == null)
return;
IWorkbenchPartSite site= part.getSite();
if (site == null)
return;
ISelectionProvider provider= site.getSelectionProvider();
if (provider != null)
setSelectionFromEditor(part, provider.getSelection());
}
private void setSelectionFromEditor(IWorkbenchPart part, ISelection selection) {
if (part instanceof IEditorPart) {
IJavaElement element= null;
if (selection instanceof IStructuredSelection) {
Object obj= getSingleElementFromSelection(selection);
if (obj instanceof IJavaElement)
element= (IJavaElement)obj;
}
IEditorInput ei= ((IEditorPart)part).getEditorInput();
if (selection instanceof ITextSelection) {
int offset= ((ITextSelection)selection).getOffset();
element= getElementAt(ei, offset);
}
if (element != null) {
adjustInputAndSetSelection(element);
return;
}
if (ei instanceof IFileEditorInput) {
IFile file= ((IFileEditorInput)ei).getFile();
IJavaElement je= (IJavaElement)file.getAdapter(IJavaElement.class);
if (je == null) {
IContainer container= ((IFileEditorInput)ei).getFile().getParent();
if (container != null)
je= (IJavaElement)container.getAdapter(IJavaElement.class);
}
if (je == null) {
setSelection(null, false);
return;
}
adjustInputAndSetSelection(je);
} else if (ei instanceof IClassFileEditorInput) {
IClassFile cf= ((IClassFileEditorInput)ei).getClassFile();
adjustInputAndSetSelection(cf);
}
}
}
/**
* 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;
}
void setSelection(ISelection selection, boolean reveal) {
if (selection != null && selection.equals(fViewer.getSelection()))
return;
fProcessSelectionEvents= false;
fViewer.setSelection(selection, reveal);
fProcessSelectionEvents= true;
}
/**
* Tries to find the given element in a workingcopy.
*/
protected static IJavaElement getWorkingCopy(IJavaElement input) {
try {
if (input instanceof ICompilationUnit)
return EditorUtility.getWorkingCopy((ICompilationUnit) input);
else
return EditorUtility.getWorkingCopy(input, false);
} catch (JavaModelException ex) {
}
return null;
}
/**
* Converts the given Java element to one which is suitable for this
* view. It takes into account wether the view shows working copies or not.
*
* @param element the Java element to be converted
* @return an element suitable for this view
*/
IJavaElement getSuitableJavaElement(Object obj) {
if (!(obj instanceof IJavaElement))
return null;
IJavaElement element= (IJavaElement)obj;
if (fTypeComparator.compare(element, IJavaElement.COMPILATION_UNIT) > 0)
return element;
if (element.getElementType() == IJavaElement.CLASS_FILE)
return element;
if (isInputAWorkingCopy()) {
IJavaElement wc= getWorkingCopy(element);
if (wc != null)
element= wc;
return element;
}
else {
return element.getPrimaryElement();
}
}
boolean isInputAWorkingCopy() {
return ((StandardJavaElementContentProvider)getViewer().getContentProvider()).getProvideWorkingCopy();
}
/**
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#getElementAt(int)
*/
protected IJavaElement getElementAt(IEditorInput input, int offset) {
if (input instanceof IClassFileEditorInput) {
try {
return ((IClassFileEditorInput)input).getClassFile().getElementAt(offset);
} catch (JavaModelException ex) {
return null;
}
}
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(input);
if (unit != null)
try {
if (unit.isConsistent())
return unit.getElementAt(offset);
else {
/*
* XXX: We should set the selection later when the
* CU is reconciled.
* see https://bugs.eclipse.org/bugs/show_bug.cgi?id=51290
*/
}
} catch (JavaModelException ex) {
// fall through
}
return null;
}
protected IType getTypeForCU(ICompilationUnit cu) {
cu= (ICompilationUnit)getSuitableJavaElement(cu);
// Use primary type if possible
IType primaryType= cu.findPrimaryType();
if (primaryType != null)
return primaryType;
// Use first top-level type
try {
IType[] types= cu.getTypes();
if (types.length > 0)
return types[0];
else
return null;
} catch (JavaModelException ex) {
return null;
}
}
void setProcessSelectionEvents(boolean state) {
fProcessSelectionEvents= state;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
if (fViewer != null) {
return fViewer.getInput();
}
return null;
}
protected void setActionGroups(CompositeActionGroup actionGroups) {
fActionGroups= actionGroups;
}
protected void setBuildActionGroup(BuildActionGroup actionGroup) {
fBuildActionGroup= actionGroup;
}
protected void setCCPActionGroup(CCPActionGroup actionGroup) {
fCCPActionGroup= actionGroup;
}
protected void setCustomFiltersActionGroup(CustomFiltersActionGroup customFiltersActionGroup) {
fCustomFiltersActionGroup= customFiltersActionGroup;
}
protected boolean hasCustomFilter() {
return fHasCustomFilter;
}
protected boolean hasWorkingSetFilter() {
return fHasWorkingSetFilter;
}
protected void setOpenEditorGroup(OpenEditorActionGroup openEditorGroup) {
fOpenEditorGroup= openEditorGroup;
}
protected OpenEditorActionGroup getOpenEditorGroup() {
return fOpenEditorGroup;
}
protected BuildActionGroup getBuildActionGroup() {
return fBuildActionGroup;
}
protected CCPActionGroup getCCPActionGroup() {
return fCCPActionGroup;
}
private boolean linkBrowsingViewSelectionToEditor() {
return isLinkingEnabled();
}
public void setLinkingEnabled(boolean enabled) {
fLinkingEnabled= enabled;
PreferenceConstants.getPreferenceStore().setValue(getLinkToEditorKey(), enabled);
if (enabled) {
IEditorPart editor = getSite().getPage().getActiveEditor();
if (editor != null) {
setSelectionFromEditor(editor);
}
}
}
}
|
54,096 |
Bug 54096 deleting elements in the outline asks for confirmation twice
|
i20040304 Deleting Java outline elements is behaving in a weird way in this build. I have a Java source open. I select some methods in the Outline view, and press <Del>. A dialog opens saying "Are you sure you want to delete these <#elems> elements?". I say "Yes", but the dialog opens for the second time. And while the dialog is showing up, the elements are removed from the outline. Of course, confirm the second deletion fails because the elemnts are not there anymore.
|
resolved fixed
|
e198917
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-09T10:07:18Z | 2004-03-08T23:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaOutlinePage.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.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.dnd.DND;
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.Display;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.IPostSelectionProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.model.WorkbenchAdapter;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.part.IShowInSource;
import org.eclipse.ui.part.IShowInTarget;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.part.Page;
import org.eclipse.ui.part.ShowInContext;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IInitializer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IParent;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.ProblemsLabelDecorator.ProblemsLabelChangedEvent;
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.JdtActionConstants;
import org.eclipse.jdt.ui.actions.MemberFilterActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
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.JavaPluginImages;
import org.eclipse.jdt.internal.ui.actions.AbstractToggleLinkingAction;
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.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDropAdapter;
import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferenceCache;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
/**
* The content outline page of the Java editor. The viewer implements a proprietary
* update mechanism based on Java model deltas. It does not react on domain changes.
* It is specified to show the content of ICompilationUnits and IClassFiles.
* Pulishes its context menu under <code>JavaPlugin.getDefault().getPluginId() + ".outline"</code>.
*/
public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdaptable , IPostSelectionProvider {
static Object[] NO_CHILDREN= new Object[0];
/**
* The element change listener of the java outline viewer.
* @see IElementChangedListener
*/
class ElementChangedListener implements IElementChangedListener {
public void elementChanged(final ElementChangedEvent e) {
if (getControl() == null)
return;
Display d= getControl().getDisplay();
if (d != null) {
d.asyncExec(new Runnable() {
public void run() {
ICompilationUnit cu= (ICompilationUnit) fInput;
IJavaElement base= cu;
if (fTopLevelTypeOnly) {
base= getMainType(cu);
if (base == null) {
if (fOutlineViewer != null)
fOutlineViewer.refresh(true);
return;
}
}
IJavaElementDelta delta= findElement(base, e.getDelta());
if (delta != null && fOutlineViewer != null) {
fOutlineViewer.reconcile(delta);
}
}
});
}
}
private boolean isPossibleStructuralChange(IJavaElementDelta cuDelta) {
if (cuDelta.getKind() != IJavaElementDelta.CHANGED) {
return true; // add or remove
}
int flags= cuDelta.getFlags();
if ((flags & IJavaElementDelta.F_CHILDREN) != 0) {
return true;
}
return (flags & (IJavaElementDelta.F_CONTENT | IJavaElementDelta.F_FINE_GRAINED)) == IJavaElementDelta.F_CONTENT;
}
protected IJavaElementDelta findElement(IJavaElement unit, IJavaElementDelta delta) {
if (delta == null || unit == null)
return null;
IJavaElement element= delta.getElement();
if (unit.equals(element)) {
if (isPossibleStructuralChange(delta)) {
return delta;
}
return null;
}
if (element.getElementType() > IJavaElement.CLASS_FILE)
return null;
IJavaElementDelta[] children= delta.getAffectedChildren();
if (children == null || children.length == 0)
return null;
for (int i= 0; i < children.length; i++) {
IJavaElementDelta d= findElement(unit, children[i]);
if (d != null)
return d;
}
return null;
}
}
static class NoClassElement extends WorkbenchAdapter implements IAdaptable {
/*
* @see java.lang.Object#toString()
*/
public String toString() {
return JavaEditorMessages.getString("JavaOutlinePage.error.NoTopLevelType"); //$NON-NLS-1$
}
/*
* @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class)
*/
public Object getAdapter(Class clas) {
if (clas == IWorkbenchAdapter.class)
return this;
return null;
}
}
/**
* Content provider for the children of an ICompilationUnit or
* an IClassFile
* @see ITreeContentProvider
*/
class ChildrenProvider implements ITreeContentProvider {
private Object[] NO_CLASS= new Object[] {new NoClassElement()};
private ElementChangedListener fListener;
protected boolean matches(IJavaElement element) {
if (element.getElementType() == IJavaElement.METHOD) {
String name= element.getElementName();
return (name != null && name.indexOf('<') >= 0);
}
return false;
}
protected IJavaElement[] filter(IJavaElement[] children) {
boolean initializers= false;
for (int i= 0; i < children.length; i++) {
if (matches(children[i])) {
initializers= true;
break;
}
}
if (!initializers)
return children;
Vector v= new Vector();
for (int i= 0; i < children.length; i++) {
if (matches(children[i]))
continue;
v.addElement(children[i]);
}
IJavaElement[] result= new IJavaElement[v.size()];
v.copyInto(result);
return result;
}
public Object[] getChildren(Object parent) {
if (parent instanceof IParent) {
IParent c= (IParent) parent;
try {
return filter(c.getChildren());
} catch (JavaModelException x) {
JavaPlugin.log(x);
}
}
return NO_CHILDREN;
}
public Object[] getElements(Object parent) {
if (fTopLevelTypeOnly) {
if (parent instanceof ICompilationUnit) {
try {
IType type= getMainType((ICompilationUnit) parent);
return type != null ? type.getChildren() : NO_CLASS;
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
} else if (parent instanceof IClassFile) {
try {
IType type= getMainType((IClassFile) parent);
return type != null ? type.getChildren() : NO_CLASS;
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
}
return getChildren(parent);
}
public Object getParent(Object child) {
if (child instanceof IJavaElement) {
IJavaElement e= (IJavaElement) child;
return e.getParent();
}
return null;
}
public boolean hasChildren(Object parent) {
if (parent instanceof IParent) {
IParent c= (IParent) parent;
try {
IJavaElement[] children= filter(c.getChildren());
return (children != null && children.length > 0);
} catch (JavaModelException x) {
JavaPlugin.log(x);
}
}
return false;
}
public boolean isDeleted(Object o) {
return false;
}
public void dispose() {
if (fListener != null) {
JavaCore.removeElementChangedListener(fListener);
fListener= null;
}
}
/*
* @see IContentProvider#inputChanged(Viewer, Object, Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
boolean isCU= (newInput instanceof ICompilationUnit);
if (isCU && fListener == null) {
fListener= new ElementChangedListener();
JavaCore.addElementChangedListener(fListener);
} else if (!isCU && fListener != null) {
JavaCore.removeElementChangedListener(fListener);
fListener= null;
}
}
}
class JavaOutlineViewer extends TreeViewer {
/**
* Indicates an item which has been reused. At the point of
* its reuse it has been expanded. This field is used to
* communicate between <code>internalExpandToLevel</code> and
* <code>reuseTreeItem</code>.
*/
private Item fReusedExpandedItem;
private boolean fReorderedMembers;
private boolean fForceFireSelectionChanged;
public JavaOutlineViewer(Tree tree) {
super(tree);
setAutoExpandLevel(ALL_LEVELS);
setUseHashlookup(true);
}
/**
* Investigates the given element change event and if affected incrementally
* updates the outline.
*/
public void reconcile(IJavaElementDelta delta) {
fReorderedMembers= false;
fForceFireSelectionChanged= false;
if (getSorter() == null) {
if (fTopLevelTypeOnly
&& delta.getElement() instanceof IType
&& (delta.getKind() & IJavaElementDelta.ADDED) != 0)
{
refresh(true);
} else {
Widget w= findItem(fInput);
if (w != null && !w.isDisposed())
update(w, delta);
if (fForceFireSelectionChanged)
fireSelectionChanged(new SelectionChangedEvent(getSite().getSelectionProvider(), this.getSelection()));
if (fReorderedMembers) {
refresh(false);
fReorderedMembers= false;
}
}
} else {
// just for now
refresh(true);
}
}
/*
* @see TreeViewer#internalExpandToLevel
*/
protected void internalExpandToLevel(Widget node, int level) {
if (node instanceof Item) {
Item i= (Item) node;
if (i.getData() instanceof IJavaElement) {
IJavaElement je= (IJavaElement) i.getData();
if (je.getElementType() == IJavaElement.IMPORT_CONTAINER || isInnerType(je)) {
if (i != fReusedExpandedItem) {
setExpanded(i, false);
return;
}
}
}
}
super.internalExpandToLevel(node, level);
}
protected void reuseTreeItem(Item item, Object element) {
// remove children
Item[] c= getChildren(item);
if (c != null && c.length > 0) {
if (getExpanded(item))
fReusedExpandedItem= item;
for (int k= 0; k < c.length; k++) {
if (c[k].getData() != null)
disassociate(c[k]);
c[k].dispose();
}
}
updateItem(item, element);
updatePlus(item, element);
internalExpandToLevel(item, ALL_LEVELS);
fReusedExpandedItem= null;
fForceFireSelectionChanged= true;
}
protected boolean mustUpdateParent(IJavaElementDelta delta, IJavaElement element) {
if (element instanceof IMethod) {
if ((delta.getKind() & IJavaElementDelta.ADDED) != 0) {
try {
return ((IMethod)element).isMainMethod();
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
}
return "main".equals(element.getElementName()); //$NON-NLS-1$
}
return false;
}
protected ISourceRange getSourceRange(IJavaElement element) throws JavaModelException {
if (element instanceof ISourceReference)
return ((ISourceReference) element).getSourceRange();
if (element instanceof IMember && !(element instanceof IInitializer))
return ((IMember) element).getNameRange();
return null;
}
protected boolean overlaps(ISourceRange range, int start, int end) {
return start <= (range.getOffset() + range.getLength() - 1) && range.getOffset() <= end;
}
protected boolean filtered(IJavaElement parent, IJavaElement child) {
Object[] result= new Object[] { child };
ViewerFilter[] filters= getFilters();
for (int i= 0; i < filters.length; i++) {
result= filters[i].filter(this, parent, result);
if (result.length == 0)
return true;
}
return false;
}
protected void update(Widget w, IJavaElementDelta delta) {
Item item;
IJavaElement parent= delta.getElement();
IJavaElementDelta[] affected= delta.getAffectedChildren();
Item[] children= getChildren(w);
boolean doUpdateParent= false;
boolean doUpdateParentsPlus= false;
Vector deletions= new Vector();
Vector additions= new Vector();
for (int i= 0; i < affected.length; i++) {
IJavaElementDelta affectedDelta= affected[i];
IJavaElement affectedElement= affectedDelta.getElement();
int status= affected[i].getKind();
// find tree item with affected element
int j;
for (j= 0; j < children.length; j++)
if (affectedElement.equals(children[j].getData()))
break;
if (j == children.length) {
// remove from collapsed parent
if ((status & IJavaElementDelta.REMOVED) != 0) {
doUpdateParentsPlus= true;
continue;
}
// addition
if ((status & IJavaElementDelta.CHANGED) != 0 &&
(affectedDelta.getFlags() & IJavaElementDelta.F_MODIFIERS) != 0 &&
!filtered(parent, affectedElement))
{
additions.addElement(affectedDelta);
}
continue;
}
item= children[j];
// removed
if ((status & IJavaElementDelta.REMOVED) != 0) {
deletions.addElement(item);
doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement);
// changed
} else if ((status & IJavaElementDelta.CHANGED) != 0) {
int change= affectedDelta.getFlags();
doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement);
if ((change & IJavaElementDelta.F_MODIFIERS) != 0) {
if (filtered(parent, affectedElement))
deletions.addElement(item);
else
updateItem(item, affectedElement);
}
if ((change & IJavaElementDelta.F_CONTENT) != 0)
updateItem(item, affectedElement);
if ((change & IJavaElementDelta.F_CHILDREN) != 0)
update(item, affectedDelta);
if ((change & IJavaElementDelta.F_REORDER) != 0)
fReorderedMembers= true;
}
}
// find all elements to add
IJavaElementDelta[] add= delta.getAddedChildren();
if (additions.size() > 0) {
IJavaElementDelta[] tmp= new IJavaElementDelta[add.length + additions.size()];
System.arraycopy(add, 0, tmp, 0, add.length);
for (int i= 0; i < additions.size(); i++)
tmp[i + add.length]= (IJavaElementDelta) additions.elementAt(i);
add= tmp;
}
// add at the right position
go2: for (int i= 0; i < add.length; i++) {
try {
IJavaElement e= add[i].getElement();
if (filtered(parent, e))
continue go2;
doUpdateParent= doUpdateParent || mustUpdateParent(add[i], e);
ISourceRange rng= getSourceRange(e);
int start= rng.getOffset();
int end= start + rng.getLength() - 1;
Item last= null;
item= null;
children= getChildren(w);
for (int j= 0; j < children.length; j++) {
item= children[j];
IJavaElement r= (IJavaElement) item.getData();
if (r == null) {
// parent node collapsed and not be opened before -> do nothing
continue go2;
}
try {
rng= getSourceRange(r);
boolean fieldsOnSameLine= r.getElementType() == IJavaElement.FIELD && e.getElementType() == IJavaElement.FIELD
&& rng.getOffset() == start && rng.getLength() == end - start + 1;
if (!fieldsOnSameLine && overlaps(rng, start, end)) {
// be tolerant if the delta is not correct, or if
// the tree has been updated other than by a delta
reuseTreeItem(item, e);
continue go2;
} else if (rng.getOffset() > start) {
if (last != null && deletions.contains(last)) {
// reuse item
deletions.removeElement(last);
reuseTreeItem(last, e);
} else {
// nothing to reuse
createTreeItem(w, e, j);
}
continue go2;
}
} catch (JavaModelException x) {
// stumbled over deleted element
}
last= item;
}
// add at the end of the list
if (last != null && deletions.contains(last)) {
// reuse item
deletions.removeElement(last);
reuseTreeItem(last, e);
} else {
// nothing to reuse
createTreeItem(w, e, -1);
}
} catch (JavaModelException x) {
// the element to be added is not present -> don't add it
}
}
// remove items which haven't been reused
Enumeration e= deletions.elements();
while (e.hasMoreElements()) {
item= (Item) e.nextElement();
disassociate(item);
item.dispose();
}
if (doUpdateParent)
updateItem(w, delta.getElement());
if (!doUpdateParent && doUpdateParentsPlus && w instanceof Item)
updatePlus((Item)w, delta.getElement());
}
/*
* @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent)
*/
protected void handleLabelProviderChanged(LabelProviderChangedEvent event) {
Object input= getInput();
if (event instanceof ProblemsLabelChangedEvent) {
ProblemsLabelChangedEvent e= (ProblemsLabelChangedEvent) event;
if (e.isMarkerChange() && input instanceof ICompilationUnit) {
return; // marker changes can be ignored
}
}
// look if the underlying resource changed
Object[] changed= event.getElements();
if (changed != null) {
IResource resource= getUnderlyingResource();
if (resource != null) {
for (int i= 0; i < changed.length; i++) {
if (changed[i] != null && changed[i].equals(resource)) {
// change event to a full refresh
event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource());
break;
}
}
}
}
super.handleLabelProviderChanged(event);
}
private IResource getUnderlyingResource() {
Object input= getInput();
if (input instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit) input;
cu= JavaModelUtil.toOriginal(cu);
return cu.getResource();
} else if (input instanceof IClassFile) {
return ((IClassFile) input).getResource();
}
return null;
}
}
class LexicalSortingAction extends Action {
private JavaElementSorter fSorter= new JavaElementSorter();
public LexicalSortingAction() {
super();
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.LEXICAL_SORTING_OUTLINE_ACTION);
setText(JavaEditorMessages.getString("JavaOutlinePage.Sort.label")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$
setToolTipText(JavaEditorMessages.getString("JavaOutlinePage.Sort.tooltip")); //$NON-NLS-1$
setDescription(JavaEditorMessages.getString("JavaOutlinePage.Sort.description")); //$NON-NLS-1$
boolean checked= JavaPlugin.getDefault().getPreferenceStore().getBoolean("LexicalSortingAction.isChecked"); //$NON-NLS-1$
valueChanged(checked, false);
}
public void run() {
valueChanged(isChecked(), true);
}
private void valueChanged(final boolean on, boolean store) {
setChecked(on);
BusyIndicator.showWhile(fOutlineViewer.getControl().getDisplay(), new Runnable() {
public void run() {
fOutlineViewer.setSorter(on ? fSorter : null); }
});
if (store)
JavaPlugin.getDefault().getPreferenceStore().setValue("LexicalSortingAction.isChecked", on); //$NON-NLS-1$
}
}
class ClassOnlyAction extends Action {
public ClassOnlyAction() {
super();
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GO_INTO_TOP_LEVEL_TYPE_ACTION);
setText(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.label")); //$NON-NLS-1$
setToolTipText(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.tooltip")); //$NON-NLS-1$
setDescription(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.description")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "gointo_toplevel_type.gif"); //$NON-NLS-1$
IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore();
boolean showclass= preferenceStore.getBoolean("GoIntoTopLevelTypeAction.isChecked"); //$NON-NLS-1$
setTopLevelTypeOnly(showclass);
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
setTopLevelTypeOnly(!fTopLevelTypeOnly);
}
private void setTopLevelTypeOnly(boolean show) {
fTopLevelTypeOnly= show;
setChecked(show);
fOutlineViewer.refresh(false);
IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore();
preferenceStore.setValue("GoIntoTopLevelTypeAction.isChecked", show); //$NON-NLS-1$
}
}
/**
* This action toggles whether this Java Outline page links
* its selection to the active editor.
*
* @since 3.0
*/
public class ToggleLinkingAction extends AbstractToggleLinkingAction {
JavaOutlinePage fJavaOutlinePage;
/**
* Constructs a new action.
*/
public ToggleLinkingAction(JavaOutlinePage outlinePage) {
boolean isLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE);
setChecked(isLinkingEnabled);
fJavaOutlinePage= outlinePage;
}
/**
* Runs the action.
*/
public void run() {
PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, isChecked());
if (isChecked() && fEditor != null)
fEditor.synchronizeOutlinePage(fEditor.computeHighlightRangeSourceReference(), false);
}
}
/** A flag to show contents of top level type only */
private boolean fTopLevelTypeOnly;
private IJavaElement fInput;
private String fContextMenuID;
private Menu fMenu;
private JavaOutlineViewer fOutlineViewer;
private JavaEditor fEditor;
private MemberFilterActionGroup fMemberFilterActionGroup;
private ListenerList fSelectionChangedListeners= new ListenerList();
private ListenerList fPostSelectionChangedListeners= new ListenerList();
private Hashtable fActions= new Hashtable();
private TogglePresentationAction fTogglePresentation;
private GotoAnnotationAction fPreviousAnnotation;
private GotoAnnotationAction fNextAnnotation;
private TextEditorAction fShowJavadoc;
private TextOperationAction fUndo;
private TextOperationAction fRedo;
private ToggleLinkingAction fToggleLinkingAction;
private CompositeActionGroup fActionGroups;
private CCPActionGroup fCCPActionGroup;
private IPropertyChangeListener fPropertyChangeListener;
public JavaOutlinePage(String contextMenuID, JavaEditor editor) {
super();
Assert.isNotNull(editor);
fContextMenuID= contextMenuID;
fEditor= editor;
fTogglePresentation= new TogglePresentationAction();
fPreviousAnnotation= new GotoAnnotationAction("PreviousAnnotation.", false); //$NON-NLS-1$
fNextAnnotation= new GotoAnnotationAction("NextAnnotation.", true); //$NON-NLS-1$
fShowJavadoc= (TextEditorAction) fEditor.getAction("ShowJavaDoc"); //$NON-NLS-1$
fUndo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.UNDO);
fRedo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.REDO);
fTogglePresentation.setEditor(editor);
fPreviousAnnotation.setEditor(editor);
fNextAnnotation.setEditor(editor);
fPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
doPropertyChange(event);
}
};
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
}
/**
* Returns the primary type of a compilation unit (has the same
* name as the compilation unit).
*
* @param compilationUnit the compilation unit
* @return returns the primary type of the compilation unit, or
* <code>null</code> if is does not have one
*/
protected IType getMainType(ICompilationUnit compilationUnit) {
if (compilationUnit == null)
return null;
String name= compilationUnit.getElementName();
int index= name.indexOf('.');
if (index != -1)
name= name.substring(0, index);
IType type= compilationUnit.getType(name);
return type.exists() ? type : null;
}
/**
* Returns the primary type of a class file.
*
* @param classFile the class file
* @return returns the primary type of the class file, or <code>null</code>
* if is does not have one
*/
protected IType getMainType(IClassFile classFile) {
try {
IType type= classFile.getType();
return type != null && type.exists() ? type : null;
} catch (JavaModelException e) {
return null;
}
}
/* (non-Javadoc)
* Method declared on Page
*/
public void init(IPageSite pageSite) {
super.init(pageSite);
}
private void doPropertyChange(PropertyChangeEvent event) {
if (fOutlineViewer != null) {
if (MembersOrderPreferenceCache.isMemberOrderProperty(event.getProperty())) {
fOutlineViewer.refresh(false);
}
}
}
/*
* @see ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener)
*/
public void addSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.addSelectionChangedListener(listener);
else
fSelectionChangedListeners.add(listener);
}
/*
* @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener)
*/
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.removeSelectionChangedListener(listener);
else
fSelectionChangedListeners.remove(listener);
}
/*
* @see ISelectionProvider#setSelection(ISelection)
*/
public void setSelection(ISelection selection) {
if (fOutlineViewer != null)
fOutlineViewer.setSelection(selection);
}
/*
* @see ISelectionProvider#getSelection()
*/
public ISelection getSelection() {
if (fOutlineViewer == null)
return StructuredSelection.EMPTY;
return fOutlineViewer.getSelection();
}
/*
* @see org.eclipse.jface.text.IPostSelectionProvider#addPostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void addPostSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.addPostSelectionChangedListener(listener);
else
fPostSelectionChangedListeners.add(listener);
}
/*
* @see org.eclipse.jface.text.IPostSelectionProvider#removePostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void removePostSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.removePostSelectionChangedListener(listener);
else
fPostSelectionChangedListeners.remove(listener);
}
private void registerToolbarActions() {
IToolBarManager toolBarManager= getSite().getActionBars().getToolBarManager();
if (toolBarManager != null) {
toolBarManager.add(new ClassOnlyAction());
toolBarManager.add(new LexicalSortingAction());
fMemberFilterActionGroup= new MemberFilterActionGroup(fOutlineViewer, "JavaOutlineViewer"); //$NON-NLS-1$
fMemberFilterActionGroup.contributeToToolBar(toolBarManager);
fToggleLinkingAction= new ToggleLinkingAction(this);
toolBarManager.add(fToggleLinkingAction);
}
}
/*
* @see IPage#createControl
*/
public void createControl(Composite parent) {
Tree tree= new Tree(parent, SWT.MULTI);
AppearanceAwareLabelProvider lprovider= new AppearanceAwareLabelProvider(
AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE,
AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS
);
fOutlineViewer= new JavaOutlineViewer(tree);
initDragAndDrop();
fOutlineViewer.setContentProvider(new ChildrenProvider());
fOutlineViewer.setLabelProvider(new DecoratingJavaLabelProvider(lprovider));
Object[] listeners= fSelectionChangedListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
fSelectionChangedListeners.remove(listeners[i]);
fOutlineViewer.addSelectionChangedListener((ISelectionChangedListener) listeners[i]);
}
listeners= fPostSelectionChangedListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
fPostSelectionChangedListeners.remove(listeners[i]);
fOutlineViewer.addPostSelectionChangedListener((ISelectionChangedListener) listeners[i]);
}
MenuManager manager= new MenuManager(fContextMenuID, fContextMenuID);
manager.setRemoveAllWhenShown(true);
manager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager m) {
contextMenuAboutToShow(m);
}
});
fMenu= manager.createContextMenu(tree);
tree.setMenu(fMenu);
IPageSite site= getSite();
site.registerContextMenu(JavaPlugin.getPluginId() + ".outline", manager, fOutlineViewer); //$NON-NLS-1$
site.setSelectionProvider(fOutlineViewer);
// we must create the groups after we have set the selection provider to the site
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
new OpenViewActionGroup(this),
fCCPActionGroup= new CCPActionGroup(this),
new GenerateActionGroup(this),
new RefactorActionGroup(this),
new JavaSearchActionGroup(this)});
// register global actions
IActionBars bars= site.getActionBars();
bars.setGlobalActionHandler(ITextEditorActionConstants.UNDO, fUndo);
bars.setGlobalActionHandler(ITextEditorActionConstants.REDO, fRedo);
bars.setGlobalActionHandler(ITextEditorActionConstants.PREVIOUS, fPreviousAnnotation);
bars.setGlobalActionHandler(ITextEditorActionConstants.NEXT, fNextAnnotation);
bars.setGlobalActionHandler(JdtActionConstants.SHOW_JAVA_DOC, fShowJavadoc);
bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.TOGGLE_SHOW_SELECTED_ELEMENT_ONLY, fTogglePresentation);
bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_NEXT_ANNOTATION, fNextAnnotation);
bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_PREVIOUS_ANNOTATION, fPreviousAnnotation);
fActionGroups.fillActionBars(bars);
IStatusLineManager statusLineManager= bars.getStatusLineManager();
if (statusLineManager != null) {
StatusBarUpdater updater= new StatusBarUpdater(statusLineManager);
fOutlineViewer.addPostSelectionChangedListener(updater);
}
registerToolbarActions();
fOutlineViewer.setInput(fInput);
fOutlineViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
handleKeyReleased(e);
}
});
}
public void dispose() {
if (fEditor == null)
return;
if (fMemberFilterActionGroup != null) {
fMemberFilterActionGroup.dispose();
fMemberFilterActionGroup= null;
}
fEditor.outlinePageClosed();
fEditor= null;
fSelectionChangedListeners.clear();
fSelectionChangedListeners= null;
fPostSelectionChangedListeners.clear();
fPostSelectionChangedListeners= null;
if (fPropertyChangeListener != null) {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fMenu != null && !fMenu.isDisposed()) {
fMenu.dispose();
fMenu= null;
}
if (fActionGroups != null)
fActionGroups.dispose();
fTogglePresentation.setEditor(null);
fPreviousAnnotation.setEditor(null);
fNextAnnotation.setEditor(null);
fOutlineViewer= null;
super.dispose();
}
public Control getControl() {
if (fOutlineViewer != null)
return fOutlineViewer.getControl();
return null;
}
public void setInput(IJavaElement inputElement) {
fInput= inputElement;
if (fOutlineViewer != null)
fOutlineViewer.setInput(fInput);
}
public void select(ISourceReference reference) {
if (fOutlineViewer != null) {
ISelection s= fOutlineViewer.getSelection();
if (s instanceof IStructuredSelection) {
IStructuredSelection ss= (IStructuredSelection) s;
List elements= ss.toList();
if (!elements.contains(reference)) {
s= (reference == null ? StructuredSelection.EMPTY : new StructuredSelection(reference));
fOutlineViewer.setSelection(s, true);
}
}
}
}
public void setAction(String actionID, IAction action) {
Assert.isNotNull(actionID);
if (action == null)
fActions.remove(actionID);
else
fActions.put(actionID, action);
}
public IAction getAction(String actionID) {
Assert.isNotNull(actionID);
return (IAction) fActions.get(actionID);
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key == IShowInSource.class) {
return getShowInSource();
}
if (key == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES };
}
};
}
if (key == IShowInTarget.class) {
return getShowInTarget();
}
return null;
}
/**
* Convenience method to add the action installed under the given actionID to the
* specified group of the menu.
*/
protected void addAction(IMenuManager menu, String group, String actionID) {
IAction action= getAction(actionID);
if (action != null) {
if (action instanceof IUpdate)
((IUpdate) action).update();
if (action.isEnabled()) {
IMenuManager subMenu= menu.findMenuUsingPath(group);
if (subMenu != null)
subMenu.add(action);
else
menu.appendToGroup(group, action);
}
}
}
protected void contextMenuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
IStructuredSelection selection= (IStructuredSelection)getSelection();
fActionGroups.setContext(new ActionContext(selection));
fActionGroups.fillContextMenu(menu);
}
/*
* @see Page#setFocus()
*/
public void setFocus() {
if (fOutlineViewer != null)
fOutlineViewer.getControl().setFocus();
}
/**
* Checkes whether a given Java element is an inner type.
*/
private boolean isInnerType(IJavaElement element) {
if (element != null && element.getElementType() == IJavaElement.TYPE) {
IType type= (IType)element;
try {
return type.isMember();
} catch (JavaModelException e) {
IJavaElement parent= type.getParent();
if (parent != null) {
int parentElementType= parent.getElementType();
return (parentElementType != IJavaElement.COMPILATION_UNIT && parentElementType != IJavaElement.CLASS_FILE);
}
}
}
return false;
}
/**
* Handles key events in viewer.
*/
private void handleKeyReleased(KeyEvent event) {
if (event.stateMask != 0)
return;
IAction action= null;
if (event.character == SWT.DEL) {
action= fCCPActionGroup.getDeleteAction();
}
if (action != null && action.isEnabled())
action.run();
}
/**
* Returns the <code>IShowInSource</code> for this view.
*/
protected IShowInSource getShowInSource() {
return new IShowInSource() {
public ShowInContext getShowInContext() {
return new ShowInContext(
null,
getSite().getSelectionProvider().getSelection());
}
};
}
/**
* Returns the <code>IShowInTarget</code> for this view.
*/
protected IShowInTarget getShowInTarget() {
return new IShowInTarget() {
public boolean show(ShowInContext context) {
ISelection sel= context.getSelection();
if (sel instanceof ITextSelection) {
ITextSelection tsel= (ITextSelection) sel;
int offset= tsel.getOffset();
IJavaElement element= fEditor.getElementAt(offset);
if (element != null) {
setSelection(new StructuredSelection(element));
return true;
}
}
return false;
}
};
}
private void initDragAndDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
Transfer[] transfers= new Transfer[] {
LocalSelectionTransfer.getInstance()
};
// Drop Adapter
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fOutlineViewer)
};
fOutlineViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners));
// Drag Adapter
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fOutlineViewer)
};
fOutlineViewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(fOutlineViewer, dragListeners));
}
}
|
54,096 |
Bug 54096 deleting elements in the outline asks for confirmation twice
|
i20040304 Deleting Java outline elements is behaving in a weird way in this build. I have a Java source open. I select some methods in the Outline view, and press <Del>. A dialog opens saying "Are you sure you want to delete these <#elems> elements?". I say "Yes", but the dialog opens for the second time. And while the dialog is showing up, the elements are removed from the outline. Of course, confirm the second deletion fails because the elemnts are not there anymore.
|
resolved fixed
|
e198917
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-09T10:07:18Z | 2004-03-08T23:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerActionGroup.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 org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.OpenStrategy;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.IWorkingSetManager;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.MoveResourceAction;
import org.eclipse.ui.actions.OpenInNewWindowAction;
import org.eclipse.ui.actions.RenameResourceAction;
import org.eclipse.ui.views.framelist.BackAction;
import org.eclipse.ui.views.framelist.ForwardAction;
import org.eclipse.ui.views.framelist.FrameAction;
import org.eclipse.ui.views.framelist.FrameList;
import org.eclipse.ui.views.framelist.GoIntoAction;
import org.eclipse.ui.views.framelist.UpAction;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IOpenable;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.BuildActionGroup;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.CustomFiltersActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.ImportActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.JdtActionConstants;
import org.eclipse.jdt.ui.actions.NavigateActionGroup;
import org.eclipse.jdt.ui.actions.ProjectActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup;
import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup;
class PackageExplorerActionGroup extends CompositeActionGroup implements ISelectionChangedListener {
private PackageExplorerPart fPart;
private GoIntoAction fZoomInAction;
private BackAction fBackAction;
private ForwardAction fForwardAction;
private UpAction fUpAction;
private GotoTypeAction fGotoTypeAction;
private GotoPackageAction fGotoPackageAction;
private GotoResourceAction fGotoResourceAction;
private CollapseAllAction fCollapseAllAction;
private RenameResourceAction fRenameResourceAction;
private MoveResourceAction fMoveResourceAction;
private ToggleLinkingAction fToggleLinkingAction;
private NavigateActionGroup fNavigateActionGroup;
private CCPActionGroup fCCPActionGroup;
private WorkingSetFilterActionGroup fWorkingSetFilterActionGroup;
private CustomFiltersActionGroup fCustomFiltersActionGroup;
private int fLastElement;
private static final int INIT= 0;
private static final int RESOURCE= 1;
private static final int REST= 2;
public PackageExplorerActionGroup(PackageExplorerPart part) {
super();
fPart= part;
TreeViewer viewer= part.getViewer();
IPropertyChangeListener workingSetListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
doWorkingSetChanged(event);
}
};
IWorkbenchPartSite site = fPart.getSite();
Shell shell= site.getShell();
ISelectionProvider provider= site.getSelectionProvider();
IStructuredSelection selection= (IStructuredSelection) provider.getSelection();
setGroups(new ActionGroup[] {
new NewWizardsActionGroup(site),
fNavigateActionGroup= new NavigateActionGroup(fPart),
fCCPActionGroup= new CCPActionGroup(fPart),
new GenerateActionGroup(fPart),
new RefactorActionGroup(fPart),
new ImportActionGroup(fPart),
new BuildActionGroup(fPart),
new JavaSearchActionGroup(fPart),
new ProjectActionGroup(fPart),
fWorkingSetFilterActionGroup= new WorkingSetFilterActionGroup(JavaUI.ID_PACKAGES, shell, workingSetListener),
fCustomFiltersActionGroup= new CustomFiltersActionGroup(fPart, viewer),
new LayoutActionGroup(part)});
viewer.addFilter(fWorkingSetFilterActionGroup.getWorkingSetFilter());
PackagesFrameSource frameSource= new PackagesFrameSource(fPart);
FrameList frameList= new FrameList(frameSource);
frameSource.connectTo(frameList);
fZoomInAction= new GoIntoAction(frameList);
fBackAction= new BackAction(frameList);
fForwardAction= new ForwardAction(frameList);
fUpAction= new UpAction(frameList);
fRenameResourceAction= new RenameResourceAction(shell);
fMoveResourceAction= new MoveResourceAction(shell);
fGotoTypeAction= new GotoTypeAction(fPart);
fGotoPackageAction= new GotoPackageAction(fPart);
fGotoResourceAction= new GotoResourceAction(fPart);
fCollapseAllAction= new CollapseAllAction(fPart);
fToggleLinkingAction = new ToggleLinkingAction(fPart);
provider.addSelectionChangedListener(this);
update(selection);
fLastElement= INIT;
}
public void dispose() {
ISelectionProvider provider= fPart.getSite().getSelectionProvider();
provider.removeSelectionChangedListener(this);
super.dispose();
}
//---- Selection changed listener ---------------------------------------------------------
public void selectionChanged(SelectionChangedEvent event) {
fRenameResourceAction.selectionChanged(event);
fMoveResourceAction.selectionChanged(event);
IStructuredSelection selection= (IStructuredSelection)event.getSelection();
update(selection);
}
private void update(IStructuredSelection selection) {
int size= selection.size();
Object element= selection.getFirstElement();
IActionBars actionBars= fPart.getViewSite().getActionBars();
if (size == 1 && element instanceof IResource) {
if (fLastElement != RESOURCE) { // fLastAction in a work around for http://bugs.eclipse.org/bugs/show_bug.cgi?id=30508
actionBars.setGlobalActionHandler(ActionFactory.RENAME.getId(), fRenameResourceAction);
actionBars.setGlobalActionHandler(ActionFactory.MOVE.getId(), fMoveResourceAction);
actionBars.updateActionBars();
fLastElement= RESOURCE;
}
} else {
if (fLastElement != REST) {
actionBars.setGlobalActionHandler(ActionFactory.RENAME.getId(), null);
actionBars.setGlobalActionHandler(ActionFactory.MOVE.getId(), null);
actionBars.updateActionBars();
fLastElement= REST;
}
}
}
//---- Persistent state -----------------------------------------------------------------------
/* package */ void restoreFilterAndSorterState(IMemento memento) {
fWorkingSetFilterActionGroup.restoreState(memento);
fCustomFiltersActionGroup.restoreState(memento);
}
/* package */ void saveFilterAndSorterState(IMemento memento) {
fWorkingSetFilterActionGroup.saveState(memento);
fCustomFiltersActionGroup.saveState(memento);
}
//---- Action Bars ----------------------------------------------------------------------------
public void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
setGlobalActionHandlers(actionBars);
fillToolBar(actionBars.getToolBarManager());
fillViewMenu(actionBars.getMenuManager());
}
/* package */ void updateActionBars(IActionBars actionBars) {
actionBars.getToolBarManager().removeAll();
actionBars.getMenuManager().removeAll();
fillActionBars(actionBars);
actionBars.updateActionBars();
fZoomInAction.setEnabled(true);
}
private void setGlobalActionHandlers(IActionBars actionBars) {
// Navigate Go Into and Go To actions.
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_INTO, fZoomInAction);
actionBars.setGlobalActionHandler(ActionFactory.BACK.getId(), fBackAction);
actionBars.setGlobalActionHandler(ActionFactory.FORWARD.getId(), fForwardAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.UP, fUpAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_TO_RESOURCE, fGotoResourceAction);
actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_TYPE, fGotoTypeAction);
actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_PACKAGE, fGotoPackageAction);
}
/* package */ void fillToolBar(IToolBarManager toolBar) {
toolBar.add(fBackAction);
toolBar.add(fForwardAction);
toolBar.add(fUpAction);
toolBar.add(new Separator());
toolBar.add(fCollapseAllAction);
toolBar.add(fToggleLinkingAction);
}
/* package */ void fillViewMenu(IMenuManager menu) {
menu.add(fToggleLinkingAction);
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$
}
/* package */ void handleSelectionChanged(SelectionChangedEvent event) {
}
//---- Context menu -------------------------------------------------------------------------
public void fillContextMenu(IMenuManager menu) {
IStructuredSelection selection= (IStructuredSelection)getContext().getSelection();
int size= selection.size();
Object element= selection.getFirstElement();
addGotoMenu(menu, element, size);
addOpenNewWindowAction(menu, element);
super.fillContextMenu(menu);
}
private void addGotoMenu(IMenuManager menu, Object element, int size) {
boolean enabled= size == 1 && fPart.getViewer().isExpandable(element) && (isGoIntoTarget(element) || element instanceof IContainer);
fZoomInAction.setEnabled(enabled);
if (enabled)
menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction);
}
private boolean isGoIntoTarget(Object element) {
if (element == null)
return false;
if (element instanceof IJavaElement) {
int type= ((IJavaElement)element).getElementType();
return type == IJavaElement.JAVA_PROJECT ||
type == IJavaElement.PACKAGE_FRAGMENT_ROOT ||
type == IJavaElement.PACKAGE_FRAGMENT;
}
return false;
}
private void addOpenNewWindowAction(IMenuManager menu, Object element) {
if (element instanceof IJavaElement) {
element= ((IJavaElement)element).getResource();
}
if (!(element instanceof IContainer))
return;
menu.appendToGroup(
IContextMenuConstants.GROUP_OPEN,
new OpenInNewWindowAction(fPart.getSite().getWorkbenchWindow(), (IContainer)element));
}
//---- Key board and mouse handling ------------------------------------------------------------
/* package*/ void handleDoubleClick(DoubleClickEvent event) {
TreeViewer viewer= fPart.getViewer();
Object element= ((IStructuredSelection)event.getSelection()).getFirstElement();
if (viewer.isExpandable(element)) {
if (doubleClickGoesInto()) {
// don't zoom into compilation units and class files
if (element instanceof ICompilationUnit || element instanceof IClassFile)
return;
if (element instanceof IOpenable || element instanceof IContainer) {
fZoomInAction.run();
}
} else {
IAction openAction= fNavigateActionGroup.getOpenAction();
if (openAction != null && openAction.isEnabled() && OpenStrategy.getOpenMethod() == OpenStrategy.DOUBLE_CLICK)
return;
viewer.setExpandedState(element, !viewer.getExpandedState(element));
}
}
}
/* package */ void handleOpen(OpenEvent event) {
IAction openAction= fNavigateActionGroup.getOpenAction();
if (openAction != null && openAction.isEnabled()) {
openAction.run();
return;
}
}
/* package */ void handleKeyEvent(KeyEvent event) {
if (event.stateMask != 0)
return;
if (event.character == SWT.DEL) {
IAction delete= fCCPActionGroup.getDeleteAction();
if (delete != null && delete.isEnabled())
delete.run();
}
else if (event.keyCode == SWT.BS) {
if (fUpAction != null && fUpAction.isEnabled())
fUpAction.run();
}
}
private void doWorkingSetChanged(PropertyChangeEvent event) {
IWorkingSet workingSet= (IWorkingSet) event.getNewValue();
String workingSetName= null;
if (workingSet != null)
workingSetName= workingSet.getName();
fPart.setWorkingSetName(workingSetName);
fPart.updateTitle();
String property= event.getProperty();
if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) {
TreeViewer viewer= fPart.getViewer();
viewer.getControl().setRedraw(false);
viewer.refresh();
viewer.getControl().setRedraw(true);
}
}
private boolean doubleClickGoesInto() {
return PreferenceConstants.DOUBLE_CLICK_GOES_INTO.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.DOUBLE_CLICK));
}
public FrameAction getUpAction() {
return fUpAction;
}
public FrameAction getBackAction() {
return fBackAction;
}
public FrameAction getForwardAction() {
return fForwardAction;
}
public WorkingSetFilterActionGroup getWorkingSetActionGroup() {
return fWorkingSetFilterActionGroup;
}
public CustomFiltersActionGroup getCustomFilterActionGroup() {
return fCustomFiltersActionGroup;
}
}
|
54,096 |
Bug 54096 deleting elements in the outline asks for confirmation twice
|
i20040304 Deleting Java outline elements is behaving in a weird way in this build. I have a Java source open. I select some methods in the Outline view, and press <Del>. A dialog opens saying "Are you sure you want to delete these <#elems> elements?". I say "Yes", but the dialog opens for the second time. And while the dialog is showing up, the elements are removed from the outline. Of course, confirm the second deletion fails because the elemnts are not there anymore.
|
resolved fixed
|
e198917
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-09T10:07:18Z | 2004-03-08T23:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.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.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
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.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.ToolBar;
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.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.IBasicPropertyConstants;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
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.IPageLayout;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.IWorkingSetManager;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.IShowInSource;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.part.PageBook;
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.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.ITypeHierarchyViewPart;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
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.corext.util.AllTypesCache;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.AddMethodStubAction;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectAllAction;
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.preferences.MembersOrderPreferenceCache;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup;
/**
* view showing the supertypes/subtypes of its input.
*/
public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart, IViewPartInputProvider {
public static final int VIEW_ID_TYPE= 2;
public static final int VIEW_ID_SUPER= 0;
public static final int VIEW_ID_SUB= 1;
public static final int VIEW_ORIENTATION_VERTICAL= 0;
public static final int VIEW_ORIENTATION_HORIZONTAL= 1;
public static final int VIEW_ORIENTATION_SINGLE= 2;
private static final String DIALOGSTORE_HIERARCHYVIEW= "TypeHierarchyViewPart.hierarchyview"; //$NON-NLS-1$
private static final String DIALOGSTORE_VIEWORIENTATION= "TypeHierarchyViewPart.orientation"; //$NON-NLS-1$
private static final String TAG_INPUT= "input"; //$NON-NLS-1$
private static final String TAG_VIEW= "view"; //$NON-NLS-1$
private static final String TAG_ORIENTATION= "orientation"; //$NON-NLS-1$
private static final String TAG_RATIO= "ratio"; //$NON-NLS-1$
private static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
private static final String TAG_VERTICAL_SCROLL= "vertical_scroll"; //$NON-NLS-1$
private static final String GROUP_FOCUS= "group.focus"; //$NON-NLS-1$
// the selected type in the hierarchy view
private IType fSelectedType;
// input element or null
private IJavaElement fInputElement;
// history of input elements. No duplicates
private ArrayList fInputHistory;
private IMemento fMemento;
private IDialogSettings fDialogSettings;
private TypeHierarchyLifeCycle fHierarchyLifeCycle;
private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener;
private IPropertyChangeListener fPropertyChangeListener;
private SelectionProviderMediator fSelectionProviderMediator;
private ISelectionChangedListener fSelectionChangedListener;
private IPartListener2 fPartListener;
private int fCurrentOrientation;
private boolean fLinkingEnabled;
private boolean fSelectInEditor;
private boolean fIsVisible;
private boolean fNeedRefresh;
private boolean fIsEnableMemberFilter;
private boolean fIsRefreshRunnablePosted;
private int fCurrentViewerIndex;
private TypeHierarchyViewer[] fAllViewers;
private MethodsViewer fMethodsViewer;
private SashForm fTypeMethodsSplitter;
private PageBook fViewerbook;
private PageBook fPagebook;
private Label fNoHierarchyShownLabel;
private Label fEmptyTypesViewer;
private ViewForm fTypeViewerViewForm;
private ViewForm fMethodViewerViewForm;
private CLabel fMethodViewerPaneLabel;
private JavaUILabelProvider fPaneLabelProvider;
private ToggleViewAction[] fViewActions;
private ToggleLinkingAction fToggleLinkingAction;
private HistoryDropDownAction fHistoryDropDownAction;
private ToggleOrientationAction[] fToggleOrientationActions;
private EnableMemberFilterAction fEnableMemberFilterAction;
private ShowQualifiedTypeNamesAction fShowQualifiedTypeNamesAction;
private AddMethodStubAction fAddStubAction;
private FocusOnTypeAction fFocusOnTypeAction;
private FocusOnSelectionAction fFocusOnSelectionAction;
private CompositeActionGroup fActionGroups;
private CCPActionGroup fCCPActionGroup;
private SelectAllAction fSelectAllAction;
private WorkingSetFilterActionGroup fWorkingSetActionGroup;
public TypeHierarchyViewPart() {
fSelectedType= null;
fInputElement= null;
fIsVisible= false;
fIsRefreshRunnablePosted= false;
fSelectInEditor= true;
fHierarchyLifeCycle= new TypeHierarchyLifeCycle();
fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() {
public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, IType[] changedTypes) {
doTypeHierarchyChanged(typeHierarchy, changedTypes);
}
};
fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener);
fPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
doPropertyChange(event);
}
};
PreferenceConstants.getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
fIsEnableMemberFilter= false;
fInputHistory= new ArrayList();
fAllViewers= null;
fViewActions= new ToggleViewAction[] {
new ToggleViewAction(this, VIEW_ID_TYPE),
new ToggleViewAction(this, VIEW_ID_SUPER),
new ToggleViewAction(this, VIEW_ID_SUB)
};
fDialogSettings= JavaPlugin.getDefault().getDialogSettings();
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)
};
fEnableMemberFilterAction= new EnableMemberFilterAction(this, false);
fShowQualifiedTypeNamesAction= new ShowQualifiedTypeNamesAction(this, false);
fFocusOnTypeAction= new FocusOnTypeAction(this);
fPaneLabelProvider= new JavaUILabelProvider();
fAddStubAction= new AddMethodStubAction();
fFocusOnSelectionAction= new FocusOnSelectionAction(this);
fPartListener= new IPartListener2() {
public void partVisible(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
if (part == TypeHierarchyViewPart.this) {
visibilityChanged(true);
}
}
public void partHidden(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
if (part == TypeHierarchyViewPart.this) {
visibilityChanged(false);
}
}
public void partActivated(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partInputChanged(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partBroughtToTop(IWorkbenchPartReference ref) {}
public void partClosed(IWorkbenchPartReference ref) {}
public void partDeactivated(IWorkbenchPartReference ref) {}
public void partOpened(IWorkbenchPartReference ref) {}
};
fSelectionChangedListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
};
fLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR);
}
/**
* Method doPropertyChange.
* @param event
*/
protected void doPropertyChange(PropertyChangeEvent event) {
String property= event.getProperty();
if (fMethodsViewer != null) {
if (MembersOrderPreferenceCache.isMemberOrderProperty(event.getProperty())) {
fMethodsViewer.refresh();
}
}
if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) {
updateHierarchyViewer(true);
}
}
/**
* Adds the entry if new. Inserted at the beginning of the history entries list.
*/
private void addHistoryEntry(IJavaElement entry) {
if (fInputHistory.contains(entry)) {
fInputHistory.remove(entry);
}
fInputHistory.add(0, entry);
fHistoryDropDownAction.setEnabled(true);
}
private void updateHistoryEntries() {
for (int i= fInputHistory.size() - 1; i >= 0; i--) {
IJavaElement type= (IJavaElement) fInputHistory.get(i);
if (!type.exists()) {
fInputHistory.remove(i);
}
}
fHistoryDropDownAction.setEnabled(!fInputHistory.isEmpty());
}
/**
* Goes to the selected entry, without updating the order of history entries.
*/
public void gotoHistoryEntry(IJavaElement entry) {
if (fInputHistory.contains(entry)) {
updateInput(entry);
}
}
/**
* Gets all history entries.
*/
public IJavaElement[] getHistoryEntries() {
if (fInputHistory.size() > 0) {
updateHistoryEntries();
}
return (IJavaElement[]) fInputHistory.toArray(new IJavaElement[fInputHistory.size()]);
}
/**
* Sets the history entries
*/
public void setHistoryEntries(IJavaElement[] elems) {
fInputHistory.clear();
for (int i= 0; i < elems.length; i++) {
fInputHistory.add(elems[i]);
}
updateHistoryEntries();
}
/**
* Selects an member in the methods list or in the current hierarchy.
*/
public void selectMember(IMember member) {
fSelectInEditor= false;
if (member.getElementType() != IJavaElement.TYPE) {
Control methodControl= fMethodsViewer.getControl();
if (methodControl != null && !methodControl.isDisposed()) {
methodControl.setFocus();
}
fMethodsViewer.setSelection(new StructuredSelection(member), true);
} else {
Control viewerControl= getCurrentViewer().getControl();
if (viewerControl != null && !viewerControl.isDisposed()) {
viewerControl.setFocus();
}
if (!member.equals(fSelectedType)) {
getCurrentViewer().setSelection(new StructuredSelection(member), true);
}
}
fSelectInEditor= true;
}
/**
* @deprecated
*/
public IType getInput() {
if (fInputElement instanceof IType) {
return (IType) fInputElement;
}
return null;
}
/**
* Sets the input to a new type
* @deprecated
*/
public void setInput(IType type) {
setInputElement(type);
}
/**
* Returns the input element of the type hierarchy.
* Can be of type <code>IType</code> or <code>IPackageFragment</code>
*/
public IJavaElement getInputElement() {
return fInputElement;
}
/**
* Sets the input to a new element.
*/
public void setInputElement(IJavaElement element) {
if (element != null) {
if (element instanceof IMember) {
if (element.getElementType() != IJavaElement.TYPE) {
element= ((IMember) element).getDeclaringType();
}
if (!element.exists()) {
MessageDialog.openError(getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
} else {
int kind= element.getElementType();
if (kind != IJavaElement.JAVA_PROJECT && kind != IJavaElement.PACKAGE_FRAGMENT_ROOT && kind != IJavaElement.PACKAGE_FRAGMENT) {
element= null;
JavaPlugin.logErrorMessage("Invalid type hierarchy input type.");//$NON-NLS-1$
}
}
}
if (element != null && !element.equals(fInputElement)) {
addHistoryEntry(element);
}
updateInput(element);
}
/**
* Changes the input to a new type
*/
private void updateInput(IJavaElement inputElement) {
IJavaElement prevInput= fInputElement;
// Make sure the UI got repainted before we execute a long running
// operation. This can be removed if we refresh the hierarchy in a
// separate thread.
// Work-araound for http://dev.eclipse.org/bugs/show_bug.cgi?id=30881
processOutstandingEvents();
if (inputElement == null) {
clearInput();
} else {
fInputElement= inputElement;
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(inputElement, JavaPlugin.getActiveWorkbenchWindow());
// fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(inputElement, getSite().getWorkbenchWindow());
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.message")); //$NON-NLS-1$ //$NON-NLS-2$
clearInput();
return;
} catch (InterruptedException e) {
return;
}
if (inputElement.getElementType() != IJavaElement.TYPE) {
setView(VIEW_ID_TYPE);
}
// turn off member filtering
fSelectInEditor= false;
setMemberFilter(null);
internalSelectType(null, false); // clear selection
fIsEnableMemberFilter= false;
if (!inputElement.equals(prevInput)) {
updateHierarchyViewer(true);
}
IType root= getSelectableType(inputElement);
internalSelectType(root, true);
updateMethodViewer(root);
updateToolbarButtons();
updateTitle();
enableMemberFilter(false);
fPagebook.showPage(fTypeMethodsSplitter);
fSelectInEditor= true;
}
}
private void processOutstandingEvents() {
Display display= getDisplay();
if (display != null && !display.isDisposed())
display.update();
}
private void clearInput() {
fInputElement= null;
fHierarchyLifeCycle.freeHierarchy();
updateHierarchyViewer(false);
updateToolbarButtons();
}
/*
* @see IWorbenchPart#setFocus
*/
public void setFocus() {
fPagebook.setFocus();
}
/*
* @see IWorkbenchPart#dispose
*/
public void dispose() {
fHierarchyLifeCycle.freeHierarchy();
fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener);
fPaneLabelProvider.dispose();
if (fMethodsViewer != null) {
fMethodsViewer.dispose();
}
if (fPropertyChangeListener != null) {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
getSite().getPage().removePartListener(fPartListener);
if (fActionGroups != null)
fActionGroups.dispose();
if (fWorkingSetActionGroup != null) {
fWorkingSetActionGroup.dispose();
}
super.dispose();
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key == IShowInSource.class) {
return getShowInSource();
}
if (key == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_RES_NAV };
}
};
}
return super.getAdapter(key);
}
private Control createTypeViewerControl(Composite parent) {
fViewerbook= new PageBook(parent, SWT.NULL);
KeyListener keyListener= createKeyListener();
// Create the viewers
TypeHierarchyViewer superTypesViewer= new SuperTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
initializeTypesViewer(superTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUPERTYPES_VIEW);
TypeHierarchyViewer subTypesViewer= new SubTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
initializeTypesViewer(subTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUBTYPES_VIEW);
TypeHierarchyViewer vajViewer= new TraditionalHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
initializeTypesViewer(vajViewer, keyListener, IContextMenuConstants.TARGET_ID_HIERARCHY_VIEW);
fAllViewers= new TypeHierarchyViewer[3];
fAllViewers[VIEW_ID_SUPER]= superTypesViewer;
fAllViewers[VIEW_ID_SUB]= subTypesViewer;
fAllViewers[VIEW_ID_TYPE]= vajViewer;
int currViewerIndex;
try {
currViewerIndex= fDialogSettings.getInt(DIALOGSTORE_HIERARCHYVIEW);
if (currViewerIndex < 0 || currViewerIndex > 2) {
currViewerIndex= VIEW_ID_TYPE;
}
} catch (NumberFormatException e) {
currViewerIndex= VIEW_ID_TYPE;
}
fEmptyTypesViewer= new Label(fViewerbook, SWT.LEFT);
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setInput(fAllViewers[i]);
}
// force the update
fCurrentViewerIndex= -1;
setView(currViewerIndex);
return fViewerbook;
}
private KeyListener createKeyListener() {
return new KeyAdapter() {
public void keyReleased(KeyEvent event) {
if (event.stateMask == 0) {
if (event.keyCode == SWT.F5) {
ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy();
if (hierarchy != null) {
fHierarchyLifeCycle.typeHierarchyChanged(hierarchy);
doTypeHierarchyChangedOnViewers(null);
}
updateHierarchyViewer(false);
return;
} else if (event.character == SWT.DEL) {
if (fCCPActionGroup.getDeleteAction().isEnabled())
fCCPActionGroup.getDeleteAction().run();
return;
}
}
}
};
}
private void initializeTypesViewer(final TypeHierarchyViewer typesViewer, KeyListener keyListener, String cotextHelpId) {
typesViewer.getControl().setVisible(false);
typesViewer.getControl().addKeyListener(keyListener);
typesViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillTypesViewerContextMenu(typesViewer, menu);
}
}, cotextHelpId, getSite());
typesViewer.addPostSelectionChangedListener(fSelectionChangedListener);
typesViewer.setQualifiedTypeName(isShowQualifiedTypeNames());
typesViewer.setWorkingSetFilter(fWorkingSetActionGroup.getWorkingSetFilter());
}
private Control createMethodViewerControl(Composite parent) {
fMethodsViewer= new MethodsViewer(parent, fHierarchyLifeCycle, this);
fMethodsViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillMethodsViewerContextMenu(menu);
}
}, IContextMenuConstants.TARGET_ID_MEMBERS_VIEW, getSite());
fMethodsViewer.addPostSelectionChangedListener(fSelectionChangedListener);
Control control= fMethodsViewer.getTable();
control.addKeyListener(createKeyListener());
control.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
fSelectAllAction.setEnabled(true);
}
public void focusLost(FocusEvent e) {
fSelectAllAction.setEnabled(false);
}
});
return control;
}
private void initDragAndDrop() {
Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() };
int ops= DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK;
for (int i= 0; i < fAllViewers.length; i++) {
addDragAdapters(fAllViewers[i], ops, transfers);
addDropAdapters(fAllViewers[i], ops | DND.DROP_DEFAULT, transfers);
}
addDragAdapters(fMethodsViewer, ops, transfers);
//dnd on empty hierarchy
DropTarget dropTarget = new DropTarget(fNoHierarchyShownLabel, ops | DND.DROP_DEFAULT);
dropTarget.setTransfer(transfers);
dropTarget.addDropListener(new TypeHierarchyTransferDropAdapter(this, fAllViewers[0]));
}
private void addDropAdapters(AbstractTreeViewer viewer, int ops, Transfer[] transfers){
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new TypeHierarchyTransferDropAdapter(this, viewer)
};
viewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
}
private void addDragAdapters(StructuredViewer viewer, int ops, Transfer[] transfers) {
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(viewer)
};
viewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(viewer, dragListeners));
}
/**
* Returns the inner component in a workbench part.
* @see IWorkbenchPart#createPartControl(Composite)
*/
public void createPartControl(Composite container) {
fPagebook= new PageBook(container, SWT.NONE);
fWorkingSetActionGroup= new WorkingSetFilterActionGroup(JavaUI.ID_TYPE_HIERARCHY, container.getShell(), fPropertyChangeListener);
// page 1 of pagebook (viewers)
fTypeMethodsSplitter= new SashForm(fPagebook, SWT.VERTICAL);
fTypeMethodsSplitter.setVisible(false);
fTypeViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE);
Control typeViewerControl= createTypeViewerControl(fTypeViewerViewForm);
fTypeViewerViewForm.setContent(typeViewerControl);
fMethodViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE);
fTypeMethodsSplitter.setWeights(new int[] {35, 65});
Control methodViewerPart= createMethodViewerControl(fMethodViewerViewForm);
fMethodViewerViewForm.setContent(methodViewerPart);
fMethodViewerPaneLabel= new CLabel(fMethodViewerViewForm, SWT.NONE);
fMethodViewerViewForm.setTopLeft(fMethodViewerPaneLabel);
ToolBar methodViewerToolBar= new ToolBar(fMethodViewerViewForm, SWT.FLAT | SWT.WRAP);
fMethodViewerViewForm.setTopCenter(methodViewerToolBar);
// page 2 of pagebook (no hierarchy label)
fNoHierarchyShownLabel= new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP);
fNoHierarchyShownLabel.setText(TypeHierarchyMessages.getString("TypeHierarchyViewPart.empty")); //$NON-NLS-1$
initDragAndDrop();
MenuManager menu= new MenuManager();
menu.add(fFocusOnTypeAction);
fNoHierarchyShownLabel.setMenu(menu.createContextMenu(fNoHierarchyShownLabel));
fPagebook.showPage(fNoHierarchyShownLabel);
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);
if (fMemento != null) { // restore state before creating action
restoreLinkingEnabled(fMemento);
}
fToggleLinkingAction= new ToggleLinkingAction(this);
// set the filter menu items
IActionBars actionBars= getViewSite().getActionBars();
IMenuManager viewMenu= actionBars.getMenuManager();
for (int i= 0; i < fViewActions.length; i++) {
viewMenu.add(fViewActions[i]);
}
viewMenu.add(new Separator());
fWorkingSetActionGroup.contributeToMenu(viewMenu);
viewMenu.add(new Separator());
IMenuManager layoutSubMenu= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.layout.submenu")); //$NON-NLS-1$
viewMenu.add(layoutSubMenu);
for (int i= 0; i < fToggleOrientationActions.length; i++) {
layoutSubMenu.add(fToggleOrientationActions[i]);
}
viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
viewMenu.add(fShowQualifiedTypeNamesAction);
viewMenu.add(fToggleLinkingAction);
// fill the method viewer toolbar
ToolBarManager lowertbmanager= new ToolBarManager(methodViewerToolBar);
lowertbmanager.add(fEnableMemberFilterAction);
lowertbmanager.add(new Separator());
fMethodsViewer.contributeToToolBar(lowertbmanager);
lowertbmanager.update(true);
// selection provider
int nHierarchyViewers= fAllViewers.length;
Viewer[] trackedViewers= new Viewer[nHierarchyViewers + 1];
for (int i= 0; i < nHierarchyViewers; i++) {
trackedViewers[i]= fAllViewers[i];
}
trackedViewers[nHierarchyViewers]= fMethodsViewer;
fSelectionProviderMediator= new SelectionProviderMediator(trackedViewers);
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fSelectionProviderMediator.addSelectionChangedListener(new StatusBarUpdater(slManager));
getSite().setSelectionProvider(fSelectionProviderMediator);
getSite().getPage().addPartListener(fPartListener);
// see http://bugs.eclipse.org/bugs/show_bug.cgi?id=33657
IJavaElement input= null; //determineInputElement();
if (fMemento != null) {
restoreState(fMemento, input);
} else if (input != null) {
setInputElement(input);
} else {
setViewerVisibility(false);
}
WorkbenchHelp.setHelp(fPagebook, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW);
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
new NewWizardsActionGroup(this.getSite()),
new OpenEditorActionGroup(this),
new OpenViewActionGroup(this),
fCCPActionGroup= new CCPActionGroup(this),
new GenerateActionGroup(this),
new RefactorActionGroup(this),
new JavaSearchActionGroup(this)
});
fActionGroups.fillActionBars(actionBars);
fSelectAllAction= new SelectAllAction(fMethodsViewer);
actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), fSelectAllAction);
}
/**
* called from ToggleOrientationAction.
* @param orientation VIEW_ORIENTATION_SINGLE, VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL
*/
public void setOrientation(int orientation) {
if (fCurrentOrientation != orientation) {
boolean methodViewerNeedsUpdate= false;
if (fMethodViewerViewForm != null && !fMethodViewerViewForm.isDisposed()
&& fTypeMethodsSplitter != null && !fTypeMethodsSplitter.isDisposed()) {
if (orientation == VIEW_ORIENTATION_SINGLE) {
fMethodViewerViewForm.setVisible(false);
enableMemberFilter(false);
updateMethodViewer(null);
} else {
if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) {
fMethodViewerViewForm.setVisible(true);
methodViewerNeedsUpdate= true;
}
boolean horizontal= orientation == VIEW_ORIENTATION_HORIZONTAL;
fTypeMethodsSplitter.setOrientation(horizontal ? SWT.HORIZONTAL : SWT.VERTICAL);
}
updateMainToolbar(orientation);
fTypeMethodsSplitter.layout();
}
for (int i= 0; i < fToggleOrientationActions.length; i++) {
fToggleOrientationActions[i].setChecked(orientation == fToggleOrientationActions[i].getOrientation());
}
fCurrentOrientation= orientation;
if (methodViewerNeedsUpdate) {
updateMethodViewer(fSelectedType);
}
fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, orientation);
}
}
private void updateMainToolbar(int orientation) {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager tbmanager= actionBars.getToolBarManager();
if (orientation == VIEW_ORIENTATION_HORIZONTAL) {
clearMainToolBar(tbmanager);
ToolBar typeViewerToolBar= new ToolBar(fTypeViewerViewForm, SWT.FLAT | SWT.WRAP);
fillMainToolBar(new ToolBarManager(typeViewerToolBar));
fTypeViewerViewForm.setTopLeft(typeViewerToolBar);
} else {
fTypeViewerViewForm.setTopLeft(null);
fillMainToolBar(tbmanager);
}
}
private void fillMainToolBar(IToolBarManager tbmanager) {
tbmanager.removeAll();
tbmanager.add(fHistoryDropDownAction);
for (int i= 0; i < fViewActions.length; i++) {
tbmanager.add(fViewActions[i]);
}
tbmanager.update(false);
}
private void clearMainToolBar(IToolBarManager tbmanager) {
tbmanager.removeAll();
tbmanager.update(false);
}
/**
* Creates the context menu for the hierarchy viewers
*/
private void fillTypesViewerContextMenu(TypeHierarchyViewer viewer, IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, new Separator(GROUP_FOCUS));
// viewer entries
viewer.contributeToContextMenu(menu);
if (fFocusOnSelectionAction.canActionBeAdded())
menu.appendToGroup(GROUP_FOCUS, fFocusOnSelectionAction);
menu.appendToGroup(GROUP_FOCUS, fFocusOnTypeAction);
fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
fActionGroups.fillContextMenu(menu);
fActionGroups.setContext(null);
}
/**
* Creates the context menu for the method viewer
*/
private void fillMethodsViewerContextMenu(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
// viewer entries
fMethodsViewer.contributeToContextMenu(menu);
if (fSelectedType != null && fAddStubAction.init(fSelectedType, fMethodsViewer.getSelection())) {
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddStubAction);
}
fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
fActionGroups.fillContextMenu(menu);
fActionGroups.setContext(null);
}
/**
* Toggles between the empty viewer page and the hierarchy
*/
private void setViewerVisibility(boolean showHierarchy) {
if (showHierarchy) {
fViewerbook.showPage(getCurrentViewer().getControl());
} else {
fViewerbook.showPage(fEmptyTypesViewer);
}
}
/**
* Sets the member filter. <code>null</code> disables member filtering.
*/
private void setMemberFilter(IMember[] memberFilter) {
Assert.isNotNull(fAllViewers);
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setMemberFilter(memberFilter);
}
}
private IType getSelectableType(IJavaElement elem) {
if (elem.getElementType() != IJavaElement.TYPE) {
return null; //(IType) getCurrentViewer().getTreeRootType();
} else {
return (IType) elem;
}
}
private void internalSelectType(IMember elem, boolean reveal) {
TypeHierarchyViewer viewer= getCurrentViewer();
viewer.removePostSelectionChangedListener(fSelectionChangedListener);
viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal);
viewer.addPostSelectionChangedListener(fSelectionChangedListener);
}
/**
* When the input changed or the hierarchy pane becomes visible,
* <code>updateHierarchyViewer<code> brings up the correct view and refreshes
* the current tree
*/
private void updateHierarchyViewer(final boolean doExpand) {
if (fInputElement == null) {
fPagebook.showPage(fNoHierarchyShownLabel);
} else {
if (getCurrentViewer().containsElements() != null) {
Runnable runnable= new Runnable() {
public void run() {
getCurrentViewer().updateContent(doExpand); // refresh
}
};
BusyIndicator.showWhile(getDisplay(), runnable);
if (!isChildVisible(fViewerbook, getCurrentViewer().getControl())) {
setViewerVisibility(true);
}
} else {
fEmptyTypesViewer.setText(TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.nodecl", fInputElement.getElementName())); //$NON-NLS-1$
setViewerVisibility(false);
}
}
}
private void updateMethodViewer(final IType input) {
if (!fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) {
if (input == fMethodsViewer.getInput()) {
if (input != null) {
Runnable runnable= new Runnable() {
public void run() {
fMethodsViewer.refresh(); // refresh
}
};
BusyIndicator.showWhile(getDisplay(), runnable);
}
} else {
if (input != null) {
fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input));
fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input));
} else {
fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$
fMethodViewerPaneLabel.setImage(null);
}
Runnable runnable= new Runnable() {
public void run() {
fMethodsViewer.setInput(input); // refresh
}
};
BusyIndicator.showWhile(getDisplay(), runnable);
}
}
}
protected void doSelectionChanged(SelectionChangedEvent e) {
if (e.getSelectionProvider() == fMethodsViewer) {
methodSelectionChanged(e.getSelection());
} else {
typeSelectionChanged(e.getSelection());
}
}
private void methodSelectionChanged(ISelection sel) {
if (sel instanceof IStructuredSelection) {
List selected= ((IStructuredSelection)sel).toList();
int nSelected= selected.size();
if (fIsEnableMemberFilter) {
IMember[] memberFilter= null;
if (nSelected > 0) {
memberFilter= new IMember[nSelected];
selected.toArray(memberFilter);
}
setMemberFilter(memberFilter);
updateHierarchyViewer(true);
updateTitle();
internalSelectType(fSelectedType, true);
}
if (nSelected == 1 && fSelectInEditor) {
revealElementInEditor(selected.get(0), fMethodsViewer);
}
}
}
private void typeSelectionChanged(ISelection sel) {
if (sel instanceof IStructuredSelection) {
List selected= ((IStructuredSelection)sel).toList();
int nSelected= selected.size();
if (nSelected != 0) {
List types= new ArrayList(nSelected);
for (int i= nSelected-1; i >= 0; i--) {
Object elem= selected.get(i);
if (elem instanceof IType && !types.contains(elem)) {
types.add(elem);
}
}
if (types.size() == 1) {
fSelectedType= (IType) types.get(0);
updateMethodViewer(fSelectedType);
} else if (types.size() == 0) {
// method selected, no change
}
if (nSelected == 1 && fSelectInEditor) {
revealElementInEditor(selected.get(0), getCurrentViewer());
}
} else {
fSelectedType= null;
updateMethodViewer(null);
}
}
}
private void revealElementInEditor(Object elem, Viewer originViewer) {
// only allow revealing when the type hierarchy is the active page
// no revealing after selection events due to model changes
if (getSite().getPage().getActivePart() != this) {
return;
}
if (fSelectionProviderMediator.getViewerInFocus() != originViewer) {
return;
}
IEditorPart editorPart= EditorUtility.isOpenInEditor(elem);
if (editorPart != null && (elem instanceof IJavaElement)) {
getSite().getPage().removePartListener(fPartListener);
getSite().getPage().bringToTop(editorPart);
EditorUtility.revealInEditor(editorPart, (IJavaElement) elem);
getSite().getPage().addPartListener(fPartListener);
}
}
private Display getDisplay() {
if (fPagebook != null && !fPagebook.isDisposed()) {
return fPagebook.getDisplay();
}
return null;
}
private boolean isChildVisible(Composite pb, Control child) {
Control[] children= pb.getChildren();
for (int i= 0; i < children.length; i++) {
if (children[i] == child && children[i].isVisible())
return true;
}
return false;
}
private void updateTitle() {
String viewerTitle= getCurrentViewer().getTitle();
String tooltip;
String title;
if (fInputElement != null) {
String[] args= new String[] { viewerTitle, JavaElementLabels.getElementLabel(fInputElement, JavaElementLabels.ALL_DEFAULT) };
title= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.title", args); //$NON-NLS-1$
tooltip= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.tooltip", args); //$NON-NLS-1$
} else {
title= viewerTitle;
tooltip= viewerTitle;
}
setTitle(title);
setTitleToolTip(tooltip);
}
private void updateToolbarButtons() {
boolean isType= fInputElement instanceof IType;
for (int i= 0; i < fViewActions.length; i++) {
ToggleViewAction action= fViewActions[i];
if (action.getViewerIndex() == VIEW_ID_TYPE) {
action.setEnabled(fInputElement != null);
} else {
action.setEnabled(isType);
}
}
}
/**
* Sets the current view (see view id)
* called from ToggleViewAction. Must be called after creation of the viewpart.
*/
public void setView(int viewerIndex) {
Assert.isNotNull(fAllViewers);
if (viewerIndex < fAllViewers.length && fCurrentViewerIndex != viewerIndex) {
fCurrentViewerIndex= viewerIndex;
updateHierarchyViewer(true);
if (fInputElement != null) {
ISelection currSelection= getCurrentViewer().getSelection();
if (currSelection == null || currSelection.isEmpty()) {
internalSelectType(getSelectableType(fInputElement), false);
currSelection= getCurrentViewer().getSelection();
}
if (!fIsEnableMemberFilter) {
typeSelectionChanged(currSelection);
}
}
updateTitle();
fDialogSettings.put(DIALOGSTORE_HIERARCHYVIEW, viewerIndex);
getCurrentViewer().getTree().setFocus();
}
for (int i= 0; i < fViewActions.length; i++) {
ToggleViewAction action= fViewActions[i];
action.setChecked(fCurrentViewerIndex == action.getViewerIndex());
}
}
/**
* Gets the curret active view index.
*/
public int getViewIndex() {
return fCurrentViewerIndex;
}
private TypeHierarchyViewer getCurrentViewer() {
return fAllViewers[fCurrentViewerIndex];
}
/**
* called from EnableMemberFilterAction.
* Must be called after creation of the viewpart.
*/
public void enableMemberFilter(boolean on) {
if (on != fIsEnableMemberFilter) {
fIsEnableMemberFilter= on;
if (!on) {
IType methodViewerInput= (IType) fMethodsViewer.getInput();
setMemberFilter(null);
updateHierarchyViewer(true);
updateTitle();
if (methodViewerInput != null && getCurrentViewer().isElementShown(methodViewerInput)) {
// avoid that the method view changes content by selecting the previous input
internalSelectType(methodViewerInput, true);
} else if (fSelectedType != null) {
// choose a input that exists
internalSelectType(fSelectedType, true);
updateMethodViewer(fSelectedType);
}
} else {
methodSelectionChanged(fMethodsViewer.getSelection());
}
}
fEnableMemberFilterAction.setChecked(on);
}
/**
* called from ShowQualifiedTypeNamesAction. Must be called after creation
* of the viewpart.
*/
public void showQualifiedTypeNames(boolean on) {
if (fAllViewers == null) {
return;
}
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setQualifiedTypeName(on);
}
}
private boolean isShowQualifiedTypeNames() {
return fShowQualifiedTypeNamesAction.isChecked();
}
/**
* Called from ITypeHierarchyLifeCycleListener.
* Can be called from any thread
*/
protected void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) {
if (!fIsVisible) {
fNeedRefresh= true;
return;
}
if (fIsRefreshRunnablePosted) {
return;
}
Display display= getDisplay();
if (display != null) {
fIsRefreshRunnablePosted= true;
display.asyncExec(new Runnable() {
public void run() {
try {
if (fPagebook != null && !fPagebook.isDisposed()) {
doTypeHierarchyChangedOnViewers(changedTypes);
}
} finally {
fIsRefreshRunnablePosted= false;
}
}
});
}
}
protected void doTypeHierarchyChangedOnViewers(IType[] changedTypes) {
if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) {
clearInput();
} else {
if (changedTypes == null) {
// hierarchy change
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, getSite().getWorkbenchWindow());
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.message")); //$NON-NLS-1$ //$NON-NLS-2$
clearInput();
return;
} catch (InterruptedException e) {
return;
}
fMethodsViewer.refresh();
updateHierarchyViewer(false);
} else {
// elements in hierarchy modified
Object methodViewerInput= fMethodsViewer.getInput();
fMethodsViewer.refresh();
fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(methodViewerInput));
fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(methodViewerInput));
if (getCurrentViewer().isMethodFiltering()) {
if (changedTypes.length == 1) {
getCurrentViewer().refresh(changedTypes[0]);
} else {
updateHierarchyViewer(false);
}
} else {
getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } );
}
}
}
}
/*
* @see IViewPart#init
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
/*
* @see ViewPart#saveState(IMemento)
*/
public void saveState(IMemento memento) {
if (fPagebook == null) {
// part has not been created
if (fMemento != null) { //Keep the old state;
memento.putMemento(fMemento);
}
return;
}
if (fInputElement != null) {
String handleIndentifier= fInputElement.getHandleIdentifier();
if (fInputElement instanceof IType) {
ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy();
if (hierarchy != null && hierarchy.getSubtypes((IType) fInputElement).length > 1000) {
// for startup performance reasons do not try to recover huge hierarchies
handleIndentifier= null;
}
}
memento.putString(TAG_INPUT, handleIndentifier);
}
memento.putInteger(TAG_VIEW, getViewIndex());
memento.putInteger(TAG_ORIENTATION, fCurrentOrientation);
int weigths[]= fTypeMethodsSplitter.getWeights();
int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]);
memento.putInteger(TAG_RATIO, ratio);
ScrollBar bar= getCurrentViewer().getTree().getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putInteger(TAG_VERTICAL_SCROLL, position);
IJavaElement selection= (IJavaElement)((IStructuredSelection) getCurrentViewer().getSelection()).getFirstElement();
if (selection != null) {
memento.putString(TAG_SELECTION, selection.getHandleIdentifier());
}
fWorkingSetActionGroup.saveState(memento);
fMethodsViewer.saveState(memento);
saveLinkingEnabled(memento);
}
private void saveLinkingEnabled(IMemento memento) {
memento.putInteger(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, fLinkingEnabled ? 1 : 0);
}
/**
* Restores the type hierarchy settings from a memento.
*/
private void restoreState(IMemento memento, IJavaElement defaultInput) {
IJavaElement input= defaultInput;
fWorkingSetActionGroup.restoreState(memento);
String elementId= memento.getString(TAG_INPUT);
if (elementId != null) {
input= JavaCore.create(elementId);
if (input != null && !input.exists()) {
input= null;
}
if (!AllTypesCache.isIndexUpToDate()) {
input= null;
}
}
setInputElement(input);
Integer viewerIndex= memento.getInteger(TAG_VIEW);
if (viewerIndex != null) {
setView(viewerIndex.intValue());
}
Integer orientation= memento.getInteger(TAG_ORIENTATION);
if (orientation != null) {
setOrientation(orientation.intValue());
}
Integer ratio= memento.getInteger(TAG_RATIO);
if (ratio != null) {
fTypeMethodsSplitter.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue() });
}
ScrollBar bar= getCurrentViewer().getTree().getVerticalBar();
if (bar != null) {
Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL);
if (vScroll != null) {
bar.setSelection(vScroll.intValue());
}
}
//String selectionId= memento.getString(TAG_SELECTION);
// do not restore type hierarchy contents
// if (selectionId != null) {
// IJavaElement elem= JavaCore.create(selectionId);
// if (getCurrentViewer().isElementShown(elem) && elem instanceof IMember) {
// internalSelectType((IMember)elem, false);
// }
// }
fMethodsViewer.restoreState(memento);
}
private void restoreLinkingEnabled(IMemento memento) {
Integer val= memento.getInteger(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR);
if (val != null) {
fLinkingEnabled= val.intValue() != 0;
}
}
/**
* view part becomes visible
*/
protected void visibilityChanged(boolean isVisible) {
fIsVisible= isVisible;
if (isVisible && fNeedRefresh) {
doTypeHierarchyChangedOnViewers(null);
}
fNeedRefresh= false;
}
/**
* Link selection to active editor.
*/
protected void editorActivated(IEditorPart editor) {
if (!isLinkingEnabled()) {
return;
}
if (fInputElement == null) {
// no type hierarchy shown
return;
}
IJavaElement elem= (IJavaElement)editor.getEditorInput().getAdapter(IJavaElement.class);
try {
TypeHierarchyViewer currentViewer= getCurrentViewer();
if (elem instanceof IClassFile) {
IType type= ((IClassFile)elem).getType();
if (currentViewer.isElementShown(type)) {
internalSelectType(type, true);
updateMethodViewer(type);
}
} else if (elem instanceof ICompilationUnit) {
IType[] allTypes= ((ICompilationUnit)elem).getAllTypes();
for (int i= 0; i < allTypes.length; i++) {
if (currentViewer.isElementShown(allTypes[i])) {
internalSelectType(allTypes[i], true);
updateMethodViewer(allTypes[i]);
return;
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return fInputElement;
}
/**
* Returns the <code>IShowInSource</code> for this view.
*/
protected IShowInSource getShowInSource() {
return new IShowInSource() {
public ShowInContext getShowInContext() {
return new ShowInContext(
null,
getSite().getSelectionProvider().getSelection());
}
};
}
boolean isLinkingEnabled() {
return fLinkingEnabled;
}
public void setLinkingEnabled(boolean enabled) {
fLinkingEnabled= enabled;
PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, enabled);
if (enabled) {
IEditorPart editor = getSite().getPage().getActiveEditor();
if (editor != null) {
editorActivated(editor);
}
}
}
public void clearNeededRefresh() {
fNeedRefresh= false;
}
}
|
54,102 |
Bug 54102 Bad initial focus on 'New Code Formatter Profile' dialog
|
I200303040800 windows>preferences>java>code formatter>New... The focus is set on the checkbox 'open the edit dialog now', it should be on the text field 'Profile name'.
|
resolved fixed
|
d9c0d75
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-09T10:10:52Z | 2004-03-08T23:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/CreateProfileDialog.java
|
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.preferences.formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusDialog;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
import org.eclipse.jdt.internal.ui.preferences.formatter.ProfileManager.Profile;
/**
* The dialog to create a new profile.
*/
public class CreateProfileDialog extends StatusDialog {
private static final String PREF_OPEN_EDIT_DIALOG= JavaUI.ID_PLUGIN + ".codeformatter.create_profile_dialog.open_edit"; //$NON-NLS-1$
private Text fNameText;
private Combo fProfileCombo;
private Button fEditCheckbox;
private final static StatusInfo fOk= new StatusInfo();
private final static StatusInfo fEmpty= new StatusInfo(IStatus.ERROR, FormatterMessages.getString("CreateProfileDialog.status.message.profile_name_is_empty")); //$NON-NLS-1$
private final static StatusInfo fDuplicate= new StatusInfo(IStatus.ERROR, FormatterMessages.getString("CreateProfileDialog.status.message.profile_with_this_name_already_exists")); //$NON-NLS-1$;
private final ProfileManager fProfileManager;
private final List fSortedProfiles;
private final String [] fSortedNames;
private CustomProfile fCreatedProfile;
protected boolean fOpenEditDialog;
/**
* Create a new CreateProfileDialog.
*/
public CreateProfileDialog(Shell parentShell, ProfileManager profileManager) {
super(parentShell);
fProfileManager= profileManager;
fSortedProfiles= fProfileManager.getSortedProfiles();
fSortedNames= fProfileManager.getSortedNames();
}
public void create() {
super.create();
setTitle(FormatterMessages.getString("CreateProfileDialog.dialog.title")); //$NON-NLS-1$
}
public Control createDialogArea(Composite parent) {
final int numColumns= 2;
GridData gd;
final GridLayout layout= new GridLayout(numColumns, false);
layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
final Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(layout);
// Create "Profile name:" label
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = numColumns;
gd.widthHint= convertWidthInCharsToPixels(60);
final Label nameLabel = new Label(composite, SWT.WRAP);
nameLabel.setText(FormatterMessages.getString("CreateProfileDialog.profile_name.label.text")); //$NON-NLS-1$
nameLabel.setLayoutData(gd);
// Create text field to enter name
gd = new GridData( GridData.FILL_HORIZONTAL);
gd.horizontalSpan= numColumns;
fNameText= new Text(composite, SWT.SINGLE | SWT.BORDER);
fNameText.setLayoutData(gd);
fNameText.addModifyListener( new ModifyListener() {
public void modifyText(ModifyEvent e) {
doValidation();
}
});
// Create "Initialize settings ..." label
gd = new GridData();
gd.horizontalSpan = numColumns;
Label profileLabel = new Label(composite, SWT.WRAP);
profileLabel.setText(FormatterMessages.getString("CreateProfileDialog.base_profile.label.text")); //$NON-NLS-1$
profileLabel.setLayoutData(gd);
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan= numColumns;
fProfileCombo = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY);
fProfileCombo.setLayoutData(gd);
// "Open the edit dialog now" checkbox
gd= new GridData();
gd.horizontalSpan= numColumns;
fEditCheckbox= new Button(composite, SWT.CHECK);
fEditCheckbox.setText(FormatterMessages.getString("CreateProfileDialog.open_edit_dialog.checkbox.text")); //$NON-NLS-1$
fEditCheckbox.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
fOpenEditDialog= ((Button)e.widget).getSelection();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
final IDialogSettings dialogSettings= JavaPlugin.getDefault().getDialogSettings();//.get(PREF_OPEN_EDIT_DIALOG);
if (dialogSettings.get(PREF_OPEN_EDIT_DIALOG) != null) {
fOpenEditDialog= dialogSettings.getBoolean(PREF_OPEN_EDIT_DIALOG);
} else {
fOpenEditDialog= true;
}
fEditCheckbox.setSelection(fOpenEditDialog);
fProfileCombo.setItems(fSortedNames);
fProfileCombo.setText(fProfileManager.getProfile(ProfileManager.DEFAULT_PROFILE).getName());
updateStatus(fEmpty);
applyDialogFont(composite);
return composite;
}
/**
* Validate the current settings
*/
protected void doValidation() {
final String name= fNameText.getText().trim();
if (fProfileManager.containsName(name)) {
updateStatus(fDuplicate);
return;
}
if (name.length() == 0) {
updateStatus(fEmpty);
return;
}
updateStatus(fOk);
}
protected void okPressed() {
if (!getStatus().isOK())
return;
JavaPlugin.getDefault().getDialogSettings().put(PREF_OPEN_EDIT_DIALOG, fOpenEditDialog);
final Map baseSettings= new HashMap(((Profile)fSortedProfiles.get(fProfileCombo.getSelectionIndex())).getSettings());
final String profileName= fNameText.getText();
fCreatedProfile= new CustomProfile(profileName, baseSettings, ProfileVersioner.CURRENT_VERSION);
fProfileManager.addProfile(fCreatedProfile);
super.okPressed();
}
public final CustomProfile getCreatedProfile() {
return fCreatedProfile;
}
public final boolean openEditDialog() {
return fOpenEditDialog;
}
}
|
53,873 |
Bug 53873 [Call Hierarchy] the name filter pattern should ignore whitespaces
|
when adding spaces after or vefore a comma for instance the filter doesnt work anymore properly - ie. doesnt apply the rest of the filter patterns after the space(s)
|
resolved fixed
|
f36aa89
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-09T20:39:46Z | 2004-03-05T15:20:00Z |
org.eclipse.jdt.ui/core
| |
53,873 |
Bug 53873 [Call Hierarchy] the name filter pattern should ignore whitespaces
|
when adding spaces after or vefore a comma for instance the filter doesnt work anymore properly - ie. doesnt apply the rest of the filter patterns after the space(s)
|
resolved fixed
|
f36aa89
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-09T20:39:46Z | 2004-03-05T15:20:00Z |
extension/org/eclipse/jdt/internal/corext/callhierarchy/CallHierarchy.java
| |
54,121 |
Bug 54121 BLE while file->revert (during selection restore)
|
The computed newLine in RememberedOffset#getOffset() can be before the start or after the end of the document. TestCase: - saved file: public class Test { public void foo() { } } - edited document (| is the caret): public class Test { public void foo() { | } } - now revert -> BLE The correct fix is to check whether newLine is valid in the current document. org.eclipse.jface.text.BadLocationException at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.jface.text.BadLocationException.<init>(BadLocationException.java:25) at org.eclipse.jface.text.AbstractLineTracker.getLineLength(AbstractLineTracker.java) at org.eclipse.jface.text.AbstractDocument.getLineLength(AbstractDocument.java) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$RememberedOffset.getOffset(CompilationUnitEditor.java:804) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$RememberedSelection.restore(CompilationUnitEditor.java:690) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.restoreSelection(CompilationUnitEditor.java:1558) at org.eclipse.ui.texteditor.AbstractTextEditor$4.run(AbstractTextEditor.java:299) at org.eclipse.ui.texteditor.AbstractTextEditor$ElementStateListener.execute(AbstractTextEditor.java:385) at org.eclipse.ui.texteditor.AbstractTextEditor$ElementStateListener.elementContentReplaced(AbstractTextEditor.java:302) at org.eclipse.ui.editors.text.TextFileDocumentProvider$FileBufferListener.bufferContentReplaced(TextFileDocumentProvider.java:214) at org.eclipse.core.internal.filebuffers.TextFileBufferManager.fireBufferContentReplaced(TextFileBufferManager.java:242) at org.eclipse.core.internal.filebuffers.ResourceTextFileBuffer.revert(ResourceTextFileBuffer.java:169) at org.eclipse.ui.editors.text.TextFileDocumentProvider$1.execute(TextFileDocumentProvider.java:577) at org.eclipse.ui.editors.text.TextFileDocumentProvider$DocumentProviderOperation.run(TextFileDocumentProvider.java:93) at org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation.execute(WorkspaceModifyDelegatingOperation.java:67) at org.eclipse.ui.actions.WorkspaceModifyOperation$1.run(WorkspaceModifyOperation.java:91) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1567) at org.eclipse.ui.actions.WorkspaceModifyOperation.run(WorkspaceModifyOperation.java:105) 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:391) at org.eclipse.ui.editors.text.TextFileDocumentProvider.resetDocument(TextFileDocumentProvider.java:590) at org.eclipse.ui.texteditor.AbstractTextEditor.performRevert(AbstractTextEditor.java:3253) at org.eclipse.ui.texteditor.AbstractTextEditor.doRevertToSaved(AbstractTextEditor.java:3236) at org.eclipse.ui.texteditor.StatusTextEditor.doRevertToSaved(StatusTextEditor.java:183) at org.eclipse.ui.texteditor.RevertToSavedAction.run(RevertToSavedAction.java:47) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.ui.actions.RetargetAction.runWithEvent(RetargetAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:550) at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:502) at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:435) 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:1509) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1480) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:257) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:48) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:260) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:173) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:106) 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:305) at org.eclipse.core.launcher.Main.run(Main.java:745) at org.eclipse.core.launcher.Main.main(Main.java:713)
|
resolved fixed
|
93f3797
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-10T10:08:06Z | 2004-03-09T08:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditor.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.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import org.eclipse.core.resources.IFile;
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.Preferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IAutoEditStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentExtension;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.ILineTracker;
import org.eclipse.jface.text.IPositionUpdater;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.IWidgetTokenKeeper;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistantExtension;
import org.eclipse.jface.text.link.ExclusivePositionUpdater;
import org.eclipse.jface.text.link.ILinkedListener;
import org.eclipse.jface.text.link.LinkedEnvironment;
import org.eclipse.jface.text.link.LinkedPositionGroup;
import org.eclipse.jface.text.link.LinkedUIControl;
import org.eclipse.jface.text.link.LinkedUIControl.ExitFlags;
import org.eclipse.jface.text.link.LinkedUIControl.IExitPolicy;
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.SourceViewerConfiguration;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.editors.text.IStorageDocumentProvider;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.ContentAssistAction;
import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.texteditor.link.EditorHistoryUpdater;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
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.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
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.AddBlockCommentAction;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.IndentAction;
import org.eclipse.jdt.internal.ui.actions.RemoveBlockCommentAction;
import org.eclipse.jdt.internal.ui.compare.LocalHistoryActionGroup;
import org.eclipse.jdt.internal.ui.text.ContentAssistPreference;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionAssistant;
import org.eclipse.jdt.internal.ui.text.java.IReconcilingParticipant;
import org.eclipse.jdt.internal.ui.text.java.SmartSemicolonAutoEditStrategy;
/**
* Java specific text editor.
*/
public class CompilationUnitEditor extends JavaEditor implements IReconcilingParticipant {
/**
* Text operation code for requesting correction assist to show correction
* proposals for the current position.
*/
public static final int CORRECTIONASSIST_PROPOSALS= 50;
/**
* Text operation code for requesting common prefix completion.
*/
public static final int CONTENTASSIST_COMPLETE_PREFIX= 60;
interface ITextConverter {
void customizeDocumentCommand(IDocument document, DocumentCommand command);
}
class AdaptedSourceViewer extends JavaSourceViewer {
private List fTextConverters;
private boolean fIgnoreTextConverters= false;
private JavaCorrectionAssistant fCorrectionAssistant;
public AdaptedSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles) {
super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles);
}
public IContentAssistant getContentAssistant() {
return fContentAssistant;
}
/*
* @see ITextOperationTarget#doOperation(int)
*/
public void doOperation(int operation) {
if (getTextWidget() == null)
return;
switch (operation) {
case CONTENTASSIST_PROPOSALS:
String msg= fContentAssistant.showPossibleCompletions();
setStatusLineErrorMessage(msg);
return;
case CORRECTIONASSIST_PROPOSALS:
msg= fCorrectionAssistant.showPossibleCompletions();
setStatusLineErrorMessage(msg);
return;
case UNDO:
fIgnoreTextConverters= true;
break;
case REDO:
fIgnoreTextConverters= true;
break;
case CONTENTASSIST_COMPLETE_PREFIX:
if (fContentAssistant instanceof IContentAssistantExtension) {
msg= ((IContentAssistantExtension) fContentAssistant).completePrefix();
setStatusLineErrorMessage(msg);
return;
} else
break;
}
super.doOperation(operation);
}
/*
* @see ITextOperationTarget#canDoOperation(int)
*/
public boolean canDoOperation(int operation) {
if (operation == CORRECTIONASSIST_PROPOSALS)
return isEditable();
else if (operation == CONTENTASSIST_COMPLETE_PREFIX)
return isEditable();
return super.canDoOperation(operation);
}
/**
* @inheritDoc
* @since 3.0
*/
public void unconfigure() {
if (fCorrectionAssistant != null) {
fCorrectionAssistant.uninstall();
fCorrectionAssistant= null;
}
super.unconfigure();
}
public void insertTextConverter(ITextConverter textConverter, int index) {
throw new UnsupportedOperationException();
}
public void addTextConverter(ITextConverter textConverter) {
if (fTextConverters == null) {
fTextConverters= new ArrayList(1);
fTextConverters.add(textConverter);
} else if (!fTextConverters.contains(textConverter))
fTextConverters.add(textConverter);
}
public void removeTextConverter(ITextConverter textConverter) {
if (fTextConverters != null) {
fTextConverters.remove(textConverter);
if (fTextConverters.size() == 0)
fTextConverters= null;
}
}
/*
* @see TextViewer#customizeDocumentCommand(DocumentCommand)
*/
protected void customizeDocumentCommand(DocumentCommand command) {
super.customizeDocumentCommand(command);
if (!fIgnoreTextConverters && fTextConverters != null) {
for (Iterator e = fTextConverters.iterator(); e.hasNext();)
((ITextConverter) e.next()).customizeDocumentCommand(getDocument(), command);
}
fIgnoreTextConverters= false;
}
// http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
public void updateIndentationPrefixes() {
SourceViewerConfiguration configuration= getSourceViewerConfiguration();
String[] types= configuration.getConfiguredContentTypes(this);
for (int i= 0; i < types.length; i++) {
String[] prefixes= configuration.getIndentPrefixes(this, types[i]);
if (prefixes != null && prefixes.length > 0)
setIndentPrefixes(prefixes, types[i]);
}
}
/*
* @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
*/
public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
if (WorkbenchHelp.isContextHelpDisplayed())
return false;
return super.requestWidgetToken(requester);
}
/*
* @see IWidgetTokenOwnerExtension#requestWidgetToken(IWidgetTokenKeeper, int)
* @since 3.0
*/
public boolean requestWidgetToken(IWidgetTokenKeeper requester, int priority) {
if (WorkbenchHelp.isContextHelpDisplayed())
return false;
return super.requestWidgetToken(requester, priority);
}
/*
* @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
*/
public void configure(SourceViewerConfiguration configuration) {
super.configure(configuration);
fCorrectionAssistant= new JavaCorrectionAssistant(CompilationUnitEditor.this);
fCorrectionAssistant.install(this);
IAutoEditStrategy smartSemi= new SmartSemicolonAutoEditStrategy(IJavaPartitions.JAVA_PARTITIONING);
prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE);
}
}
static class TabConverter implements ITextConverter {
private int fTabRatio;
private ILineTracker fLineTracker;
public TabConverter() {
}
public void setNumberOfSpacesPerTab(int ratio) {
fTabRatio= ratio;
}
public void setLineTracker(ILineTracker lineTracker) {
fLineTracker= lineTracker;
}
private int insertTabString(StringBuffer buffer, int offsetInLine) {
if (fTabRatio == 0)
return 0;
int remainder= offsetInLine % fTabRatio;
remainder= fTabRatio - remainder;
for (int i= 0; i < remainder; i++)
buffer.append(' ');
return remainder;
}
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
String text= command.text;
if (text == null)
return;
int index= text.indexOf('\t');
if (index > -1) {
StringBuffer buffer= new StringBuffer();
fLineTracker.set(command.text);
int lines= fLineTracker.getNumberOfLines();
try {
for (int i= 0; i < lines; i++) {
int offset= fLineTracker.getLineOffset(i);
int endOffset= offset + fLineTracker.getLineLength(i);
String line= text.substring(offset, endOffset);
int position= 0;
if (i == 0) {
IRegion firstLine= document.getLineInformationOfOffset(command.offset);
position= command.offset - firstLine.getOffset();
}
int length= line.length();
for (int j= 0; j < length; j++) {
char c= line.charAt(j);
if (c == '\t') {
position += insertTabString(buffer, position);
} else {
buffer.append(c);
++ position;
}
}
}
command.text= buffer.toString();
} catch (BadLocationException x) {
}
}
}
}
private class ExitPolicy implements IExitPolicy {
final char fExitCharacter;
final char fEscapeCharacter;
final Stack fStack;
final int fSize;
public ExitPolicy(char exitCharacter, char escapeCharacter, Stack stack) {
fExitCharacter= exitCharacter;
fEscapeCharacter= escapeCharacter;
fStack= stack;
fSize= fStack.size();
}
/*
* @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int)
*/
public ExitFlags doExit(LinkedEnvironment environment, VerifyEvent event, int offset, int length) {
if (event.character == fExitCharacter) {
if (fSize == fStack.size() && !isMasked(offset)) {
BracketLevel level= (BracketLevel) fStack.peek();
if (level.fFirstPosition.offset > offset || level.fSecondPosition.offset < offset)
return null;
if (level.fSecondPosition.offset == offset && length == 0)
// don't enter the character if if its the closing peer
return new ExitFlags(ILinkedListener.UPDATE_CARET, false);
else
return new ExitFlags(ILinkedListener.UPDATE_CARET, true);
}
}
return null;
}
private boolean isMasked(int offset) {
IDocument document= getSourceViewer().getDocument();
try {
return fEscapeCharacter == document.getChar(offset - 1);
} catch (BadLocationException e) {
}
return false;
}
}
private static class BracketLevel {
int fOffset;
int fLength;
LinkedUIControl fEditor;
Position fFirstPosition;
Position fSecondPosition;
}
private class BracketInserter implements VerifyKeyListener, ILinkedListener {
private boolean fCloseBrackets= true;
private boolean fCloseStrings= true;
private final String CATEGORY= toString();
private IPositionUpdater fUpdater= new ExclusivePositionUpdater(CATEGORY);
private Stack fBracketLevelStack= new Stack();
public void setCloseBracketsEnabled(boolean enabled) {
fCloseBrackets= enabled;
}
public void setCloseStringsEnabled(boolean enabled) {
fCloseStrings= enabled;
}
private boolean hasIdentifierToTheRight(IDocument document, int offset) {
try {
int end= offset;
IRegion endLine= document.getLineInformationOfOffset(end);
int maxEnd= endLine.getOffset() + endLine.getLength();
while (end != maxEnd && Character.isWhitespace(document.getChar(end)))
++end;
return end != maxEnd && Character.isJavaIdentifierPart(document.getChar(end));
} catch (BadLocationException e) {
// be conservative
return true;
}
}
private boolean hasIdentifierToTheLeft(IDocument document, int offset) {
try {
int start= offset;
IRegion startLine= document.getLineInformationOfOffset(start);
int minStart= startLine.getOffset();
while (start != minStart && Character.isWhitespace(document.getChar(start - 1)))
--start;
return start != minStart && Character.isJavaIdentifierPart(document.getChar(start - 1));
} catch (BadLocationException e) {
return true;
}
}
private boolean hasCharacterToTheRight(IDocument document, int offset, char character) {
try {
int end= offset;
IRegion endLine= document.getLineInformationOfOffset(end);
int maxEnd= endLine.getOffset() + endLine.getLength();
while (end != maxEnd && Character.isWhitespace(document.getChar(end)))
++end;
return end != maxEnd && document.getChar(end) == character;
} catch (BadLocationException e) {
// be conservative
return true;
}
}
/*
* @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
*/
public void verifyKey(VerifyEvent event) {
if (!event.doit || getInsertMode() != SMART_INSERT)
return;
final ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
final Point selection= sourceViewer.getSelectedRange();
final int offset= selection.x;
final int length= selection.y;
switch (event.character) {
case '(':
if (hasCharacterToTheRight(document, offset + length, '('))
return;
// fall through
case '[':
if (!fCloseBrackets)
return;
if (hasIdentifierToTheRight(document, offset + length))
return;
// fall through
case '\'':
if (event.character == '\'') {
if (!fCloseStrings)
return;
if (hasIdentifierToTheLeft(document, offset) || hasIdentifierToTheRight(document, offset + length))
return;
}
// fall through
case '"':
if (event.character == '"') {
if (!fCloseStrings)
return;
if (hasIdentifierToTheLeft(document, offset) || hasIdentifierToTheRight(document, offset + length))
return;
}
try {
ITypedRegion partition= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, offset);
if (! IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) && partition.getOffset() != offset)
return;
if (!validateEditorInputState())
return;
final char character= event.character;
final char closingCharacter= getPeerCharacter(character);
final StringBuffer buffer= new StringBuffer();
buffer.append(character);
buffer.append(closingCharacter);
document.replace(offset, length, buffer.toString());
BracketLevel level= new BracketLevel();
fBracketLevelStack.push(level);
LinkedPositionGroup group= new LinkedPositionGroup();
group.createPosition(document, offset + 1, 0);
LinkedEnvironment env= new LinkedEnvironment();
env.addLinkedListener(this);
env.addGroup(group);
env.forceInstall();
level.fOffset= offset;
level.fLength= 2;
// set up position tracking for our magic peers
if (fBracketLevelStack.size() == 1) {
document.addPositionCategory(CATEGORY);
document.addPositionUpdater(fUpdater);
}
level.fFirstPosition= new Position(offset, 1);
level.fSecondPosition= new Position(offset + 1, 1);
document.addPosition(CATEGORY, level.fFirstPosition);
document.addPosition(CATEGORY, level.fSecondPosition);
level.fEditor= new LinkedUIControl(env, sourceViewer);
level.fEditor.setPositionListener(new EditorHistoryUpdater());
level.fEditor.setExitPolicy(new ExitPolicy(closingCharacter, getEscapeCharacter(closingCharacter), fBracketLevelStack));
level.fEditor.setExitPosition(sourceViewer, offset + 2, 0, Integer.MAX_VALUE);
level.fEditor.setCyclingMode(LinkedUIControl.CYCLE_NEVER);
level.fEditor.enter();
IRegion newSelection= level.fEditor.getSelectedRegion();
sourceViewer.setSelectedRange(newSelection.getOffset(), newSelection.getLength());
event.doit= false;
} catch (BadLocationException e) {
JavaPlugin.log(e);
} catch (BadPositionCategoryException e) {
JavaPlugin.log(e);
}
break;
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#left(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment, int)
*/
public void left(LinkedEnvironment environment, int flags) {
final BracketLevel level= (BracketLevel) fBracketLevelStack.pop();
if (flags != ILinkedListener.EXTERNAL_MODIFICATION)
return;
// remove brackets
final ISourceViewer sourceViewer= getSourceViewer();
final IDocument document= sourceViewer.getDocument();
if (document instanceof IDocumentExtension) {
IDocumentExtension extension= (IDocumentExtension) document;
extension.registerPostNotificationReplace(null, new IDocumentExtension.IReplace() {
public void perform(IDocument d, IDocumentListener owner) {
if ((level.fFirstPosition.isDeleted || level.fFirstPosition.length == 0) && !level.fSecondPosition.isDeleted && level.fSecondPosition.offset == level.fFirstPosition.offset) {
try {
document.replace(level.fSecondPosition.offset, level.fSecondPosition.length, null);
} catch (BadLocationException e) {
}
}
if (fBracketLevelStack.size() == 0) {
document.removePositionUpdater(fUpdater);
try {
document.removePositionCategory(CATEGORY);
} catch (BadPositionCategoryException e) {
}
}
}
});
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#suspend(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment)
*/
public void suspend(LinkedEnvironment environment) {
}
/*
* @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#resume(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment, int)
*/
public void resume(LinkedEnvironment environment, int flags) {
}
}
/**
* Remembers data related to the current selection to be able to
* restore it later.
*
* @since 3.0
*/
private class RememberedSelection {
/** The remembered selection start. */
private RememberedOffset fStartOffset= new RememberedOffset();
/** The remembered selection end. */
private RememberedOffset fEndOffset= new RememberedOffset();
/**
* Remember current selection.
*/
public void remember() {
/* https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257
* This method may be called inside an async call posted
* to the UI thread, so protect against intermediate disposal
* of the editor.
*/
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
IRegion selection= getSignedSelection(viewer);
int startOffset= selection.getOffset();
int endOffset= startOffset + selection.getLength();
fStartOffset.setOffset(startOffset);
fEndOffset.setOffset(endOffset);
}
}
/**
* Restore remembered selection.
*/
public void restore() {
/* https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257
* This method may be called inside an async call posted
* to the UI thread, so protect against intermediate disposal
* of the editor.
*/
if (getSourceViewer() == null)
return;
try {
int startOffset= fStartOffset.getOffset();
int endOffset= fEndOffset.getOffset();
if (startOffset == -1)
startOffset= endOffset; // fallback to carret offset
if (endOffset == -1)
endOffset= startOffset; // fallback to other offset
IJavaElement element;
if (endOffset == -1) {
// fallback to element selection
element= fEndOffset.getElement();
if (element == null)
element= fStartOffset.getElement();
if (element != null)
setSelection(element);
return;
}
if (isValidSelection(startOffset, endOffset - startOffset))
selectAndReveal(startOffset, endOffset - startOffset);
} finally {
fStartOffset.clear();
fEndOffset.clear();
}
}
private boolean isValidSelection(int offset, int length) {
IDocumentProvider provider= getDocumentProvider();
if (provider != null) {
IDocument document= provider.getDocument(getEditorInput());
if (document != null) {
int end= offset + length;
int documentLength= document.getLength();
return 0 <= offset && offset <= documentLength && 0 <= end && end <= documentLength;
}
}
return false;
}
}
/**
* Remembers additional data for a given
* offset to be able restore it later.
*
* @since 3.0
*/
private class RememberedOffset {
/** Remembered line for the given offset */
private int fLine;
/** Remembered column for the given offset*/
private int fColumn;
/** Remembered Java element for the given offset*/
private IJavaElement fElement;
/** Remembered Java element line for the given offset*/
private int fElementLine;
/**
* Store visual properties of the given offset.
*
* @param offset Offset in the document
*/
public void setOffset(int offset) {
try {
IDocument document= getSourceViewer().getDocument();
fLine= document.getLineOfOffset(offset);
fColumn= offset - document.getLineOffset(fLine);
fElement= getElementAt(offset, true);
fElementLine= -1;
if (fElement instanceof IMember) {
ISourceRange range= ((IMember) fElement).getNameRange();
if (range != null)
fElementLine= document.getLineOfOffset(range.getOffset());
}
if (fElementLine == -1)
fElementLine= document.getLineOfOffset(getOffset(fElement));
} catch (BadLocationException e) {
// should not happen
JavaPlugin.log(e);
clear();
} catch (JavaModelException e) {
// should not happen
JavaPlugin.log(e.getStatus());
clear();
}
}
/**
* Return offset recomputed from stored visual properties.
*
* @return Offset in the document
*/
public int getOffset() {
try {
IJavaElement newElement= getElement();
if (newElement == null)
return -1;
IDocument document= getSourceViewer().getDocument();
int newElementLine= -1;
if (newElement instanceof IMember) {
ISourceRange range= ((IMember) newElement).getNameRange();
if (range != null)
newElementLine= document.getLineOfOffset(range.getOffset());
}
if (newElementLine == -1)
newElementLine= document.getLineOfOffset(getOffset(newElement));
if (newElementLine == -1)
return -1;
int newLine= fLine + newElementLine - fElementLine;
int maxColumn= document.getLineLength(newLine);
String lineDelimiter= document.getLineDelimiter(newLine);
if (lineDelimiter != null)
maxColumn= maxColumn - lineDelimiter.length();
int offset;
if (fColumn > maxColumn)
offset= document.getLineOffset(newLine) + maxColumn;
else
offset= document.getLineOffset(newLine) + fColumn;
if (!containsOffset(newElement, offset) && (offset == 0 || !containsOffset(newElement, offset - 1)))
return -1;
return offset;
} catch (BadLocationException e) {
// should not happen
JavaPlugin.log(e);
return -1;
} catch (JavaModelException e) {
// should not happen
JavaPlugin.log(e.getStatus());
return -1;
}
}
/**
* Return Java element recomputed from stored visual properties.
*
* @return Java element
*/
public IJavaElement getElement() {
if (fElement == null)
return null;
return findElement(fElement);
}
/**
* Clears the stored position
*/
public void clear() {
fLine= -1;
fColumn= -1;
fElement= null;
fElementLine= -1;
}
/**
* Does the given Java element contain the given offset?
* @param element Java element
* @param offset Offset
* @return <code>true</code> iff the Java element contains the offset
*/
private boolean containsOffset(IJavaElement element, int offset) {
int elementOffset= getOffset(element);
int elementLength= getLength(element);
return (elementOffset > -1 && elementLength > -1) ? (offset >= elementOffset && offset < elementOffset + elementLength) : false;
}
/**
* Returns the offset of the given Java element.
*
* @param element Java element
* @return Offset of the given Java element
*/
private int getOffset(IJavaElement element) {
if (element instanceof ISourceReference) {
ISourceReference sr= (ISourceReference) element;
try {
ISourceRange srcRange= sr.getSourceRange();
if (srcRange != null)
return srcRange.getOffset();
} catch (JavaModelException e) {
}
}
return -1;
}
/**
* Returns the length of the given Java element.
*
* @param element Java element
* @return Length of the given Java element
*/
private int getLength(IJavaElement element) {
if (element instanceof ISourceReference) {
ISourceReference sr= (ISourceReference) element;
try {
ISourceRange srcRange= sr.getSourceRange();
if (srcRange != null)
return srcRange.getLength();
} catch (JavaModelException e) {
}
}
return -1;
}
/**
* Returns the updated java element for the old java element.
*
* @param element Old Java element
* @return Updated Java element
*/
private IJavaElement findElement(IJavaElement element) {
if (element == null)
return null;
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
if (unit != null) {
try {
synchronized (unit) {
unit.reconcile(false, null);
}
IJavaElement[] findings= unit.findElements(element);
if (findings != null && findings.length > 0)
return findings[0];
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
// nothing found, be tolerant and go on
}
}
return null;
}
}
/** Preference key for code formatter tab size */
private final static String CODE_FORMATTER_TAB_SIZE= JavaCore.FORMATTER_TAB_SIZE;
/** Preference key for inserting spaces rather than tabs */
private final static String SPACES_FOR_TABS= PreferenceConstants.EDITOR_SPACES_FOR_TABS;
/** Preference key for automatically closing strings */
private final static String CLOSE_STRINGS= PreferenceConstants.EDITOR_CLOSE_STRINGS;
/** Preference key for automatically closing brackets and parenthesis */
private final static String CLOSE_BRACKETS= PreferenceConstants.EDITOR_CLOSE_BRACKETS;
/** The editor's save policy */
protected ISavePolicy fSavePolicy;
/** Listener to annotation model changes that updates the error tick in the tab image */
private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater;
/** The editor's tab converter */
private TabConverter fTabConverter;
/**
* The remembered selection.
* @since 3.0
*/
private RememberedSelection fRememberedSelection= new RememberedSelection();
/** The bracket inserter. */
private BracketInserter fBracketInserter= new BracketInserter();
/** The standard action groups added to the menu */
private GenerateActionGroup fGenerateActionGroup;
private CompositeActionGroup fContextMenuGroup;
/**
* Creates a new compilation unit editor.
*/
public CompilationUnitEditor() {
super();
setDocumentProvider(JavaPlugin.getDefault().getCompilationUnitDocumentProvider());
setEditorContextMenuId("#CompilationUnitEditorContext"); //$NON-NLS-1$
setRulerContextMenuId("#CompilationUnitRulerContext"); //$NON-NLS-1$
setOutlinerContextMenuId("#CompilationUnitOutlinerContext"); //$NON-NLS-1$
// don't set help contextId, we install our own help context
fSavePolicy= null;
fJavaEditorErrorTickUpdater= new JavaEditorErrorTickUpdater(this);
}
/*
* @see AbstractTextEditor#createActions()
*/
protected void createActions() {
super.createActions();
Action action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS);
setAction("CorrectionAssistProposal", action); //$NON-NLS-1$
markAsStateDependentAction("CorrectionAssistProposal", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.QUICK_FIX_ACTION);
action= new ContentAssistAction(JavaEditorMessages.getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
setAction("ContentAssistProposal", action); //$NON-NLS-1$
markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.CONTENT_ASSIST_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ContentAssistContextInformation.", this, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
setAction("ContentAssistContextInformation", action); //$NON-NLS-1$
markAsStateDependentAction("ContentAssistContextInformation", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX);
setAction("ContentAssistCompletePrefix", action); //$NON-NLS-1$
markAsStateDependentAction("ContentAssistCompletePrefix", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.COMMENT);
setAction("Comment", action); //$NON-NLS-1$
markAsStateDependentAction("Comment", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.UNCOMMENT);
setAction("Uncomment", action); //$NON-NLS-1$
markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION);
action= new ToggleCommentAction(JavaEditorMessages.getResourceBundle(), "ToggleComment.", this, getSourceViewerConfiguration().getDefaultPrefixes(getSourceViewer(), "")); //$NON-NLS-1$ //$NON-NLS-2$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.TOGGLE_COMMENT);
setAction("ToggleComment", action); //$NON-NLS-1$
markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.TOGGLE_COMMENT_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.FORMAT);
setAction("Format", action); //$NON-NLS-1$
markAsStateDependentAction("Format", true); //$NON-NLS-1$
markAsSelectionDependentAction("Format", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION);
action= new AddBlockCommentAction(JavaEditorMessages.getResourceBundle(), "AddBlockComment.", this); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
setAction("AddBlockComment", action); //$NON-NLS-1$
markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
action= new RemoveBlockCommentAction(JavaEditorMessages.getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
setAction("RemoveBlockComment", action); //$NON-NLS-1$
markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.REMOVE_BLOCK_COMMENT_ACTION);
action= new IndentAction(JavaEditorMessages.getResourceBundle(), "Indent.", this, false); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.INDENT);
setAction("Indent", action); //$NON-NLS-1$
markAsStateDependentAction("Indent", true); //$NON-NLS-1$
markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
action= new IndentAction(JavaEditorMessages.getResourceBundle(), "Indent.", this, true); //$NON-NLS-1$
setAction("IndentOnTab", action); //$NON-NLS-1$
markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
if (getNewPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_TAB)) {
// don't replace Shift Right - have to make sure their enablement is mutually exclusive
// removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT);
setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$
}
fGenerateActionGroup= new GenerateActionGroup(this, ITextEditorActionConstants.GROUP_EDIT);
ActionGroup rg= new RefactorActionGroup(this, ITextEditorActionConstants.GROUP_EDIT);
fActionGroups.addGroup(rg);
fActionGroups.addGroup(fGenerateActionGroup);
// We have to keep the context menu group separate to have better control over positioning
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {
fGenerateActionGroup,
rg,
new LocalHistoryActionGroup(this, ITextEditorActionConstants.GROUP_EDIT)});
}
/*
* @see JavaEditor#getElementAt(int)
*/
protected IJavaElement getElementAt(int offset) {
return getElementAt(offset, true);
}
/**
* Returns the most narrow element including the given offset. If <code>reconcile</code>
* is <code>true</code> the editor's input element is reconciled in advance. If it is
* <code>false</code> this method only returns a result if the editor's input element
* does not need to be reconciled.
*
* @param offset the offset included by the retrieved element
* @param reconcile <code>true</code> if working copy should be reconciled
*/
protected IJavaElement getElementAt(int offset, boolean reconcile) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
if (unit != null) {
try {
if (reconcile) {
synchronized (unit) {
unit.reconcile(false, null);
}
return unit.getElementAt(offset);
} else if (unit.isConsistent())
return unit.getElementAt(offset);
} catch (JavaModelException x) {
if (!x.isDoesNotExist())
JavaPlugin.log(x.getStatus());
// nothing found, be tolerant and go on
}
}
return null;
}
/*
* @see JavaEditor#getCorrespondingElement(IJavaElement)
*/
protected IJavaElement getCorrespondingElement(IJavaElement element) {
try {
return EditorUtility.getWorkingCopy(element, true);
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
// nothing found, be tolerant and go on
}
return null;
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#getInputElement()
*/
protected IJavaElement getInputJavaElement() {
return JavaPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(getEditorInput());
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/*
* @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
*/
protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
if (page != null) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
page.setInput(manager.getWorkingCopy(input));
}
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean, org.eclipse.core.runtime.IProgressMonitor)
*/
protected void performSave(boolean overwrite, IProgressMonitor progressMonitor) {
IDocumentProvider p= getDocumentProvider();
if (p instanceof ICompilationUnitDocumentProvider) {
ICompilationUnitDocumentProvider cp= (ICompilationUnitDocumentProvider) p;
cp.setSavePolicy(fSavePolicy);
}
try {
super.performSave(overwrite, progressMonitor);
} finally {
if (p instanceof ICompilationUnitDocumentProvider) {
ICompilationUnitDocumentProvider cp= (ICompilationUnitDocumentProvider) p;
cp.setSavePolicy(null);
}
}
}
/*
* @see AbstractTextEditor#doSaveAs
*/
public void doSaveAs() {
if (askIfNonWorkbenchEncodingIsOk()) {
super.doSaveAs();
}
}
/*
* @see AbstractTextEditor#doSave(IProgressMonitor)
*/
public void doSave(IProgressMonitor progressMonitor) {
IDocumentProvider p= getDocumentProvider();
if (p == null) {
// editor has been closed
return;
}
if (!askIfNonWorkbenchEncodingIsOk()) {
progressMonitor.setCanceled(true);
return;
}
if (p.isDeleted(getEditorInput())) {
if (isSaveAsAllowed()) {
/*
* 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors.
* Changed Behavior to make sure that if called inside a regular save (because
* of deletion of input element) there is a way to report back to the caller.
*/
performSaveAs(progressMonitor);
} else {
/*
* 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there
* Missing resources.
*/
Shell shell= getSite().getShell();
MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title1"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
setStatusLineErrorMessage(null);
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
if (unit != null) {
synchronized (unit) {
performSave(false, progressMonitor);
}
} else
performSave(false, progressMonitor);
}
}
/**
* Asks the user if it is ok to store in non-workbench encoding.
* @return <true> if the user wants to continue
*/
private boolean askIfNonWorkbenchEncodingIsOk() {
IDocumentProvider provider= getDocumentProvider();
if (provider instanceof IStorageDocumentProvider) {
IEditorInput input= getEditorInput();
IStorageDocumentProvider storageProvider= (IStorageDocumentProvider)provider;
String encoding= storageProvider.getEncoding(input);
String defaultEncoding= storageProvider.getDefaultEncoding();
if (encoding != null && !encoding.equals(defaultEncoding)) {
Shell shell= getSite().getShell();
String title= JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$
String msg;
if (input != null)
msg= MessageFormat.format(JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.message1"), new String[] {input.getName(), encoding});//$NON-NLS-1$
else
msg= MessageFormat.format(JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.message2"), new String[] {encoding});//$NON-NLS-1$
return MessageDialog.openQuestion(shell, title, msg);
}
}
return true;
}
public boolean isSaveAsAllowed() {
return true;
}
/**
* The compilation unit editor implementation of this <code>AbstractTextEditor</code>
* method asks the user for the workspace path of a file resource and saves the document
* there. See http://dev.eclipse.org/bugs/show_bug.cgi?id=6295
*/
protected void performSaveAs(IProgressMonitor progressMonitor) {
Shell shell= getSite().getShell();
IEditorInput input = getEditorInput();
SaveAsDialog dialog= new SaveAsDialog(shell);
IFile original= (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null;
if (original != null)
dialog.setOriginalFile(original);
dialog.create();
IDocumentProvider provider= getDocumentProvider();
if (provider == null) {
// editor has been programmatically closed while the dialog was open
return;
}
if (provider.isDeleted(input) && original != null) {
String message= JavaEditorMessages.getFormattedString("CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$
dialog.setErrorMessage(null);
dialog.setMessage(message, IMessageProvider.WARNING);
}
if (dialog.open() == Window.CANCEL) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IPath filePath= dialog.getResult();
if (filePath == null) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
IFile file= workspaceRoot.getFile(filePath);
final IEditorInput newInput= new FileEditorInput(file);
boolean success= false;
try {
provider.aboutToChange(newInput);
getDocumentProvider().saveDocument(progressMonitor, newInput, getDocumentProvider().getDocument(getEditorInput()), true);
success= true;
} catch (CoreException x) {
ErrorDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title2"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), x.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
} finally {
provider.changed(newInput);
if (success)
setInput(newInput);
}
if (progressMonitor != null)
progressMonitor.setCanceled(!success);
}
/*
* @see AbstractTextEditor#doSetInput(IEditorInput)
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
configureTabConverter();
}
private void configureTabConverter() {
if (fTabConverter != null) {
IDocumentProvider provider= getDocumentProvider();
if (provider instanceof ICompilationUnitDocumentProvider) {
ICompilationUnitDocumentProvider cup= (ICompilationUnitDocumentProvider) provider;
fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput()));
}
}
}
private int getTabSize() {
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
return preferences.getInt(CODE_FORMATTER_TAB_SIZE);
}
private void startTabConversion() {
if (fTabConverter == null) {
fTabConverter= new TabConverter();
configureTabConverter();
fTabConverter.setNumberOfSpacesPerTab(getTabSize());
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
asv.addTextConverter(fTabConverter);
// http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
asv.updateIndentationPrefixes();
}
}
private void stopTabConversion() {
if (fTabConverter != null) {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
asv.removeTextConverter(fTabConverter);
// http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
asv.updateIndentationPrefixes();
fTabConverter= null;
}
}
private boolean isTabConversionEnabled() {
IPreferenceStore store= getNewPreferenceStore();
return store.getBoolean(SPACES_FOR_TABS);
}
public void dispose() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension)
((ITextViewerExtension) sourceViewer).removeVerifyKeyListener(fBracketInserter);
if (fJavaEditorErrorTickUpdater != null) {
fJavaEditorErrorTickUpdater.dispose();
fJavaEditorErrorTickUpdater= null;
}
if (fActionGroups != null) {
fActionGroups.dispose();
fActionGroups= null;
}
super.dispose();
}
/*
* @see AbstractTextEditor#createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
if (isTabConversionEnabled())
startTabConversion();
IPreferenceStore preferenceStore= getNewPreferenceStore();
boolean closeBrackets= preferenceStore.getBoolean(CLOSE_BRACKETS);
boolean closeStrings= preferenceStore.getBoolean(CLOSE_STRINGS);
fBracketInserter.setCloseBracketsEnabled(closeBrackets);
fBracketInserter.setCloseStringsEnabled(closeStrings);
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension)
((ITextViewerExtension) sourceViewer).prependVerifyKeyListener(fBracketInserter);
}
private static char getEscapeCharacter(char character) {
switch (character) {
case '"':
case '\'':
return '\\';
default:
return 0;
}
}
private static char getPeerCharacter(char character) {
switch (character) {
case '(':
return ')';
case ')':
return '(';
case '[':
return ']';
case ']':
return '[';
case '"':
return character;
case '\'':
return character;
default:
throw new IllegalArgumentException();
}
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
if (asv != null) {
String p= event.getProperty();
if (CLOSE_BRACKETS.equals(p)) {
fBracketInserter.setCloseBracketsEnabled(getNewPreferenceStore().getBoolean(p));
return;
}
if (CLOSE_STRINGS.equals(p)) {
fBracketInserter.setCloseStringsEnabled(getNewPreferenceStore().getBoolean(p));
return;
}
if (SPACES_FOR_TABS.equals(p)) {
if (isTabConversionEnabled())
startTabConversion();
else
stopTabConversion();
return;
}
if (PreferenceConstants.EDITOR_SMART_TAB.equals(p)) {
if (getNewPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_TAB)) {
setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$
} else {
removeActionActivationCode("IndentOnTab"); //$NON-NLS-1$
}
}
IContentAssistant c= asv.getContentAssistant();
if (c instanceof ContentAssistant)
ContentAssistPreference.changeConfiguration((ContentAssistant) c, getNewPreferenceStore(), event);
if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
asv.updateIndentationPrefixes();
if (fTabConverter != null)
fTabConverter.setNumberOfSpacesPerTab(getTabSize());
}
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite, org.eclipse.jface.text.source.IVerticalRuler, org.eclipse.jface.text.source.IOverviewRuler, boolean, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) {
return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler, isOverviewRulerVisible, styles);
}
/*
* @see IReconcilingParticipant#reconciled()
*/
public void reconciled() {
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) {
Shell shell= getSite().getShell();
if (shell != null && !shell.isDisposed()) {
shell.getDisplay().asyncExec(new Runnable() {
public void run() {
synchronizeOutlinePageSelection();
}
});
}
}
}
protected void updateStateDependentActions() {
super.updateStateDependentActions();
fGenerateActionGroup.editorStateChanged();
}
/*
* @see AbstractTextEditor#rememberSelection()
*/
protected void rememberSelection() {
fRememberedSelection.remember();
}
/*
* @see AbstractTextEditor#restoreSelection()
*/
protected void restoreSelection() {
fRememberedSelection.restore();
}
/*
* @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput)
*/
protected boolean canHandleMove(IEditorInput originalElement, IEditorInput movedElement) {
String oldExtension= ""; //$NON-NLS-1$
if (originalElement instanceof IFileEditorInput) {
IFile file= ((IFileEditorInput) originalElement).getFile();
if (file != null) {
String ext= file.getFileExtension();
if (ext != null)
oldExtension= ext;
}
}
String newExtension= ""; //$NON-NLS-1$
if (movedElement instanceof IFileEditorInput) {
IFile file= ((IFileEditorInput) movedElement).getFile();
if (file != null)
newExtension= file.getFileExtension();
}
return oldExtension.equals(newExtension);
}
/*
* @see org.eclipse.ui.texteditor.ExtendedTextEditor#isPrefQuickDiffAlwaysOn()
*/
protected boolean isPrefQuickDiffAlwaysOn() {
// reestablishes the behaviour from ExtendedTextEditor which was hacked by JavaEditor
// to disable the change bar for the class file (attached source) java editor.
IPreferenceStore store= getNewPreferenceStore();
return store.getBoolean(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON);
}
}
|
46,341 |
Bug 46341 [formatting][implementation] comment line length not correctly applied
|
(1105 nightly build) when formatting the declaration below, with all default code formatter options (i.e. comment line length = 80), the last word '<code>String</code>' is not correctly moved to anotherline, leaving the last line longer than 80 characters (about 87 characters i think..) /** * Sets the set of identifiers to active activities. * * @param activeActivityIds * the set of identifiers to active activities. This set may be * empty, but it must not be <code>null</code>. If this set * is not empty, it must only contain instances of <code>String</code>. */ void setActiveActivityIds(Set activeActivityIds);
|
resolved fixed
|
c79d3f5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-10T11:46:17Z | 2003-11-10T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/CommentRegion.java
|
/*****************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*****************************************************************************/
package org.eclipse.jdt.internal.ui.text.comment;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import org.eclipse.text.edits.InsertEdit;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.MultiTextEdit;
import org.eclipse.text.edits.ReplaceEdit;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.ConfigurableLineTracker;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ILineTracker;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.TypedPosition;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.javadoc.IHtmlTagConstants;
/**
* Comment region in a source code document.
*
* @since 3.0
*/
public class CommentRegion extends TypedPosition implements IHtmlTagConstants, IBorderAttributes, ICommentAttributes {
/** Default line prefix length */
public static final int COMMENT_PREFIX_LENGTH= 3;
/** Default comment range delimiter */
protected static final String COMMENT_RANGE_DELIMITER= " "; //$NON-NLS-1$
/** The borders of this region */
private int fBorders= 0;
/** Should all blank lines be cleared during formatting? */
private final boolean fClear;
/** The line delimiter used in this comment region */
private final String fDelimiter;
/** The document to format */
private final IDocument fDocument;
/** Text measurement */
private final ITextMeasurement fTextMeasurement;
/** The lines in this comment region */
private final LinkedList fLines= new LinkedList();
/** The formatting preferences */
private final Map fPreferences;
/** The comment ranges in this comment region */
private final LinkedList fRanges= new LinkedList();
/** The resulting text edit */
private MultiTextEdit fResult= new MultiTextEdit();
/** Is this comment region a single line region? */
private final boolean fSingleLine;
/** Number of whitespaces representing tabulator */
private int fTabs;
/**
* Creates a new comment region.
*
* @param document
* The document which contains the comment region
* @param position
* The position of this comment region in the document
* @param delimiter
* The line delimiter of this comment region
* @param preferences
* The formatting preferences for this region
* @param textMeasurement
* The text measurement. Can be <code>null</code>.
*/
protected CommentRegion(final IDocument document, final TypedPosition position, final String delimiter, final Map preferences, final ITextMeasurement textMeasurement) {
super(position.getOffset(), position.getLength(), position.getType());
fDelimiter= delimiter;
fPreferences= preferences;
fDocument= document;
fClear= fPreferences.get(PreferenceConstants.FORMATTER_COMMENT_CLEARBLANKLINES) == IPreferenceStore.TRUE;
fTextMeasurement= textMeasurement;
if (fPreferences.containsKey(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE))
try {
fTabs= Integer.parseInt((String) fPreferences.get(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE));
} catch (NumberFormatException e) {
fTabs= 4;
}
else
fTabs= 4;
final ILineTracker tracker= new ConfigurableLineTracker(new String[] { delimiter });
IRegion range= null;
CommentLine line= null;
tracker.set(getText(0, getLength()));
final int lines= tracker.getNumberOfLines();
fSingleLine= lines == 1;
try {
for (int index= 0; index < lines; index++) {
range= tracker.getLineInformation(index);
line= CommentObjectFactory.createLine(this);
line.append(new CommentRange(range.getOffset(), range.getLength()));
fLines.add(line);
}
} catch (BadLocationException exception) {
// Should not happen
}
}
/**
* Appends the comment range to this comment region.
*
* @param range
* Comment range to append to this comment region
*/
protected final void append(final CommentRange range) {
fRanges.addLast(range);
}
/**
* Can the comment range be appended to the comment line?
*
* @param line
* Comment line where to append the comment range
* @param previous
* Comment range which is the predecessor of the current comment
* range
* @param next
* Comment range to test whether it can be appended to the
* comment line
* @param index
* Amount of space in the comment line used by already inserted
* comment ranges
* @param width
* The maximal width of text in this comment region measured in
* average character widths
* @return <code>true</code> iff the comment range can be added to the
* line, <code>false</code> otherwise
*/
protected boolean canAppend(final CommentLine line, final CommentRange previous, final CommentRange next, final int index, final int width) {
return index == 0 || index + next.getLength() < width;
}
/**
* Can the whitespace between the two comment ranges be formatted?
*
* @param previous
* Previous comment range which was already formatted
* @param next
* Next comment range to be formatted
* @return <code>true</code> iff the next comment range can be formatted,
* <code>false</code> otherwise.
*/
protected boolean canFormat(final CommentRange previous, final CommentRange next) {
return true;
}
/**
* Formats the comment region.
*
* @param indentation
* The indentation of the comment region
* @return The resulting text edit of the formatting process
*/
public final TextEdit format(final String indentation) {
fResult= new MultiTextEdit();
final String probe= getText(0, CommentLine.NON_FORMAT_START_PREFIX.length());
if (!probe.startsWith(CommentLine.NON_FORMAT_START_PREFIX)) {
int margin= 80;
try {
margin= Integer.parseInt(fPreferences.get(PreferenceConstants.FORMATTER_COMMENT_LINELENGTH).toString());
} catch (Exception exception) {
// Do nothing
}
margin= Math.max(COMMENT_PREFIX_LENGTH + 1, margin - stringToLength(indentation) - COMMENT_PREFIX_LENGTH);
tokenizeRegion();
markRegion();
wrapRegion(margin);
formatRegion(indentation, margin);
}
return fResult;
}
/**
* Formats this comment region.
*
* @param indentation
* The indentation of this comment region
* @param width
* The maximal width of text in this comment region measured in
* average character widths
*/
protected void formatRegion(final String indentation, final int width) {
final int last= fLines.size() - 1;
if (last >= 0) {
CommentLine previous= null;
CommentLine next= (CommentLine)fLines.get(last);
CommentRange range= next.getLast();
next.formatLowerBorder(range, indentation, width);
for (int line= last; line >= 0; line--) {
previous= next;
next= (CommentLine)fLines.get(line);
range= next.formatLine(previous, range, indentation, line); // FIXME: range is fLines.get(last).getLast() in first iteration; leads to BadLocationException in logEdit(..)
}
next.formatUpperBorder(range, indentation, width);
}
}
/**
* Returns the line delimiter used in this comment region.
*
* @return The line delimiter for this comment region
*/
protected final String getDelimiter() {
return fDelimiter;
}
/**
* Returns the line delimiter used in this comment line break.
*
* @param predecessor
* The predecessor comment line after the line break
* @param successor
* The successor comment line before the line break
* @param previous
* The comment range after the line break
* @param next
* The comment range before the line break
* @param indentation
* Indentation of the formatted line break
* @return The line delimiter for this comment line break
*/
protected String getDelimiter(final CommentLine predecessor, final CommentLine successor, final CommentRange previous, final CommentRange next, final String indentation) {
return fDelimiter + indentation + successor.getContentPrefix();
}
/**
* Returns the range delimiter for this comment range break.
*
* @param previous
* The previous comment range to the right of the range
* delimiter
* @param next
* The next comment range to the left of the range delimiter
* @return The delimiter for this comment range break
*/
protected String getDelimiter(final CommentRange previous, final CommentRange next) {
return COMMENT_RANGE_DELIMITER;
}
/**
* Returns the document of this comment region.
*
* @return The document of this region
*/
protected final IDocument getDocument() {
return fDocument;
}
/**
* Returns the formatting preferences.
*
* @return The formatting preferences
*/
public final Map getPreferences() {
return fPreferences;
}
/**
* Returns the comment ranges in this comment region
*
* @return The comment ranges in this region
*/
protected final LinkedList getRanges() {
return fRanges;
}
/**
* Returns the number of comment lines in this comment region.
*
* @return The number of lines in this comment region
*/
protected final int getSize() {
return fLines.size();
}
/**
* Returns the text of this comment region in the indicated range.
*
* @param position
* The offset of the comment range to retrieve in comment region
* coordinates
* @param count
* The length of the comment range to retrieve
* @return The content of this comment region in the indicated range
*/
protected final String getText(final int position, final int count) {
String content= ""; //$NON-NLS-1$
try {
content= fDocument.get(getOffset() + position, count);
} catch (BadLocationException exception) {
// Should not happen
}
return content;
}
/**
* Does the border <code>border</code> exist?
*
* @param border
* The type of the border. Must be a border attribute of <code>CommentRegion</code>.
* @return <code>true</code> iff this border exists, <code>false</code>
* otherwise.
*/
protected final boolean hasBorder(final int border) {
return (fBorders & border) == border;
}
/**
* Does the comment range consist of letters and digits only?
*
* @param range
* The comment range to text
* @return <code>true</code> iff the comment range consists of letters
* and digits only, <code>false</code> otherwise.
*/
protected final boolean isAlphaNumeric(final CommentRange range) {
final String token= getText(range.getOffset(), range.getLength());
for (int index= 0; index < token.length(); index++) {
if (!Character.isLetterOrDigit(token.charAt(index)))
return false;
}
return true;
}
/**
* Does the comment range contain no letters and digits?
*
* @param range
* The comment range to text
* @return <code>true</code> iff the comment range contains no letters
* and digits, <code>false</code> otherwise.
*/
protected final boolean isNonAlphaNumeric(final CommentRange range) {
final String token= getText(range.getOffset(), range.getLength());
for (int index= 0; index < token.length(); index++) {
if (Character.isLetterOrDigit(token.charAt(index)))
return false;
}
return true;
}
/**
* Should blank lines be cleared during formatting?
*
* @return <code>true</code> iff blank lines should be cleared, <code>false</code>
* otherwise
*/
protected final boolean isClearLines() {
return fClear;
}
/**
* Is this comment region a single line region?
*
* @return <code>true</code> iff this region is single line, <code>false</code>
* otherwise.
*/
protected final boolean isSingleLine() {
return fSingleLine;
}
/**
* Logs a text edit operation occurred during the formatting process
*
* @param change
* The changed text
* @param position
* Offset measured in comment region coordinates where to apply
* the changed text
* @param count
* Length of the range where to apply the changed text
* @return The resulting text edit, or <code>null</code> iff the
* operation can not be performed.
*/
protected final TextEdit logEdit(final String change, final int position, final int count) {
TextEdit child= null;
try {
final int base= getOffset() + position;
final String content= fDocument.get(base, count);
if (!change.equals(content)) {
if (count > 0)
child= new ReplaceEdit(base, count, change);
else
child= new InsertEdit(base, change);
fResult.addChild(child);
}
} catch (BadLocationException exception) {
// Should not happen
} catch (MalformedTreeException exception) {
// Do nothing
JavaPlugin.log(exception);
}
return child;
}
/**
* Marks the comment ranges in this comment region.
*/
protected void markRegion() {
// Do nothing
}
/**
* Set the border type <code>border</code> to true.
*
* @param border
* The type of the border. Must be a border attribute of <code>CommentRegion</code>.
*/
protected final void setBorder(final int border) {
fBorders |= border;
}
/**
* Computes the equivalent indentation for a string
*
* @param reference
* The string to compute the indentation for
* @param tabs
* <code>true</code> iff the indentation should use tabs,
* <code>false</code> otherwise.
* @return The indentation string
*/
protected final String stringToIndent(final String reference, final boolean tabs) {
int space;
int pixels;
if (fTextMeasurement != null) {
pixels= stringToPixels(reference);
space= fTextMeasurement.computeWidth(" "); //$NON-NLS-1$
} else {
space= 1;
pixels= reference.length();
int index= -1;
while ((index= reference.indexOf('\t', index+1)) >= 0)
pixels += fTabs-1;
}
final StringBuffer buffer= new StringBuffer();
final int spaces= pixels / space;
if (tabs) {
final int count= spaces / fTabs;
final int modulo= spaces % fTabs;
for (int index= 0; index < count; index++)
buffer.append('\t');
for (int index= 0; index < modulo; index++)
buffer.append(' ');
} else {
for (int index= 0; index < spaces; index++)
buffer.append(' ');
}
return buffer.toString();
}
/**
* Returns the length of the in expanded characters.
*
* @param reference
* The string to get the length for
* @return The length of the string in expanded characters
*/
protected final int stringToLength(final String reference) {
int tabs= 0;
int count= reference.length();
for (int index= 0; index < count; index++) {
if (reference.charAt(index) == '\t')
tabs++;
}
count += tabs * (fTabs - 1);
return count;
}
/**
* Returns the width of the string in pixels.
*
* @param reference
* The string to get the width for
* @return The width of the string in pixels
*/
protected final int stringToPixels(final String reference) {
final StringBuffer buffer= new StringBuffer();
char character= 0;
for (int index= 0; index < reference.length(); index++) {
character= reference.charAt(index);
if (character == '\t') {
for (int tab= 0; tab < fTabs; tab++)
buffer.append(' ');
} else
buffer.append(character);
}
return fTextMeasurement.computeWidth(buffer.toString());
}
/**
* Tokenizes the comment region.
*/
protected void tokenizeRegion() {
int index= 0;
CommentLine line= null;
for (final Iterator iterator= fLines.iterator(); iterator.hasNext(); index++) {
line= (CommentLine)iterator.next();
line.scanLine(index);
line.tokenizeLine(index);
}
}
/**
* Wraps the comment ranges in this comment region into comment lines.
*
* @param width
* The maximal width of text in this comment region measured in
* average character widths
*/
protected void wrapRegion(final int width) {
fLines.clear();
int index= 0;
boolean adapted= false;
CommentLine successor= null;
CommentLine predecessor= null;
CommentRange previous= null;
CommentRange next= null;
while (!fRanges.isEmpty()) {
index= 0;
adapted= false;
predecessor= successor;
successor= CommentObjectFactory.createLine(this);
fLines.add(successor);
while (!fRanges.isEmpty()) {
next= (CommentRange)fRanges.getFirst();
if (canAppend(successor, previous, next, index, width)) {
if (!adapted && predecessor != null) {
successor.adapt(predecessor);
adapted= true;
}
fRanges.removeFirst();
successor.append(next);
index += (next.getLength() + 1);
previous= next;
} else
break;
}
}
}
}
|
46,341 |
Bug 46341 [formatting][implementation] comment line length not correctly applied
|
(1105 nightly build) when formatting the declaration below, with all default code formatter options (i.e. comment line length = 80), the last word '<code>String</code>' is not correctly moved to anotherline, leaving the last line longer than 80 characters (about 87 characters i think..) /** * Sets the set of identifiers to active activities. * * @param activeActivityIds * the set of identifiers to active activities. This set may be * empty, but it must not be <code>null</code>. If this set * is not empty, it must only contain instances of <code>String</code>. */ void setActiveActivityIds(Set activeActivityIds);
|
resolved fixed
|
c79d3f5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-10T11:46:17Z | 2003-11-10T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/MultiCommentRegion.java
|
/*****************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*****************************************************************************/
package org.eclipse.jdt.internal.ui.text.comment;
import java.util.ListIterator;
import java.util.Map;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.TypedPosition;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.text.javadoc.ICommentTagConstants;
/**
* Multi-comment region in a source code document.
*
* @since 3.0
*/
public class MultiCommentRegion extends CommentRegion implements ICommentTagConstants {
/** Should root tag parameter descriptions be indented after the tag? */
private final boolean fIndentDescriptions;
/** Should root tag parameter descriptions be indented? */
private final boolean fIndentRoots;
/** Should description of parameters go to the next line? */
private final boolean fParameterNewLine;
/** Should root tags be separated from description? */
private boolean fSeparateRoots;
/**
* Creates a new multi-comment region.
*
* @param document
* The document which contains the comment region
* @param position
* The position of this comment region in the document
* @param delimiter
* The line delimiter of this comment region
* @param preferences
* The formatting preferences for this region
* @param textMeasurement
* The text measurement. Can be <code>null</code>.
*/
protected MultiCommentRegion(final IDocument document, final TypedPosition position, final String delimiter, final Map preferences, final ITextMeasurement textMeasurement) {
super(document, position, delimiter, preferences, textMeasurement);
fIndentRoots= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_INDENTROOTTAGS));
fIndentDescriptions= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION));
fSeparateRoots= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_SEPARATEROOTTAGS));
fParameterNewLine= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_NEWLINEFORPARAMETER));
}
/**
* @inheritDoc
*/
protected boolean canAppend(final CommentLine line, final CommentRange previous, final CommentRange next, final int index, int count) {
final boolean blank= next.hasAttribute(COMMENT_BLANKLINE);
// Avoid wraping punctuation
if (next.getLength() <= 2 && !blank && isNonAlphaNumeric(next))
return true;
if (fParameterNewLine && line.hasAttribute(COMMENT_PARAMETER) && line.getSize() > 1)
return false;
if (previous != null) {
if (previous.hasAttribute(COMMENT_ROOT))
return true;
if (index != 0 && (blank || previous.hasAttribute(COMMENT_BLANKLINE) || next.hasAttribute(COMMENT_PARAMETER) || next.hasAttribute(COMMENT_ROOT) || next.hasAttribute(COMMENT_SEPARATOR) || next.hasAttribute(COMMENT_NEWLINE) || previous.hasAttribute(COMMENT_BREAK) || previous.hasAttribute(COMMENT_SEPARATOR)))
return false;
if (next.hasAttribute(COMMENT_IMMUTABLE) && previous.hasAttribute(COMMENT_IMMUTABLE))
return true;
}
if (fIndentRoots && !line.hasAttribute(COMMENT_ROOT) && !line.hasAttribute(COMMENT_PARAMETER))
count -= stringToLength(line.getIndentationReference());
return super.canAppend(line, previous, next, index, count);
}
/**
* @inheritDoc
*/
protected String getDelimiter(CommentLine predecessor, CommentLine successor, CommentRange previous, CommentRange next, String indentation) {
final String delimiter= super.getDelimiter(predecessor, successor, previous, next, indentation);
if (previous != null) {
if (previous.hasAttribute(COMMENT_IMMUTABLE | COMMENT_SEPARATOR) && !next.hasAttribute(COMMENT_CODE) && !successor.hasAttribute(COMMENT_BLANKLINE))
return delimiter + delimiter;
// else if (previous.hasAttribute(COMMENT_CODE) && !next.hasAttribute(COMMENT_CODE))
// return getDelimiter();
//
// // remove any asterisk borders inside code sections
// else if (previous.hasAttribute(COMMENT_CODE) && next.hasAttribute(COMMENT_CODE))
// return getDelimiter();
else if ((next.hasAttribute(COMMENT_IMMUTABLE | COMMENT_SEPARATOR) || ((fSeparateRoots || !isClearLines()) && previous.hasAttribute(COMMENT_PARAGRAPH))) && !successor.hasAttribute(COMMENT_BLANKLINE) && !predecessor.hasAttribute(COMMENT_BLANKLINE))
return delimiter + delimiter;
else if (fIndentRoots && !predecessor.hasAttribute(COMMENT_ROOT) && !predecessor.hasAttribute(COMMENT_PARAMETER) && !predecessor.hasAttribute(COMMENT_BLANKLINE))
return delimiter + stringToIndent(predecessor.getIndentationReference(), false);
}
return delimiter;
}
/**
* @inheritDoc
*/
protected String getDelimiter(final CommentRange previous, final CommentRange next) {
if (previous != null) {
if (previous.hasAttribute(COMMENT_HTML) && next.hasAttribute(COMMENT_HTML))
return ""; //$NON-NLS-1$
else if (next.hasAttribute(COMMENT_OPEN) || previous.hasAttribute(COMMENT_HTML | COMMENT_CLOSE))
return ""; //$NON-NLS-1$
else if (!next.hasAttribute(COMMENT_CODE) && previous.hasAttribute(COMMENT_CODE))
return ""; //$NON-NLS-1$
else if (next.hasAttribute(COMMENT_CLOSE) && previous.getLength() <= 2 && !isAlphaNumeric(previous))
return ""; //$NON-NLS-1$
else if (previous.hasAttribute(COMMENT_OPEN) && next.getLength() <= 2 && !isAlphaNumeric(next))
return ""; //$NON-NLS-1$
}
return super.getDelimiter(previous, next);
}
/**
* Should root tag parameter descriptions be indented after the tag?
*
* @return <code>true</code> iff the descriptions should be indented
* after, <code>false</code> otherwise.
*/
protected final boolean isIndentDescriptions() {
return fIndentDescriptions;
}
/**
* Should root tag parameter descriptions be indented?
*
* @return <code>true</code> iff the root tags should be indented, <code>false</code>
* otherwise.
*/
protected final boolean isIndentRoots() {
return fIndentRoots;
}
/**
* Marks the comment ranges confined by HTML ranges.
*/
protected void markHtmlRanges() {
// Do nothing
}
/**
* Marks the comment range with its html tag attributes.
*
* @param range
* The comment range to mark
* @param token
* Token associated with the comment range
*/
protected void markHtmlTag(final CommentRange range, final String token) {
// Do nothing
}
/**
* Marks the comment range with its javadoc tag attributes.
*
* @param range
* The comment range to mark
* @param token
* Token associated with the comment range
*/
protected void markJavadocTag(final CommentRange range, final String token) {
range.markPrefixTag(COMMENT_ROOT_TAGS, COMMENT_TAG_PREFIX, token, COMMENT_ROOT);
}
/**
* @inheritDoc
*/
protected void markRegion() {
int count= 0;
boolean paragraph= false;
String token= null;
CommentRange range= null;
CommentRange blank= null;
for (final ListIterator iterator= getRanges().listIterator(); iterator.hasNext();) {
range= (CommentRange)iterator.next();
count= range.getLength();
if (count > 0) {
token= getText(range.getOffset(), count).toLowerCase();
markJavadocTag(range, token);
if (!paragraph && (range.hasAttribute(COMMENT_ROOT) || range.hasAttribute(COMMENT_PARAMETER))) {
iterator.previous();
while (iterator.hasPrevious()) {
blank= (CommentRange)iterator.previous();
if (blank.hasAttribute(COMMENT_BLANKLINE))
iterator.remove();
else
break;
}
range.setAttribute(COMMENT_PARAGRAPH);
paragraph= true;
}
markHtmlTag(range, token);
}
}
markHtmlRanges();
}
}
|
54,334 |
Bug 54334 Pasting a CU caused entry in log
|
I20040309 !ENTRY org.eclipse.jdt.ui 4 10001 Mar 10, 2004 18:08:46.915 !MESSAGE Internal Error !STACK 0 java.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.jface.dialogs.ProgressMonitorDialog.run (ProgressMonitorDialog.java:400) at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper.perform (RefactoringExecutionHelper.java:90) at org.eclipse.jdt.internal.ui.refactoring.reorg.ReorgCopyStarter.run (ReorgCopyStarter.java:70) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction$JavaElementAndResourc ePaster.paste(PasteAction.java:403) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction.run (PasteAction.java:190) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:212) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:188) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:550) at org.eclipse.jface.action.ActionContributionItem.access$2 (ActionContributionItem.java:502) at org.eclipse.jface.action.ActionContributionItem$5.handleEvent (ActionContributionItem.java:435) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:833) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2367) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2047) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1451) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1422) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:258) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:48) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:260) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:173) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:106) 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:305) at org.eclipse.core.launcher.Main.run(Main.java:745) at org.eclipse.core.launcher.Main.main(Main.java:713) Caused by: java.lang.NullPointerException at org.eclipse.ltk.internal.refactoring.core.DirtyBufferValidationState.dispose (BufferValidationState.java:166) at org.eclipse.jdt.internal.corext.refactoring.changes.UndoTextFileChange.dispose (UndoTextFileChange.java:146) at org.eclipse.jdt.internal.corext.refactoring.UndoManager.sendDispose (UndoManager.java:325) at org.eclipse.jdt.internal.corext.refactoring.UndoManager.flushUndo (UndoManager.java:129) at org.eclipse.jdt.internal.corext.refactoring.UndoManager.flush (UndoManager.java:122) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation$1.run (PerformChangeOperation.java:215) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation (BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.run (JavaModelOperation.java:700) at org.eclipse.core.internal.resources.Workspace.run (Workspace.java:1562) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:3182) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:3139) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.executeChange (PerformChangeOperation.java:222) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:164) at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$Operation.ru n(RefactoringExecutionHelper.java:65) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation (BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.run (JavaModelOperation.java:700) at org.eclipse.core.internal.resources.Workspace.run (Workspace.java:1562) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:3182) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:3139) at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run (WorkbenchRunnableAdapter.java:50) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302) ... 31 more
|
resolved fixed
|
b4a0cd8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-10T17:42:43Z | 2004-03-10T17:33:20Z |
org.eclipse.jdt.ui/core
| |
54,334 |
Bug 54334 Pasting a CU caused entry in log
|
I20040309 !ENTRY org.eclipse.jdt.ui 4 10001 Mar 10, 2004 18:08:46.915 !MESSAGE Internal Error !STACK 0 java.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.jface.dialogs.ProgressMonitorDialog.run (ProgressMonitorDialog.java:400) at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper.perform (RefactoringExecutionHelper.java:90) at org.eclipse.jdt.internal.ui.refactoring.reorg.ReorgCopyStarter.run (ReorgCopyStarter.java:70) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction$JavaElementAndResourc ePaster.paste(PasteAction.java:403) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction.run (PasteAction.java:190) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:212) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:188) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:550) at org.eclipse.jface.action.ActionContributionItem.access$2 (ActionContributionItem.java:502) at org.eclipse.jface.action.ActionContributionItem$5.handleEvent (ActionContributionItem.java:435) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:833) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2367) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2047) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1451) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1422) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:258) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:48) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:260) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:173) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:106) 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:305) at org.eclipse.core.launcher.Main.run(Main.java:745) at org.eclipse.core.launcher.Main.main(Main.java:713) Caused by: java.lang.NullPointerException at org.eclipse.ltk.internal.refactoring.core.DirtyBufferValidationState.dispose (BufferValidationState.java:166) at org.eclipse.jdt.internal.corext.refactoring.changes.UndoTextFileChange.dispose (UndoTextFileChange.java:146) at org.eclipse.jdt.internal.corext.refactoring.UndoManager.sendDispose (UndoManager.java:325) at org.eclipse.jdt.internal.corext.refactoring.UndoManager.flushUndo (UndoManager.java:129) at org.eclipse.jdt.internal.corext.refactoring.UndoManager.flush (UndoManager.java:122) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation$1.run (PerformChangeOperation.java:215) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation (BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.run (JavaModelOperation.java:700) at org.eclipse.core.internal.resources.Workspace.run (Workspace.java:1562) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:3182) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:3139) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.executeChange (PerformChangeOperation.java:222) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:164) at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$Operation.ru n(RefactoringExecutionHelper.java:65) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation (BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.run (JavaModelOperation.java:700) at org.eclipse.core.internal.resources.Workspace.run (Workspace.java:1562) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:3182) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:3139) at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run (WorkbenchRunnableAdapter.java:50) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302) ... 31 more
|
resolved fixed
|
b4a0cd8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-10T17:42:43Z | 2004-03-10T17:33:20Z |
refactoring/org/eclipse/ltk/internal/refactoring/core/BufferValidationState.java
| |
54,239 |
Bug 54239 Hide local types does not hide local types in field initializers
|
build I20040303 - opened org.eclipse.ui.internal.skins.newlook.BasicStackPresentation (new in head) - the outline showed lots of local types - selected Hide Local Types - still had many local types showing - took me a while to realize that these were just the ones in field initializers I would expect all local types to be suppressed, whether within a method or field or static initializers.
|
resolved fixed
|
191bde3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-11T09:45:00Z | 2004-03-10T03:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/MemberFilter.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.viewsupport;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
/**
* Filter for the methods viewer.
* Changing a filter property does not trigger a refiltering of the viewer
*/
public class MemberFilter extends ViewerFilter {
public static final int FILTER_NONPUBLIC= 1;
public static final int FILTER_STATIC= 2;
public static final int FILTER_FIELDS= 4;
public static final int FILTER_LOCALTYPES= 8;
private int fFilterProperties;
/**
* Modifies filter and add a property to filter for
*/
public final void addFilter(int filter) {
fFilterProperties |= filter;
}
/**
* Modifies filter and remove a property to filter for
*/
public final void removeFilter(int filter) {
fFilterProperties &= (-1 ^ filter);
}
/**
* Tests if a property is filtered
*/
public final boolean hasFilter(int filter) {
return (fFilterProperties & filter) != 0;
}
/*
* @see ViewerFilter@isFilterProperty
*/
public boolean isFilterProperty(Object element, Object property) {
return false;
}
/*
* @see ViewerFilter@select
*/
public boolean select(Viewer viewer, Object parentElement, Object element) {
try {
if (hasFilter(FILTER_FIELDS) && element instanceof IField) {
return false;
}
if (hasFilter(FILTER_LOCALTYPES) && element instanceof IType && ((IType) element).isLocal()) {
return false;
}
if (element instanceof IMember) {
IMember member= (IMember)element;
if (member.getElementName().startsWith("<")) { // filter out <clinit> //$NON-NLS-1$
return false;
}
int flags= member.getFlags();
if (hasFilter(FILTER_STATIC) && (Flags.isStatic(flags) || isFieldInInterface(member)) && member.getElementType() != IJavaElement.TYPE) {
return false;
}
if (hasFilter(FILTER_NONPUBLIC) && !Flags.isPublic(flags) && !isMemberInInterface(member) && !isTopLevelType(member)) {
return false;
}
}
} catch (JavaModelException e) {
// ignore
}
return true;
}
private boolean isMemberInInterface(IMember member) throws JavaModelException {
IType parent= member.getDeclaringType();
return parent != null && parent.isInterface();
}
private boolean isFieldInInterface(IMember member) throws JavaModelException {
return (member.getElementType() == IJavaElement.FIELD) && member.getDeclaringType().isInterface();
}
private boolean isTopLevelType(IMember member) throws JavaModelException {
IType parent= member.getDeclaringType();
return parent == null;
}
}
|
50,502 |
Bug 50502 Change signature refactoring doesn't update JavaDoc comments
|
I have a class with abstract method. I use the change signature to change the signature of the method. If I delete field, I would expect it to delete the @param from the comment. If I add field, I would expect it to add @param with TODO to the comment. Also all the derived classes have javadoc with @see original method signature. When the refactor changes the signature of all the derived/implementing classes, it should update the @see with new method signature.
|
resolved fixed
|
31a4198
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-11T11:54:12Z | 2004-01-23T20:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testAll58_in.java
|
package p;
abstract class A {
public abstract int m(int a, String[] b[][]);
}
class B extends A {
public int m(int number, String[] b[][]) {
return number + 0;
}
}
class C extends B {
public int m(int a, String[] strings[][]) {
return a + 17;
}
}
|
50,502 |
Bug 50502 Change signature refactoring doesn't update JavaDoc comments
|
I have a class with abstract method. I use the change signature to change the signature of the method. If I delete field, I would expect it to delete the @param from the comment. If I add field, I would expect it to add @param with TODO to the comment. Also all the derived classes have javadoc with @see original method signature. When the refactor changes the signature of all the derived/implementing classes, it should update the @see with new method signature.
|
resolved fixed
|
31a4198
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-11T11:54:12Z | 2004-01-23T20:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testAll58_out.java
|
package p;
abstract class A {
public abstract int m(String[] bbb[][], int abb);
}
class B extends A {
public int m(String[] bbb[][], int number) {
return number + 0;
}
}
class C extends B {
public int m(String[] strings[][], int abb) {
return abb + 17;
}
}
|
50,502 |
Bug 50502 Change signature refactoring doesn't update JavaDoc comments
|
I have a class with abstract method. I use the change signature to change the signature of the method. If I delete field, I would expect it to delete the @param from the comment. If I add field, I would expect it to add @param with TODO to the comment. Also all the derived classes have javadoc with @see original method signature. When the refactor changes the signature of all the derived/implementing classes, it should update the @see with new method signature.
|
resolved fixed
|
31a4198
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-11T11:54:12Z | 2004-01-23T20:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testAll59_out.java
|
package p;
import java.util.*;
class A {
/**
* @param from 1st param of {@link A#getList(boolean, int, char) me}
* @see getList
* @see #getList(boolean, int, char)
* @see #getList(int from, tho long)
* @see #getList(boolean really, int f, char t)
* @param to
* @return list
* @param bogus{@link #getList}
*/
public List getList(boolean really, int f, char t) {
return new ArrayList((int)t-f);
}
/** start here
* Doesn't call {@linkplain #getList(boolean, int, char)}
*
* @see getList
* @see #getList
* @see A#getList(boolean, int, char)
* @see A#getList(int, long, Object[][])
* @see A#getList (
* boolean really,int f, char t
* )
* @see #getList(..)
* @see p.A#getList(int, int, boolean)
* @see <a href="spec.html#section">Java Spec</a>
* @see A# getList(boolean, int, char)
*/
public ArrayList getList(int from, long to, Object[] arr[]) {
return new ArrayList(Arrays.asList(arr).subList(from, (int)to));
}
}
|
50,502 |
Bug 50502 Change signature refactoring doesn't update JavaDoc comments
|
I have a class with abstract method. I use the change signature to change the signature of the method. If I delete field, I would expect it to delete the @param from the comment. If I add field, I would expect it to add @param with TODO to the comment. Also all the derived classes have javadoc with @see original method signature. When the refactor changes the signature of all the derived/implementing classes, it should update the @see with new method signature.
|
resolved fixed
|
31a4198
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-11T11:54:12Z | 2004-01-23T20:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testAll60_in.java
| |
50,502 |
Bug 50502 Change signature refactoring doesn't update JavaDoc comments
|
I have a class with abstract method. I use the change signature to change the signature of the method. If I delete field, I would expect it to delete the @param from the comment. If I add field, I would expect it to add @param with TODO to the comment. Also all the derived classes have javadoc with @see original method signature. When the refactor changes the signature of all the derived/implementing classes, it should update the @see with new method signature.
|
resolved fixed
|
31a4198
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-11T11:54:12Z | 2004-01-23T20:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testAll60_out.java
| |
50,502 |
Bug 50502 Change signature refactoring doesn't update JavaDoc comments
|
I have a class with abstract method. I use the change signature to change the signature of the method. If I delete field, I would expect it to delete the @param from the comment. If I add field, I would expect it to add @param with TODO to the comment. Also all the derived classes have javadoc with @see original method signature. When the refactor changes the signature of all the derived/implementing classes, it should update the @see with new method signature.
|
resolved fixed
|
31a4198
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-11T11:54:12Z | 2004-01-23T20:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
50,502 |
Bug 50502 Change signature refactoring doesn't update JavaDoc comments
|
I have a class with abstract method. I use the change signature to change the signature of the method. If I delete field, I would expect it to delete the @param from the comment. If I add field, I would expect it to add @param with TODO to the comment. Also all the derived classes have javadoc with @see original method signature. When the refactor changes the signature of all the derived/implementing classes, it should update the @see with new method signature.
|
resolved fixed
|
31a4198
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-11T11:54:12Z | 2004-01-23T20:33:20Z |
cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java
| |
50,502 |
Bug 50502 Change signature refactoring doesn't update JavaDoc comments
|
I have a class with abstract method. I use the change signature to change the signature of the method. If I delete field, I would expect it to delete the @param from the comment. If I add field, I would expect it to add @param with TODO to the comment. Also all the derived classes have javadoc with @see original method signature. When the refactor changes the signature of all the derived/implementing classes, it should update the @see with new method signature.
|
resolved fixed
|
31a4198
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-11T11:54:12Z | 2004-01-23T20:33:20Z |
org.eclipse.jdt.ui/core
| |
50,502 |
Bug 50502 Change signature refactoring doesn't update JavaDoc comments
|
I have a class with abstract method. I use the change signature to change the signature of the method. If I delete field, I would expect it to delete the @param from the comment. If I add field, I would expect it to add @param with TODO to the comment. Also all the derived classes have javadoc with @see original method signature. When the refactor changes the signature of all the derived/implementing classes, it should update the @see with new method signature.
|
resolved fixed
|
31a4198
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-11T11:54:12Z | 2004-01-23T20:33:20Z |
extension/org/eclipse/jdt/internal/corext/dom/NodeInfoStore.java
| |
50,502 |
Bug 50502 Change signature refactoring doesn't update JavaDoc comments
|
I have a class with abstract method. I use the change signature to change the signature of the method. If I delete field, I would expect it to delete the @param from the comment. If I add field, I would expect it to add @param with TODO to the comment. Also all the derived classes have javadoc with @see original method signature. When the refactor changes the signature of all the derived/implementing classes, it should update the @see with new method signature.
|
resolved fixed
|
31a4198
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-11T11:54:12Z | 2004-01-23T20:33:20Z |
org.eclipse.jdt.ui/core
| |
50,502 |
Bug 50502 Change signature refactoring doesn't update JavaDoc comments
|
I have a class with abstract method. I use the change signature to change the signature of the method. If I delete field, I would expect it to delete the @param from the comment. If I add field, I would expect it to add @param with TODO to the comment. Also all the derived classes have javadoc with @see original method signature. When the refactor changes the signature of all the derived/implementing classes, it should update the @see with new method signature.
|
resolved fixed
|
31a4198
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-11T11:54:12Z | 2004-01-23T20:33:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/ParameterInfo.java
| |
50,502 |
Bug 50502 Change signature refactoring doesn't update JavaDoc comments
|
I have a class with abstract method. I use the change signature to change the signature of the method. If I delete field, I would expect it to delete the @param from the comment. If I add field, I would expect it to add @param with TODO to the comment. Also all the derived classes have javadoc with @see original method signature. When the refactor changes the signature of all the derived/implementing classes, it should update the @see with new method signature.
|
resolved fixed
|
31a4198
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-11T11:54:12Z | 2004-01-23T20:33:20Z |
org.eclipse.jdt.ui/core
| |
50,502 |
Bug 50502 Change signature refactoring doesn't update JavaDoc comments
|
I have a class with abstract method. I use the change signature to change the signature of the method. If I delete field, I would expect it to delete the @param from the comment. If I add field, I would expect it to add @param with TODO to the comment. Also all the derived classes have javadoc with @see original method signature. When the refactor changes the signature of all the derived/implementing classes, it should update the @see with new method signature.
|
resolved fixed
|
31a4198
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-11T11:54:12Z | 2004-01-23T20:33:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureRefactoring.java
| |
54,468 |
Bug 54468 Remove non-default-encoding-alert from CompilationUnitEditor
|
no longer necessary with new encoding support.
|
resolved fixed
|
40f73c4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-15T10:21:18Z | 2004-03-11T15:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditor.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.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import org.eclipse.core.resources.IFile;
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.Preferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IAutoEditStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentExtension;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.ILineTracker;
import org.eclipse.jface.text.IPositionUpdater;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.IWidgetTokenKeeper;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistantExtension;
import org.eclipse.jface.text.link.ExclusivePositionUpdater;
import org.eclipse.jface.text.link.ILinkedListener;
import org.eclipse.jface.text.link.LinkedEnvironment;
import org.eclipse.jface.text.link.LinkedPositionGroup;
import org.eclipse.jface.text.link.LinkedUIControl;
import org.eclipse.jface.text.link.LinkedUIControl.ExitFlags;
import org.eclipse.jface.text.link.LinkedUIControl.IExitPolicy;
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.SourceViewerConfiguration;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.editors.text.IStorageDocumentProvider;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.ContentAssistAction;
import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.texteditor.link.EditorHistoryUpdater;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
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.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
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.AddBlockCommentAction;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.IndentAction;
import org.eclipse.jdt.internal.ui.actions.RemoveBlockCommentAction;
import org.eclipse.jdt.internal.ui.compare.LocalHistoryActionGroup;
import org.eclipse.jdt.internal.ui.text.ContentAssistPreference;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionAssistant;
import org.eclipse.jdt.internal.ui.text.java.IReconcilingParticipant;
import org.eclipse.jdt.internal.ui.text.java.SmartSemicolonAutoEditStrategy;
/**
* Java specific text editor.
*/
public class CompilationUnitEditor extends JavaEditor implements IReconcilingParticipant {
/**
* Text operation code for requesting correction assist to show correction
* proposals for the current position.
*/
public static final int CORRECTIONASSIST_PROPOSALS= 50;
/**
* Text operation code for requesting common prefix completion.
*/
public static final int CONTENTASSIST_COMPLETE_PREFIX= 60;
interface ITextConverter {
void customizeDocumentCommand(IDocument document, DocumentCommand command);
}
class AdaptedSourceViewer extends JavaSourceViewer {
private List fTextConverters;
private boolean fIgnoreTextConverters= false;
private JavaCorrectionAssistant fCorrectionAssistant;
public AdaptedSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles) {
super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles);
}
public IContentAssistant getContentAssistant() {
return fContentAssistant;
}
/*
* @see ITextOperationTarget#doOperation(int)
*/
public void doOperation(int operation) {
if (getTextWidget() == null)
return;
switch (operation) {
case CONTENTASSIST_PROPOSALS:
String msg= fContentAssistant.showPossibleCompletions();
setStatusLineErrorMessage(msg);
return;
case CORRECTIONASSIST_PROPOSALS:
msg= fCorrectionAssistant.showPossibleCompletions();
setStatusLineErrorMessage(msg);
return;
case UNDO:
fIgnoreTextConverters= true;
break;
case REDO:
fIgnoreTextConverters= true;
break;
case CONTENTASSIST_COMPLETE_PREFIX:
if (fContentAssistant instanceof IContentAssistantExtension) {
msg= ((IContentAssistantExtension) fContentAssistant).completePrefix();
setStatusLineErrorMessage(msg);
return;
} else
break;
}
super.doOperation(operation);
}
/*
* @see ITextOperationTarget#canDoOperation(int)
*/
public boolean canDoOperation(int operation) {
if (operation == CORRECTIONASSIST_PROPOSALS)
return isEditable();
else if (operation == CONTENTASSIST_COMPLETE_PREFIX)
return isEditable();
return super.canDoOperation(operation);
}
/**
* @inheritDoc
* @since 3.0
*/
public void unconfigure() {
if (fCorrectionAssistant != null) {
fCorrectionAssistant.uninstall();
fCorrectionAssistant= null;
}
super.unconfigure();
}
public void insertTextConverter(ITextConverter textConverter, int index) {
throw new UnsupportedOperationException();
}
public void addTextConverter(ITextConverter textConverter) {
if (fTextConverters == null) {
fTextConverters= new ArrayList(1);
fTextConverters.add(textConverter);
} else if (!fTextConverters.contains(textConverter))
fTextConverters.add(textConverter);
}
public void removeTextConverter(ITextConverter textConverter) {
if (fTextConverters != null) {
fTextConverters.remove(textConverter);
if (fTextConverters.size() == 0)
fTextConverters= null;
}
}
/*
* @see TextViewer#customizeDocumentCommand(DocumentCommand)
*/
protected void customizeDocumentCommand(DocumentCommand command) {
super.customizeDocumentCommand(command);
if (!fIgnoreTextConverters && fTextConverters != null) {
for (Iterator e = fTextConverters.iterator(); e.hasNext();)
((ITextConverter) e.next()).customizeDocumentCommand(getDocument(), command);
}
fIgnoreTextConverters= false;
}
// http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
public void updateIndentationPrefixes() {
SourceViewerConfiguration configuration= getSourceViewerConfiguration();
String[] types= configuration.getConfiguredContentTypes(this);
for (int i= 0; i < types.length; i++) {
String[] prefixes= configuration.getIndentPrefixes(this, types[i]);
if (prefixes != null && prefixes.length > 0)
setIndentPrefixes(prefixes, types[i]);
}
}
/*
* @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
*/
public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
if (WorkbenchHelp.isContextHelpDisplayed())
return false;
return super.requestWidgetToken(requester);
}
/*
* @see IWidgetTokenOwnerExtension#requestWidgetToken(IWidgetTokenKeeper, int)
* @since 3.0
*/
public boolean requestWidgetToken(IWidgetTokenKeeper requester, int priority) {
if (WorkbenchHelp.isContextHelpDisplayed())
return false;
return super.requestWidgetToken(requester, priority);
}
/*
* @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
*/
public void configure(SourceViewerConfiguration configuration) {
super.configure(configuration);
fCorrectionAssistant= new JavaCorrectionAssistant(CompilationUnitEditor.this);
fCorrectionAssistant.install(this);
IAutoEditStrategy smartSemi= new SmartSemicolonAutoEditStrategy(IJavaPartitions.JAVA_PARTITIONING);
prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE);
}
}
static class TabConverter implements ITextConverter {
private int fTabRatio;
private ILineTracker fLineTracker;
public TabConverter() {
}
public void setNumberOfSpacesPerTab(int ratio) {
fTabRatio= ratio;
}
public void setLineTracker(ILineTracker lineTracker) {
fLineTracker= lineTracker;
}
private int insertTabString(StringBuffer buffer, int offsetInLine) {
if (fTabRatio == 0)
return 0;
int remainder= offsetInLine % fTabRatio;
remainder= fTabRatio - remainder;
for (int i= 0; i < remainder; i++)
buffer.append(' ');
return remainder;
}
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
String text= command.text;
if (text == null)
return;
int index= text.indexOf('\t');
if (index > -1) {
StringBuffer buffer= new StringBuffer();
fLineTracker.set(command.text);
int lines= fLineTracker.getNumberOfLines();
try {
for (int i= 0; i < lines; i++) {
int offset= fLineTracker.getLineOffset(i);
int endOffset= offset + fLineTracker.getLineLength(i);
String line= text.substring(offset, endOffset);
int position= 0;
if (i == 0) {
IRegion firstLine= document.getLineInformationOfOffset(command.offset);
position= command.offset - firstLine.getOffset();
}
int length= line.length();
for (int j= 0; j < length; j++) {
char c= line.charAt(j);
if (c == '\t') {
position += insertTabString(buffer, position);
} else {
buffer.append(c);
++ position;
}
}
}
command.text= buffer.toString();
} catch (BadLocationException x) {
}
}
}
}
private class ExitPolicy implements IExitPolicy {
final char fExitCharacter;
final char fEscapeCharacter;
final Stack fStack;
final int fSize;
public ExitPolicy(char exitCharacter, char escapeCharacter, Stack stack) {
fExitCharacter= exitCharacter;
fEscapeCharacter= escapeCharacter;
fStack= stack;
fSize= fStack.size();
}
/*
* @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int)
*/
public ExitFlags doExit(LinkedEnvironment environment, VerifyEvent event, int offset, int length) {
if (event.character == fExitCharacter) {
if (fSize == fStack.size() && !isMasked(offset)) {
BracketLevel level= (BracketLevel) fStack.peek();
if (level.fFirstPosition.offset > offset || level.fSecondPosition.offset < offset)
return null;
if (level.fSecondPosition.offset == offset && length == 0)
// don't enter the character if if its the closing peer
return new ExitFlags(ILinkedListener.UPDATE_CARET, false);
else
return new ExitFlags(ILinkedListener.UPDATE_CARET, true);
}
}
return null;
}
private boolean isMasked(int offset) {
IDocument document= getSourceViewer().getDocument();
try {
return fEscapeCharacter == document.getChar(offset - 1);
} catch (BadLocationException e) {
}
return false;
}
}
private static class BracketLevel {
int fOffset;
int fLength;
LinkedUIControl fEditor;
Position fFirstPosition;
Position fSecondPosition;
}
private class BracketInserter implements VerifyKeyListener, ILinkedListener {
private boolean fCloseBrackets= true;
private boolean fCloseStrings= true;
private final String CATEGORY= toString();
private IPositionUpdater fUpdater= new ExclusivePositionUpdater(CATEGORY);
private Stack fBracketLevelStack= new Stack();
public void setCloseBracketsEnabled(boolean enabled) {
fCloseBrackets= enabled;
}
public void setCloseStringsEnabled(boolean enabled) {
fCloseStrings= enabled;
}
private boolean hasIdentifierToTheRight(IDocument document, int offset) {
try {
int end= offset;
IRegion endLine= document.getLineInformationOfOffset(end);
int maxEnd= endLine.getOffset() + endLine.getLength();
while (end != maxEnd && Character.isWhitespace(document.getChar(end)))
++end;
return end != maxEnd && Character.isJavaIdentifierPart(document.getChar(end));
} catch (BadLocationException e) {
// be conservative
return true;
}
}
private boolean hasIdentifierToTheLeft(IDocument document, int offset) {
try {
int start= offset;
IRegion startLine= document.getLineInformationOfOffset(start);
int minStart= startLine.getOffset();
while (start != minStart && Character.isWhitespace(document.getChar(start - 1)))
--start;
return start != minStart && Character.isJavaIdentifierPart(document.getChar(start - 1));
} catch (BadLocationException e) {
return true;
}
}
private boolean hasCharacterToTheRight(IDocument document, int offset, char character) {
try {
int end= offset;
IRegion endLine= document.getLineInformationOfOffset(end);
int maxEnd= endLine.getOffset() + endLine.getLength();
while (end != maxEnd && Character.isWhitespace(document.getChar(end)))
++end;
return end != maxEnd && document.getChar(end) == character;
} catch (BadLocationException e) {
// be conservative
return true;
}
}
/*
* @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
*/
public void verifyKey(VerifyEvent event) {
if (!event.doit || getInsertMode() != SMART_INSERT)
return;
final ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
final Point selection= sourceViewer.getSelectedRange();
final int offset= selection.x;
final int length= selection.y;
switch (event.character) {
case '(':
if (hasCharacterToTheRight(document, offset + length, '('))
return;
// fall through
case '[':
if (!fCloseBrackets)
return;
if (hasIdentifierToTheRight(document, offset + length))
return;
// fall through
case '\'':
if (event.character == '\'') {
if (!fCloseStrings)
return;
if (hasIdentifierToTheLeft(document, offset) || hasIdentifierToTheRight(document, offset + length))
return;
}
// fall through
case '"':
if (event.character == '"') {
if (!fCloseStrings)
return;
if (hasIdentifierToTheLeft(document, offset) || hasIdentifierToTheRight(document, offset + length))
return;
}
try {
ITypedRegion partition= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, offset);
if (! IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) && partition.getOffset() != offset)
return;
if (!validateEditorInputState())
return;
final char character= event.character;
final char closingCharacter= getPeerCharacter(character);
final StringBuffer buffer= new StringBuffer();
buffer.append(character);
buffer.append(closingCharacter);
document.replace(offset, length, buffer.toString());
BracketLevel level= new BracketLevel();
fBracketLevelStack.push(level);
LinkedPositionGroup group= new LinkedPositionGroup();
group.createPosition(document, offset + 1, 0);
LinkedEnvironment env= new LinkedEnvironment();
env.addLinkedListener(this);
env.addGroup(group);
env.forceInstall();
level.fOffset= offset;
level.fLength= 2;
// set up position tracking for our magic peers
if (fBracketLevelStack.size() == 1) {
document.addPositionCategory(CATEGORY);
document.addPositionUpdater(fUpdater);
}
level.fFirstPosition= new Position(offset, 1);
level.fSecondPosition= new Position(offset + 1, 1);
document.addPosition(CATEGORY, level.fFirstPosition);
document.addPosition(CATEGORY, level.fSecondPosition);
level.fEditor= new LinkedUIControl(env, sourceViewer);
level.fEditor.setPositionListener(new EditorHistoryUpdater());
level.fEditor.setExitPolicy(new ExitPolicy(closingCharacter, getEscapeCharacter(closingCharacter), fBracketLevelStack));
level.fEditor.setExitPosition(sourceViewer, offset + 2, 0, Integer.MAX_VALUE);
level.fEditor.setCyclingMode(LinkedUIControl.CYCLE_NEVER);
level.fEditor.enter();
IRegion newSelection= level.fEditor.getSelectedRegion();
sourceViewer.setSelectedRange(newSelection.getOffset(), newSelection.getLength());
event.doit= false;
} catch (BadLocationException e) {
JavaPlugin.log(e);
} catch (BadPositionCategoryException e) {
JavaPlugin.log(e);
}
break;
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#left(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment, int)
*/
public void left(LinkedEnvironment environment, int flags) {
final BracketLevel level= (BracketLevel) fBracketLevelStack.pop();
if (flags != ILinkedListener.EXTERNAL_MODIFICATION)
return;
// remove brackets
final ISourceViewer sourceViewer= getSourceViewer();
final IDocument document= sourceViewer.getDocument();
if (document instanceof IDocumentExtension) {
IDocumentExtension extension= (IDocumentExtension) document;
extension.registerPostNotificationReplace(null, new IDocumentExtension.IReplace() {
public void perform(IDocument d, IDocumentListener owner) {
if ((level.fFirstPosition.isDeleted || level.fFirstPosition.length == 0) && !level.fSecondPosition.isDeleted && level.fSecondPosition.offset == level.fFirstPosition.offset) {
try {
document.replace(level.fSecondPosition.offset, level.fSecondPosition.length, null);
} catch (BadLocationException e) {
}
}
if (fBracketLevelStack.size() == 0) {
document.removePositionUpdater(fUpdater);
try {
document.removePositionCategory(CATEGORY);
} catch (BadPositionCategoryException e) {
}
}
}
});
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#suspend(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment)
*/
public void suspend(LinkedEnvironment environment) {
}
/*
* @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#resume(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment, int)
*/
public void resume(LinkedEnvironment environment, int flags) {
}
}
/**
* Remembers data related to the current selection to be able to
* restore it later.
*
* @since 3.0
*/
private class RememberedSelection {
/** The remembered selection start. */
private RememberedOffset fStartOffset= new RememberedOffset();
/** The remembered selection end. */
private RememberedOffset fEndOffset= new RememberedOffset();
/**
* Remember current selection.
*/
public void remember() {
/* https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257
* This method may be called inside an async call posted
* to the UI thread, so protect against intermediate disposal
* of the editor.
*/
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
IRegion selection= getSignedSelection(viewer);
int startOffset= selection.getOffset();
int endOffset= startOffset + selection.getLength();
fStartOffset.setOffset(startOffset);
fEndOffset.setOffset(endOffset);
}
}
/**
* Restore remembered selection.
*/
public void restore() {
/* https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257
* This method may be called inside an async call posted
* to the UI thread, so protect against intermediate disposal
* of the editor.
*/
if (getSourceViewer() == null)
return;
try {
int startOffset= fStartOffset.getOffset();
int endOffset= fEndOffset.getOffset();
if (startOffset == -1)
startOffset= endOffset; // fallback to caret offset
if (endOffset == -1)
endOffset= startOffset; // fallback to other offset
IJavaElement element;
if (endOffset == -1) {
// fallback to element selection
element= fEndOffset.getElement();
if (element == null)
element= fStartOffset.getElement();
if (element != null)
setSelection(element);
return;
}
if (isValidSelection(startOffset, endOffset - startOffset))
selectAndReveal(startOffset, endOffset - startOffset);
} finally {
fStartOffset.clear();
fEndOffset.clear();
}
}
private boolean isValidSelection(int offset, int length) {
IDocumentProvider provider= getDocumentProvider();
if (provider != null) {
IDocument document= provider.getDocument(getEditorInput());
if (document != null) {
int end= offset + length;
int documentLength= document.getLength();
return 0 <= offset && offset <= documentLength && 0 <= end && end <= documentLength;
}
}
return false;
}
}
/**
* Remembers additional data for a given
* offset to be able restore it later.
*
* @since 3.0
*/
private class RememberedOffset {
/** Remembered line for the given offset */
private int fLine;
/** Remembered column for the given offset*/
private int fColumn;
/** Remembered Java element for the given offset*/
private IJavaElement fElement;
/** Remembered Java element line for the given offset*/
private int fElementLine;
/**
* Store visual properties of the given offset.
*
* @param offset Offset in the document
*/
public void setOffset(int offset) {
try {
IDocument document= getSourceViewer().getDocument();
fLine= document.getLineOfOffset(offset);
fColumn= offset - document.getLineOffset(fLine);
fElement= getElementAt(offset, true);
fElementLine= -1;
if (fElement instanceof IMember) {
ISourceRange range= ((IMember) fElement).getNameRange();
if (range != null)
fElementLine= document.getLineOfOffset(range.getOffset());
}
if (fElementLine == -1)
fElementLine= document.getLineOfOffset(getOffset(fElement));
} catch (BadLocationException e) {
// should not happen
JavaPlugin.log(e);
clear();
} catch (JavaModelException e) {
// should not happen
JavaPlugin.log(e.getStatus());
clear();
}
}
/**
* Return offset recomputed from stored visual properties.
*
* @return Offset in the document
*/
public int getOffset() {
try {
IJavaElement newElement= getElement();
if (newElement == null)
return -1;
IDocument document= getSourceViewer().getDocument();
int newElementLine= -1;
if (newElement instanceof IMember) {
ISourceRange range= ((IMember) newElement).getNameRange();
if (range != null)
newElementLine= document.getLineOfOffset(range.getOffset());
}
if (newElementLine == -1)
newElementLine= document.getLineOfOffset(getOffset(newElement));
if (newElementLine == -1)
return -1;
int newLine= fLine + newElementLine - fElementLine;
if (newLine < 0 || newLine >= document.getNumberOfLines())
return -1;
int maxColumn= document.getLineLength(newLine);
String lineDelimiter= document.getLineDelimiter(newLine);
if (lineDelimiter != null)
maxColumn= maxColumn - lineDelimiter.length();
int offset;
if (fColumn > maxColumn)
offset= document.getLineOffset(newLine) + maxColumn;
else
offset= document.getLineOffset(newLine) + fColumn;
if (!containsOffset(newElement, offset) && (offset == 0 || !containsOffset(newElement, offset - 1)))
return -1;
return offset;
} catch (BadLocationException e) {
// should not happen
JavaPlugin.log(e);
return -1;
} catch (JavaModelException e) {
// should not happen
JavaPlugin.log(e.getStatus());
return -1;
}
}
/**
* Return Java element recomputed from stored visual properties.
*
* @return Java element
*/
public IJavaElement getElement() {
if (fElement == null)
return null;
return findElement(fElement);
}
/**
* Clears the stored position
*/
public void clear() {
fLine= -1;
fColumn= -1;
fElement= null;
fElementLine= -1;
}
/**
* Does the given Java element contain the given offset?
* @param element Java element
* @param offset Offset
* @return <code>true</code> iff the Java element contains the offset
*/
private boolean containsOffset(IJavaElement element, int offset) {
int elementOffset= getOffset(element);
int elementLength= getLength(element);
return (elementOffset > -1 && elementLength > -1) ? (offset >= elementOffset && offset < elementOffset + elementLength) : false;
}
/**
* Returns the offset of the given Java element.
*
* @param element Java element
* @return Offset of the given Java element
*/
private int getOffset(IJavaElement element) {
if (element instanceof ISourceReference) {
ISourceReference sr= (ISourceReference) element;
try {
ISourceRange srcRange= sr.getSourceRange();
if (srcRange != null)
return srcRange.getOffset();
} catch (JavaModelException e) {
}
}
return -1;
}
/**
* Returns the length of the given Java element.
*
* @param element Java element
* @return Length of the given Java element
*/
private int getLength(IJavaElement element) {
if (element instanceof ISourceReference) {
ISourceReference sr= (ISourceReference) element;
try {
ISourceRange srcRange= sr.getSourceRange();
if (srcRange != null)
return srcRange.getLength();
} catch (JavaModelException e) {
}
}
return -1;
}
/**
* Returns the updated java element for the old java element.
*
* @param element Old Java element
* @return Updated Java element
*/
private IJavaElement findElement(IJavaElement element) {
if (element == null)
return null;
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
if (unit != null) {
try {
synchronized (unit) {
unit.reconcile(false, null);
}
IJavaElement[] findings= unit.findElements(element);
if (findings != null && findings.length > 0)
return findings[0];
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
// nothing found, be tolerant and go on
}
}
return null;
}
}
/** Preference key for code formatter tab size */
private final static String CODE_FORMATTER_TAB_SIZE= JavaCore.FORMATTER_TAB_SIZE;
/** Preference key for inserting spaces rather than tabs */
private final static String SPACES_FOR_TABS= PreferenceConstants.EDITOR_SPACES_FOR_TABS;
/** Preference key for automatically closing strings */
private final static String CLOSE_STRINGS= PreferenceConstants.EDITOR_CLOSE_STRINGS;
/** Preference key for automatically closing brackets and parenthesis */
private final static String CLOSE_BRACKETS= PreferenceConstants.EDITOR_CLOSE_BRACKETS;
/** The editor's save policy */
protected ISavePolicy fSavePolicy;
/** Listener to annotation model changes that updates the error tick in the tab image */
private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater;
/** The editor's tab converter */
private TabConverter fTabConverter;
/**
* The remembered selection.
* @since 3.0
*/
private RememberedSelection fRememberedSelection= new RememberedSelection();
/** The bracket inserter. */
private BracketInserter fBracketInserter= new BracketInserter();
/** The standard action groups added to the menu */
private GenerateActionGroup fGenerateActionGroup;
private CompositeActionGroup fContextMenuGroup;
/**
* Creates a new compilation unit editor.
*/
public CompilationUnitEditor() {
super();
setDocumentProvider(JavaPlugin.getDefault().getCompilationUnitDocumentProvider());
setEditorContextMenuId("#CompilationUnitEditorContext"); //$NON-NLS-1$
setRulerContextMenuId("#CompilationUnitRulerContext"); //$NON-NLS-1$
setOutlinerContextMenuId("#CompilationUnitOutlinerContext"); //$NON-NLS-1$
// don't set help contextId, we install our own help context
fSavePolicy= null;
fJavaEditorErrorTickUpdater= new JavaEditorErrorTickUpdater(this);
}
/*
* @see AbstractTextEditor#createActions()
*/
protected void createActions() {
super.createActions();
Action action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS);
setAction("CorrectionAssistProposal", action); //$NON-NLS-1$
markAsStateDependentAction("CorrectionAssistProposal", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.QUICK_FIX_ACTION);
action= new ContentAssistAction(JavaEditorMessages.getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
setAction("ContentAssistProposal", action); //$NON-NLS-1$
markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.CONTENT_ASSIST_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ContentAssistContextInformation.", this, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
setAction("ContentAssistContextInformation", action); //$NON-NLS-1$
markAsStateDependentAction("ContentAssistContextInformation", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX);
setAction("ContentAssistCompletePrefix", action); //$NON-NLS-1$
markAsStateDependentAction("ContentAssistCompletePrefix", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.COMMENT);
setAction("Comment", action); //$NON-NLS-1$
markAsStateDependentAction("Comment", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.UNCOMMENT);
setAction("Uncomment", action); //$NON-NLS-1$
markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION);
action= new ToggleCommentAction(JavaEditorMessages.getResourceBundle(), "ToggleComment.", this, getSourceViewerConfiguration().getDefaultPrefixes(getSourceViewer(), "")); //$NON-NLS-1$ //$NON-NLS-2$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.TOGGLE_COMMENT);
setAction("ToggleComment", action); //$NON-NLS-1$
markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.TOGGLE_COMMENT_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.FORMAT);
setAction("Format", action); //$NON-NLS-1$
markAsStateDependentAction("Format", true); //$NON-NLS-1$
markAsSelectionDependentAction("Format", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION);
action= new AddBlockCommentAction(JavaEditorMessages.getResourceBundle(), "AddBlockComment.", this); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
setAction("AddBlockComment", action); //$NON-NLS-1$
markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
action= new RemoveBlockCommentAction(JavaEditorMessages.getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
setAction("RemoveBlockComment", action); //$NON-NLS-1$
markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.REMOVE_BLOCK_COMMENT_ACTION);
action= new IndentAction(JavaEditorMessages.getResourceBundle(), "Indent.", this, false); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.INDENT);
setAction("Indent", action); //$NON-NLS-1$
markAsStateDependentAction("Indent", true); //$NON-NLS-1$
markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
action= new IndentAction(JavaEditorMessages.getResourceBundle(), "Indent.", this, true); //$NON-NLS-1$
setAction("IndentOnTab", action); //$NON-NLS-1$
markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
if (getNewPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_TAB)) {
// don't replace Shift Right - have to make sure their enablement is mutually exclusive
// removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT);
setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$
}
fGenerateActionGroup= new GenerateActionGroup(this, ITextEditorActionConstants.GROUP_EDIT);
ActionGroup rg= new RefactorActionGroup(this, ITextEditorActionConstants.GROUP_EDIT);
fActionGroups.addGroup(rg);
fActionGroups.addGroup(fGenerateActionGroup);
// We have to keep the context menu group separate to have better control over positioning
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {
fGenerateActionGroup,
rg,
new LocalHistoryActionGroup(this, ITextEditorActionConstants.GROUP_EDIT)});
}
/*
* @see JavaEditor#getElementAt(int)
*/
protected IJavaElement getElementAt(int offset) {
return getElementAt(offset, true);
}
/**
* Returns the most narrow element including the given offset. If <code>reconcile</code>
* is <code>true</code> the editor's input element is reconciled in advance. If it is
* <code>false</code> this method only returns a result if the editor's input element
* does not need to be reconciled.
*
* @param offset the offset included by the retrieved element
* @param reconcile <code>true</code> if working copy should be reconciled
*/
protected IJavaElement getElementAt(int offset, boolean reconcile) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
if (unit != null) {
try {
if (reconcile) {
synchronized (unit) {
unit.reconcile(false, null);
}
return unit.getElementAt(offset);
} else if (unit.isConsistent())
return unit.getElementAt(offset);
} catch (JavaModelException x) {
if (!x.isDoesNotExist())
JavaPlugin.log(x.getStatus());
// nothing found, be tolerant and go on
}
}
return null;
}
/*
* @see JavaEditor#getCorrespondingElement(IJavaElement)
*/
protected IJavaElement getCorrespondingElement(IJavaElement element) {
try {
return EditorUtility.getWorkingCopy(element, true);
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
// nothing found, be tolerant and go on
}
return null;
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#getInputElement()
*/
protected IJavaElement getInputJavaElement() {
return JavaPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(getEditorInput());
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/*
* @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
*/
protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
if (page != null) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
page.setInput(manager.getWorkingCopy(input));
}
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean, org.eclipse.core.runtime.IProgressMonitor)
*/
protected void performSave(boolean overwrite, IProgressMonitor progressMonitor) {
IDocumentProvider p= getDocumentProvider();
if (p instanceof ICompilationUnitDocumentProvider) {
ICompilationUnitDocumentProvider cp= (ICompilationUnitDocumentProvider) p;
cp.setSavePolicy(fSavePolicy);
}
try {
super.performSave(overwrite, progressMonitor);
} finally {
if (p instanceof ICompilationUnitDocumentProvider) {
ICompilationUnitDocumentProvider cp= (ICompilationUnitDocumentProvider) p;
cp.setSavePolicy(null);
}
}
}
/*
* @see AbstractTextEditor#doSaveAs
*/
public void doSaveAs() {
if (askIfNonWorkbenchEncodingIsOk()) {
super.doSaveAs();
}
}
/*
* @see AbstractTextEditor#doSave(IProgressMonitor)
*/
public void doSave(IProgressMonitor progressMonitor) {
IDocumentProvider p= getDocumentProvider();
if (p == null) {
// editor has been closed
return;
}
if (!askIfNonWorkbenchEncodingIsOk()) {
progressMonitor.setCanceled(true);
return;
}
if (p.isDeleted(getEditorInput())) {
if (isSaveAsAllowed()) {
/*
* 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors.
* Changed Behavior to make sure that if called inside a regular save (because
* of deletion of input element) there is a way to report back to the caller.
*/
performSaveAs(progressMonitor);
} else {
/*
* 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there
* Missing resources.
*/
Shell shell= getSite().getShell();
MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title1"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
setStatusLineErrorMessage(null);
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
if (unit != null) {
synchronized (unit) {
performSave(false, progressMonitor);
}
} else
performSave(false, progressMonitor);
}
}
/**
* Asks the user if it is OK to store in non-workbench encoding.
* @return <code>true</code> if the user wants to continue
*/
private boolean askIfNonWorkbenchEncodingIsOk() {
IDocumentProvider provider= getDocumentProvider();
if (provider instanceof IStorageDocumentProvider) {
IEditorInput input= getEditorInput();
IStorageDocumentProvider storageProvider= (IStorageDocumentProvider)provider;
String encoding= storageProvider.getEncoding(input);
String defaultEncoding= storageProvider.getDefaultEncoding();
if (encoding != null && !encoding.equals(defaultEncoding)) {
Shell shell= getSite().getShell();
String title= JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$
String msg;
if (input != null)
msg= MessageFormat.format(JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.message1"), new String[] {input.getName(), encoding});//$NON-NLS-1$
else
msg= MessageFormat.format(JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.message2"), new String[] {encoding});//$NON-NLS-1$
return MessageDialog.openQuestion(shell, title, msg);
}
}
return true;
}
public boolean isSaveAsAllowed() {
return true;
}
/**
* The compilation unit editor implementation of this <code>AbstractTextEditor</code>
* method asks the user for the workspace path of a file resource and saves the document
* there. See http://dev.eclipse.org/bugs/show_bug.cgi?id=6295
*/
protected void performSaveAs(IProgressMonitor progressMonitor) {
Shell shell= getSite().getShell();
IEditorInput input = getEditorInput();
SaveAsDialog dialog= new SaveAsDialog(shell);
IFile original= (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null;
if (original != null)
dialog.setOriginalFile(original);
dialog.create();
IDocumentProvider provider= getDocumentProvider();
if (provider == null) {
// editor has been programmatically closed while the dialog was open
return;
}
if (provider.isDeleted(input) && original != null) {
String message= JavaEditorMessages.getFormattedString("CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$
dialog.setErrorMessage(null);
dialog.setMessage(message, IMessageProvider.WARNING);
}
if (dialog.open() == Window.CANCEL) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IPath filePath= dialog.getResult();
if (filePath == null) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
IFile file= workspaceRoot.getFile(filePath);
final IEditorInput newInput= new FileEditorInput(file);
boolean success= false;
try {
provider.aboutToChange(newInput);
getDocumentProvider().saveDocument(progressMonitor, newInput, getDocumentProvider().getDocument(getEditorInput()), true);
success= true;
} catch (CoreException x) {
ErrorDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title2"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), x.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
} finally {
provider.changed(newInput);
if (success)
setInput(newInput);
}
if (progressMonitor != null)
progressMonitor.setCanceled(!success);
}
/*
* @see AbstractTextEditor#doSetInput(IEditorInput)
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
configureTabConverter();
}
private void configureTabConverter() {
if (fTabConverter != null) {
IDocumentProvider provider= getDocumentProvider();
if (provider instanceof ICompilationUnitDocumentProvider) {
ICompilationUnitDocumentProvider cup= (ICompilationUnitDocumentProvider) provider;
fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput()));
}
}
}
private int getTabSize() {
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
return preferences.getInt(CODE_FORMATTER_TAB_SIZE);
}
private void startTabConversion() {
if (fTabConverter == null) {
fTabConverter= new TabConverter();
configureTabConverter();
fTabConverter.setNumberOfSpacesPerTab(getTabSize());
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
asv.addTextConverter(fTabConverter);
// http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
asv.updateIndentationPrefixes();
}
}
private void stopTabConversion() {
if (fTabConverter != null) {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
asv.removeTextConverter(fTabConverter);
// http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
asv.updateIndentationPrefixes();
fTabConverter= null;
}
}
private boolean isTabConversionEnabled() {
IPreferenceStore store= getNewPreferenceStore();
return store.getBoolean(SPACES_FOR_TABS);
}
public void dispose() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension)
((ITextViewerExtension) sourceViewer).removeVerifyKeyListener(fBracketInserter);
if (fJavaEditorErrorTickUpdater != null) {
fJavaEditorErrorTickUpdater.dispose();
fJavaEditorErrorTickUpdater= null;
}
if (fActionGroups != null) {
fActionGroups.dispose();
fActionGroups= null;
}
super.dispose();
}
/*
* @see AbstractTextEditor#createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
if (isTabConversionEnabled())
startTabConversion();
IPreferenceStore preferenceStore= getNewPreferenceStore();
boolean closeBrackets= preferenceStore.getBoolean(CLOSE_BRACKETS);
boolean closeStrings= preferenceStore.getBoolean(CLOSE_STRINGS);
fBracketInserter.setCloseBracketsEnabled(closeBrackets);
fBracketInserter.setCloseStringsEnabled(closeStrings);
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension)
((ITextViewerExtension) sourceViewer).prependVerifyKeyListener(fBracketInserter);
}
private static char getEscapeCharacter(char character) {
switch (character) {
case '"':
case '\'':
return '\\';
default:
return 0;
}
}
private static char getPeerCharacter(char character) {
switch (character) {
case '(':
return ')';
case ')':
return '(';
case '[':
return ']';
case ']':
return '[';
case '"':
return character;
case '\'':
return character;
default:
throw new IllegalArgumentException();
}
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
if (asv != null) {
String p= event.getProperty();
if (CLOSE_BRACKETS.equals(p)) {
fBracketInserter.setCloseBracketsEnabled(getNewPreferenceStore().getBoolean(p));
return;
}
if (CLOSE_STRINGS.equals(p)) {
fBracketInserter.setCloseStringsEnabled(getNewPreferenceStore().getBoolean(p));
return;
}
if (SPACES_FOR_TABS.equals(p)) {
if (isTabConversionEnabled())
startTabConversion();
else
stopTabConversion();
return;
}
if (PreferenceConstants.EDITOR_SMART_TAB.equals(p)) {
if (getNewPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_TAB)) {
setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$
} else {
removeActionActivationCode("IndentOnTab"); //$NON-NLS-1$
}
}
IContentAssistant c= asv.getContentAssistant();
if (c instanceof ContentAssistant)
ContentAssistPreference.changeConfiguration((ContentAssistant) c, getNewPreferenceStore(), event);
if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
asv.updateIndentationPrefixes();
if (fTabConverter != null)
fTabConverter.setNumberOfSpacesPerTab(getTabSize());
}
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite, org.eclipse.jface.text.source.IVerticalRuler, org.eclipse.jface.text.source.IOverviewRuler, boolean, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) {
return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler, isOverviewRulerVisible, styles);
}
/*
* @see IReconcilingParticipant#reconciled()
*/
public void reconciled() {
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) {
Shell shell= getSite().getShell();
if (shell != null && !shell.isDisposed()) {
shell.getDisplay().asyncExec(new Runnable() {
public void run() {
synchronizeOutlinePageSelection();
}
});
}
}
}
protected void updateStateDependentActions() {
super.updateStateDependentActions();
fGenerateActionGroup.editorStateChanged();
}
/*
* @see AbstractTextEditor#rememberSelection()
*/
protected void rememberSelection() {
fRememberedSelection.remember();
}
/*
* @see AbstractTextEditor#restoreSelection()
*/
protected void restoreSelection() {
fRememberedSelection.restore();
}
/*
* @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput)
*/
protected boolean canHandleMove(IEditorInput originalElement, IEditorInput movedElement) {
String oldExtension= ""; //$NON-NLS-1$
if (originalElement instanceof IFileEditorInput) {
IFile file= ((IFileEditorInput) originalElement).getFile();
if (file != null) {
String ext= file.getFileExtension();
if (ext != null)
oldExtension= ext;
}
}
String newExtension= ""; //$NON-NLS-1$
if (movedElement instanceof IFileEditorInput) {
IFile file= ((IFileEditorInput) movedElement).getFile();
if (file != null)
newExtension= file.getFileExtension();
}
return oldExtension.equals(newExtension);
}
/*
* @see org.eclipse.ui.texteditor.ExtendedTextEditor#isPrefQuickDiffAlwaysOn()
*/
protected boolean isPrefQuickDiffAlwaysOn() {
// reestablishes the behaviour from ExtendedTextEditor which was hacked by JavaEditor
// to disable the change bar for the class file (attached source) java editor.
IPreferenceStore store= getNewPreferenceStore();
return store.getBoolean(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON);
}
}
|
54,470 |
Bug 54470 Eclipse should disallow usage of types defined in default package
| null |
resolved fixed
|
1cfe8de
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-15T10:43:48Z | 2004-03-11T15:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.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.wizards;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
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.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
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.CompilationUnit;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
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.Text;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.dom.TokenScanner;
import org.eclipse.jdt.internal.corext.template.java.JavaContext;
import org.eclipse.jdt.internal.corext.template.java.Templates;
import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
import org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaPackageCompletionProcessor;
import org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.SuperInterfaceSelectionDialog;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
import org.eclipse.jdt.ui.CodeGeneration;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.PreferenceConstants;
/**
* The class <code>NewTypeWizardPage</code> contains controls and validation routines
* for a 'New Type WizardPage'. Implementors decide which components to add and to enable.
* Implementors can also customize the validation code. <code>NewTypeWizardPage</code>
* is intended to serve as base class of all wizards that create types like applets, servlets, classes,
* interfaces, etc.
* <p>
* See <code>NewClassWizardPage</code> or <code>NewInterfaceWizardPage</code> for an
* example usage of <code>NewTypeWizardPage</code>.
* </p>
*
* @see org.eclipse.jdt.ui.wizards.NewClassWizardPage
* @see org.eclipse.jdt.ui.wizards.NewInterfaceWizardPage
*
* @since 2.0
*/
public abstract class NewTypeWizardPage extends NewContainerWizardPage {
/**
* Class used in stub creation routines to add needed imports to a
* compilation unit.
*/
public static class ImportsManager {
private ImportsStructure fImportsStructure;
private HashSet fAddedTypes;
/* package */ ImportsManager(ICompilationUnit createdWorkingCopy) throws CoreException {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store);
int threshold= JavaPreferencesSettings.getImportNumberThreshold(store);
fAddedTypes= new HashSet();
fImportsStructure= new ImportsStructure(createdWorkingCopy, prefOrder, threshold, true);
}
/* package */ ImportsStructure getImportsStructure() {
return fImportsStructure;
}
/**
* Adds a new import declaration that is sorted in the existing imports.
* If an import already exists or the import would conflict with another import
* of an other type with the same simple name the import is not added.
*
* @param qualifiedTypeName The fully qualified name of the type to import
* (dot separated)
* @return Returns the simple type name that can be used in the code or the
* fully qualified type name if an import conflict prevented the import
*/
public String addImport(String qualifiedTypeName) {
fAddedTypes.add(qualifiedTypeName);
return fImportsStructure.addImport(qualifiedTypeName);
}
/* package */ void create(boolean needsSave, SubProgressMonitor monitor) throws CoreException {
fImportsStructure.create(needsSave, monitor);
}
/* package */ void removeImport(String qualifiedName) {
if (fAddedTypes.contains(qualifiedName)) {
fImportsStructure.removeImport(qualifiedName);
}
}
}
/** Public access flag. See The Java Virtual Machine Specification for more details. */
public int F_PUBLIC = Flags.AccPublic;
/** Private access flag. See The Java Virtual Machine Specification for more details. */
public int F_PRIVATE = Flags.AccPrivate;
/** Protected access flag. See The Java Virtual Machine Specification for more details. */
public int F_PROTECTED = Flags.AccProtected;
/** Static access flag. See The Java Virtual Machine Specification for more details. */
public int F_STATIC = Flags.AccStatic;
/** Final access flag. See The Java Virtual Machine Specification for more details. */
public int F_FINAL = Flags.AccFinal;
/** Abstract property flag. See The Java Virtual Machine Specification for more details. */
public int F_ABSTRACT = Flags.AccAbstract;
private final static String PAGE_NAME= "NewTypeWizardPage"; //$NON-NLS-1$
/** Field ID of the package input field */
protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$
/** Field ID of the eclosing type input field */
protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$
/** Field ID of the enclosing type checkbox */
protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$
/** Field ID of the type name input field */
protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$
/** Field ID of the super type input field */
protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$
/** Field ID of the super interfaces input field */
protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$
/** Field ID of the modifier checkboxes */
protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$
/** Field ID of the method stubs checkboxes */
protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$
private class InterfacesListLabelProvider extends LabelProvider {
private Image fInterfaceImage;
public InterfacesListLabelProvider() {
super();
fInterfaceImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_INTERFACE);
}
public Image getImage(Object element) {
return fInterfaceImage;
}
}
private StringButtonStatusDialogField fPackageDialogField;
private SelectionButtonDialogField fEnclosingTypeSelection;
private StringButtonDialogField fEnclosingTypeDialogField;
private boolean fCanModifyPackage;
private boolean fCanModifyEnclosingType;
private IPackageFragment fCurrPackage;
private IType fCurrEnclosingType;
private StringDialogField fTypeNameDialogField;
private StringButtonDialogField fSuperClassDialogField;
private ListDialogField fSuperInterfacesDialogField;
private IType fSuperClass;
private SelectionButtonDialogFieldGroup fAccMdfButtons;
private SelectionButtonDialogFieldGroup fOtherMdfButtons;
private IType fCreatedType;
private JavaPackageCompletionProcessor fCurrPackageCompletionProcessor;
private JavaTypeCompletionProcessor fEnclosingTypeCompletionProcessor;
private JavaTypeCompletionProcessor fSuperClassCompletionProcessor;
protected IStatus fEnclosingTypeStatus;
protected IStatus fPackageStatus;
protected IStatus fTypeNameStatus;
protected IStatus fSuperClassStatus;
protected IStatus fModifierStatus;
protected IStatus fSuperInterfacesStatus;
private boolean fIsClass;
private int fStaticMdfIndex;
private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3;
private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1;
/**
* Creates a new <code>NewTypeWizardPage</code>
*
* @param isClass <code>true</code> if a new class is to be created; otherwise
* an interface is to be created
* @param pageName the wizard page's name
*/
public NewTypeWizardPage(boolean isClass, String pageName) {
super(pageName);
fCreatedType= null;
fIsClass= isClass;
TypeFieldsAdapter adapter= new TypeFieldsAdapter();
fPackageDialogField= new StringButtonStatusDialogField(adapter);
fPackageDialogField.setDialogFieldListener(adapter);
fPackageDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.package.label")); //$NON-NLS-1$
fPackageDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.package.button")); //$NON-NLS-1$
fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$
fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK);
fEnclosingTypeSelection.setDialogFieldListener(adapter);
fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.enclosing.selection.label")); //$NON-NLS-1$
fEnclosingTypeDialogField= new StringButtonDialogField(adapter);
fEnclosingTypeDialogField.setDialogFieldListener(adapter);
fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.enclosing.button")); //$NON-NLS-1$
fTypeNameDialogField= new StringDialogField();
fTypeNameDialogField.setDialogFieldListener(adapter);
fTypeNameDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.typename.label")); //$NON-NLS-1$
fSuperClassDialogField= new StringButtonDialogField(adapter);
fSuperClassDialogField.setDialogFieldListener(adapter);
fSuperClassDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.superclass.label")); //$NON-NLS-1$
fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.superclass.button")); //$NON-NLS-1$
String[] addButtons= new String[] {
/* 0 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.add"), //$NON-NLS-1$
/* 1 */ null,
/* 2 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.remove") //$NON-NLS-1$
};
fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider());
fSuperInterfacesDialogField.setDialogFieldListener(adapter);
String interfaceLabel= fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.interfaces.class.label") : NewWizardMessages.getString("NewTypeWizardPage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$
fSuperInterfacesDialogField.setLabelText(interfaceLabel);
fSuperInterfacesDialogField.setRemoveButtonIndex(2);
String[] buttonNames1= new String[] {
/* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.public"), //$NON-NLS-1$
/* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.default"), //$NON-NLS-1$
/* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.private"), //$NON-NLS-1$
/* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("NewTypeWizardPage.modifiers.protected") //$NON-NLS-1$
};
fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4);
fAccMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.modifiers.acc.label")); //$NON-NLS-1$
fAccMdfButtons.setSelection(0, true);
String[] buttonNames2;
if (fIsClass) {
buttonNames2= new String[] {
/* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.abstract"), //$NON-NLS-1$
/* 1 == FINAL_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.final"), //$NON-NLS-1$
/* 2 */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$
};
fStaticMdfIndex= 2; // index of the static checkbox is 2
} else {
buttonNames2= new String[] {
NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$
};
fStaticMdfIndex= 0; // index of the static checkbox is 0
}
fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4);
fOtherMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false);
fCurrPackageCompletionProcessor= new JavaPackageCompletionProcessor();
fEnclosingTypeCompletionProcessor= new JavaTypeCompletionProcessor(false, false);
fSuperClassCompletionProcessor= new JavaTypeCompletionProcessor(false, false);
fPackageStatus= new StatusInfo();
fEnclosingTypeStatus= new StatusInfo();
fCanModifyPackage= true;
fCanModifyEnclosingType= true;
updateEnableState();
fTypeNameStatus= new StatusInfo();
fSuperClassStatus= new StatusInfo();
fSuperInterfacesStatus= new StatusInfo();
fModifierStatus= new StatusInfo();
}
/**
* Initializes all fields provided by the page with a given selection.
*
* @param elem the selection used to intialize this page or <code>
* null</code> if no selection was available
*/
protected void initTypePage(IJavaElement elem) {
String initSuperclass= "java.lang.Object"; //$NON-NLS-1$
ArrayList initSuperinterfaces= new ArrayList(5);
IPackageFragment pack= null;
IType enclosingType= null;
if (elem != null) {
// evaluate the enclosing type
pack= (IPackageFragment) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
IType typeInCU= (IType) elem.getAncestor(IJavaElement.TYPE);
if (typeInCU != null) {
if (typeInCU.getCompilationUnit() != null) {
enclosingType= typeInCU;
}
} else {
ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
enclosingType= cu.findPrimaryType();
}
}
try {
IType type= null;
if (elem.getElementType() == IJavaElement.TYPE) {
type= (IType)elem;
if (type.exists()) {
String superName= JavaModelUtil.getFullyQualifiedName(type);
if (type.isInterface()) {
initSuperinterfaces.add(superName);
} else {
initSuperclass= superName;
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// ignore this exception now
}
}
String typeName= ""; //$NON-NLS-1$
ITextSelection selection= getCurrentTextSelection();
if (selection != null) {
String text= selection.getText();
if (JavaConventions.validateJavaTypeName(text).isOK()) {
typeName= text;
}
}
setPackageFragment(pack, true);
setEnclosingType(enclosingType, true);
setEnclosingTypeSelection(false, true);
setTypeName(typeName, true);
setSuperClass(initSuperclass, true);
setSuperInterfaces(initSuperinterfaces, true);
}
// -------- UI Creation ---------
/**
* Creates a separator line. Expects a <code>GridLayout</code> with at least 1 column.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSeparator(Composite composite, int nColumns) {
(new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1));
}
/**
* Creates the controls for the package name field. Expects a <code>GridLayout</code> with at
* least 4 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createPackageControls(Composite composite, int nColumns) {
fPackageDialogField.doFillIntoGrid(composite, nColumns);
Text text= fPackageDialogField.getTextControl(null);
LayoutUtil.setWidthHint(text, getMaxFieldWidth());
LayoutUtil.setHorizontalGrabbing(text);
ControlContentAssistHelper.createTextContentAssistant(text, fCurrPackageCompletionProcessor);
}
/**
* Creates the controls for the enclosing type name field. Expects a <code>GridLayout</code> with at
* least 4 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createEnclosingTypeControls(Composite composite, int nColumns) {
// #6891
Composite tabGroup= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
tabGroup.setLayout(layout);
fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1);
Text text= fEnclosingTypeDialogField.getTextControl(composite);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint= getMaxFieldWidth();
gd.horizontalSpan= 2;
text.setLayoutData(gd);
Button button= fEnclosingTypeDialogField.getChangeControl(composite);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.heightHint = SWTUtil.getButtonHeightHint(button);
gd.widthHint = SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
ControlContentAssistHelper.createTextContentAssistant(text, fEnclosingTypeCompletionProcessor);
}
/**
* Creates the controls for the type name field. Expects a <code>GridLayout</code> with at
* least 2 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createTypeNameControls(Composite composite, int nColumns) {
fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1);
DialogField.createEmptySpace(composite);
LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* Creates the controls for the modifiers radio/ceckbox buttons. Expects a
* <code>GridLayout</code> with at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createModifierControls(Composite composite, int nColumns) {
LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1);
Control control= fAccMdfButtons.getSelectionButtonsGroup(composite);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
DialogField.createEmptySpace(composite);
control= fOtherMdfButtons.getSelectionButtonsGroup(composite);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
}
/**
* Creates the controls for the superclass name field. Expects a <code>GridLayout</code>
* with at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSuperClassControls(Composite composite, int nColumns) {
fSuperClassDialogField.doFillIntoGrid(composite, nColumns);
Text text= fSuperClassDialogField.getTextControl(null);
LayoutUtil.setWidthHint(text, getMaxFieldWidth());
ControlContentAssistHelper.createTextContentAssistant(text, fSuperClassCompletionProcessor);
}
/**
* Creates the controls for the superclass name field. Expects a <code>GridLayout</code> with
* at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSuperInterfacesControls(Composite composite, int nColumns) {
fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns);
GridData gd= (GridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData();
if (fIsClass) {
gd.heightHint= convertHeightInCharsToPixels(3);
} else {
gd.heightHint= convertHeightInCharsToPixels(6);
}
gd.grabExcessVerticalSpace= false;
gd.widthHint= getMaxFieldWidth();
}
/**
* Sets the focus on the type name input field.
*/
protected void setFocus() {
fTypeNameDialogField.setFocus();
}
// -------- TypeFieldsAdapter --------
private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter {
// -------- IStringButtonAdapter
public void changeControlPressed(DialogField field) {
typePageChangeControlPressed(field);
}
// -------- IListAdapter
public void customButtonPressed(ListDialogField field, int index) {
typePageCustomButtonPressed(field, index);
}
public void selectionChanged(ListDialogField field) {}
// -------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
typePageDialogFieldChanged(field);
}
public void doubleClicked(ListDialogField field) {
}
}
private void typePageChangeControlPressed(DialogField field) {
if (field == fPackageDialogField) {
IPackageFragment pack= choosePackage();
if (pack != null) {
fPackageDialogField.setText(pack.getElementName());
}
} else if (field == fEnclosingTypeDialogField) {
IType type= chooseEnclosingType();
if (type != null) {
fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
} else if (field == fSuperClassDialogField) {
IType type= chooseSuperType();
if (type != null) {
fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
}
}
private void typePageCustomButtonPressed(DialogField field, int index) {
if (field == fSuperInterfacesDialogField) {
chooseSuperInterfaces();
}
}
/*
* A field on the type has changed. The fields' status and all dependend
* status are updated.
*/
private void typePageDialogFieldChanged(DialogField field) {
String fieldName= null;
if (field == fPackageDialogField) {
fPackageStatus= packageChanged();
updatePackageStatusLabel();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= PACKAGE;
} else if (field == fEnclosingTypeDialogField) {
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSING;
} else if (field == fEnclosingTypeSelection) {
updateEnableState();
boolean isEnclosedType= isEnclosingTypeSelected();
if (!isEnclosedType) {
if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, false);
fAccMdfButtons.setSelection(PROTECTED_INDEX, false);
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
fOtherMdfButtons.setSelection(fStaticMdfIndex, false);
}
}
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType);
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSINGSELECTION;
} else if (field == fTypeNameDialogField) {
fTypeNameStatus= typeNameChanged();
fieldName= TYPENAME;
} else if (field == fSuperClassDialogField) {
fSuperClassStatus= superClassChanged();
fieldName= SUPER;
} else if (field == fSuperInterfacesDialogField) {
fSuperInterfacesStatus= superInterfacesChanged();
fieldName= INTERFACES;
} else if (field == fOtherMdfButtons || field == fAccMdfButtons) {
fModifierStatus= modifiersChanged();
fieldName= MODIFIERS;
} else {
fieldName= METHODS;
}
// tell all others
handleFieldChanged(fieldName);
}
// -------- update message ----------------
/*
* @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String)
*/
protected void handleFieldChanged(String fieldName) {
super.handleFieldChanged(fieldName);
if (fieldName == CONTAINER) {
fPackageStatus= packageChanged();
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fSuperInterfacesStatus= superInterfacesChanged();
}
}
// ---- set / get ----------------
/**
* Returns the text of the package input field.
*
* @return the text of the package input field
*/
public String getPackageText() {
return fPackageDialogField.getText();
}
/**
* Returns the text of the enclosing type input field.
*
* @return the text of the enclosing type input field
*/
public String getEnclosingTypeText() {
return fEnclosingTypeDialogField.getText();
}
/**
* Returns the package fragment corresponding to the current input.
*
* @return a package fragement or <code>null</code> if the input
* could not be resolved.
*/
public IPackageFragment getPackageFragment() {
if (!isEnclosingTypeSelected()) {
return fCurrPackage;
} else {
if (fCurrEnclosingType != null) {
return fCurrEnclosingType.getPackageFragment();
}
}
return null;
}
/**
* Sets the package fragment to the given value. The method updates the model
* and the text of the control.
*
* @param pack the package fragement to be set
* @param canBeModified if <code>true</code> the package fragment is
* editable; otherwise it is read-only.
*/
public void setPackageFragment(IPackageFragment pack, boolean canBeModified) {
fCurrPackage= pack;
fCanModifyPackage= canBeModified;
String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$
fPackageDialogField.setText(str);
updateEnableState();
}
/**
* Returns the enclosing type corresponding to the current input.
*
* @return the enclosing type or <code>null</code> if the enclosing type is
* not selected or the input could not be resolved
*/
public IType getEnclosingType() {
if (isEnclosingTypeSelected()) {
return fCurrEnclosingType;
}
return null;
}
/**
* Sets the enclosing type. The method updates the underlying model
* and the text of the control.
*
* @param type the enclosing type
* @param canBeModified if <code>true</code> the enclosing type field is
* editable; otherwise it is read-only.
*/
public void setEnclosingType(IType type, boolean canBeModified) {
fCurrEnclosingType= type;
fCanModifyEnclosingType= canBeModified;
String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$
fEnclosingTypeDialogField.setText(str);
updateEnableState();
}
/**
* Returns the selection state of the enclosing type checkbox.
*
* @return the seleciton state of the enclosing type checkbox
*/
public boolean isEnclosingTypeSelected() {
return fEnclosingTypeSelection.isSelected();
}
/**
* Sets the enclosing type checkbox's selection state.
*
* @param isSelected the checkbox's selection state
* @param canBeModified if <code>true</code> the enclosing type checkbox is
* modifiable; otherwise it is read-only.
*/
public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) {
fEnclosingTypeSelection.setSelection(isSelected);
fEnclosingTypeSelection.setEnabled(canBeModified);
updateEnableState();
}
/**
* Returns the type name entered into the type input field.
*
* @return the type name
*/
public String getTypeName() {
return fTypeNameDialogField.getText();
}
/**
* Sets the type name input field's text to the given value. Method doesn't update
* the model.
*
* @param name the new type name
* @param canBeModified if <code>true</code> the enclosing type name field is
* editable; otherwise it is read-only.
*/
public void setTypeName(String name, boolean canBeModified) {
fTypeNameDialogField.setText(name);
fTypeNameDialogField.setEnabled(canBeModified);
}
/**
* Returns the selected modifiers.
*
* @return the selected modifiers
* @see Flags
*/
public int getModifiers() {
int mdf= 0;
if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) {
mdf+= F_PUBLIC;
} else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) {
mdf+= F_PRIVATE;
} else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
mdf+= F_PROTECTED;
}
if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) {
mdf+= F_ABSTRACT;
}
if (fOtherMdfButtons.isSelected(FINAL_INDEX)) {
mdf+= F_FINAL;
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
mdf+= F_STATIC;
}
return mdf;
}
/**
* Sets the modifiers.
*
* @param modifiers <code>F_PUBLIC</code>, <code>F_PRIVATE</code>,
* <code>F_PROTECTED</code>, <code>F_ABSTRACT, F_FINAL</code>
* or <code>F_STATIC</code> or, a valid combination.
* @param canBeModified if <code>true</code> the modifier fields are
* editable; otherwise they are read-only
* @see Flags
*/
public void setModifiers(int modifiers, boolean canBeModified) {
if (Flags.isPublic(modifiers)) {
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
} else if (Flags.isPrivate(modifiers)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, true);
} else if (Flags.isProtected(modifiers)) {
fAccMdfButtons.setSelection(PROTECTED_INDEX, true);
} else {
fAccMdfButtons.setSelection(DEFAULT_INDEX, true);
}
if (Flags.isAbstract(modifiers)) {
fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true);
}
if (Flags.isFinal(modifiers)) {
fOtherMdfButtons.setSelection(FINAL_INDEX, true);
}
if (Flags.isStatic(modifiers)) {
fOtherMdfButtons.setSelection(fStaticMdfIndex, true);
}
fAccMdfButtons.setEnabled(canBeModified);
fOtherMdfButtons.setEnabled(canBeModified);
}
/**
* Returns the content of the superclass input field.
*
* @return the superclass name
*/
public String getSuperClass() {
return fSuperClassDialogField.getText();
}
/**
* Sets the super class name.
*
* @param name the new superclass name
* @param canBeModified if <code>true</code> the superclass name field is
* editable; otherwise it is read-only.
*/
public void setSuperClass(String name, boolean canBeModified) {
fSuperClassDialogField.setText(name);
fSuperClassDialogField.setEnabled(canBeModified);
}
/**
* Returns the chosen super interfaces.
*
* @return a list of chosen super interfaces. The list's elements
* are of type <code>String</code>
*/
public List getSuperInterfaces() {
return fSuperInterfacesDialogField.getElements();
}
/**
* Sets the super interfaces.
*
* @param interfacesNames a list of super interface. The method requires that
* the list's elements are of type <code>String</code>
* @param canBeModified if <code>true</code> the super interface field is
* editable; otherwise it is read-only.
*/
public void setSuperInterfaces(List interfacesNames, boolean canBeModified) {
fSuperInterfacesDialogField.setElements(interfacesNames);
fSuperInterfacesDialogField.setEnabled(canBeModified);
}
/**
* Returns the resource handle that corresponds to the compilation unit to was or
* will be created or modified.
* @return A resource or null if the page contains illegal values.
* @since 3.0
*/
public IResource getModifiedResource() {
IType enclosing= getEnclosingType();
if (enclosing != null) {
return enclosing.getResource();
}
IPackageFragment pack= getPackageFragment();
if (pack != null) {
return pack.getCompilationUnit(getTypeName() + ".java").getResource(); //$NON-NLS-1$
}
return null;
}
// ----------- validation ----------
/*
* @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#containerChanged()
*/
protected IStatus containerChanged() {
IStatus status= super.containerChanged();
fCurrPackageCompletionProcessor.setPackageFragmentRoot(getPackageFragmentRoot());
if (getPackageFragmentRoot() != null)
fEnclosingTypeCompletionProcessor.setPackageFragment(getPackageFragmentRoot().getPackageFragment("")); //$NON-NLS-1$
return status;
}
/**
* A hook method that gets called when the package field has changed. The method
* validates the package name and returns the status of the validation. The validation
* also updates the package fragment model.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus packageChanged() {
StatusInfo status= new StatusInfo();
fPackageDialogField.enableButton(getPackageFragmentRoot() != null);
String packName= getPackageText();
if (packName.length() > 0) {
IStatus val= JavaConventions.validatePackageName(packName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$
// continue
}
}
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root != null) {
if (root.getJavaProject().exists() && packName.length() > 0) {
try {
IPath rootPath= root.getPath();
IPath outputPath= root.getJavaProject().getOutputLocation();
if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
// if the bin folder is inside of our root, dont allow to name a package
// like the bin folder
IPath packagePath= rootPath.append(packName.replace('.', '/'));
if (outputPath.isPrefixOf(packagePath)) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// let pass
}
}
fCurrPackage= root.getPackageFragment(packName);
fSuperClassCompletionProcessor.setPackageFragment(fCurrPackage);
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
/*
* Updates the 'default' label next to the package field.
*/
private void updatePackageStatusLabel() {
String packName= getPackageText();
if (packName.length() == 0) {
fPackageDialogField.setStatus(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$
} else {
fPackageDialogField.setStatus(""); //$NON-NLS-1$
}
}
/*
* Updates the enable state of buttons related to the enclosing type selection checkbox.
*/
private void updateEnableState() {
boolean enclosing= isEnclosingTypeSelected();
fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing);
fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing);
}
/**
* Hook method that gets called when the enclosing type name has changed. The method
* validates the enclosing type and returns the status of the validation. It also updates the
* enclosing type model.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus enclosingTypeChanged() {
StatusInfo status= new StatusInfo();
fCurrEnclosingType= null;
IPackageFragmentRoot root= getPackageFragmentRoot();
fEnclosingTypeDialogField.enableButton(root != null);
if (root == null) {
status.setError(""); //$NON-NLS-1$
return status;
}
String enclName= getEnclosingTypeText();
if (enclName.length() == 0) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeEnterName")); //$NON-NLS-1$
return status;
}
try {
IType type= findType(root.getJavaProject(), enclName);
if (type == null) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$
return status;
}
if (type.getCompilationUnit() == null) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotInCU")); //$NON-NLS-1$
return status;
}
if (!JavaModelUtil.isEditable(type.getCompilationUnit())) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotEditable")); //$NON-NLS-1$
return status;
}
fCurrEnclosingType= type;
IPackageFragmentRoot enclosingRoot= JavaModelUtil.getPackageFragmentRoot(type);
if (!enclosingRoot.equals(root)) {
status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.EnclosingNotInSourceFolder")); //$NON-NLS-1$
}
return status;
} catch (JavaModelException e) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$
JavaPlugin.log(e);
return status;
}
}
/**
* Hook method that gets called when the type name has changed. The method validates the
* type name and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus typeNameChanged() {
StatusInfo status= new StatusInfo();
String typeName= getTypeName();
// must not be empty
if (typeName.length() == 0) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnterTypeName")); //$NON-NLS-1$
return status;
}
if (typeName.indexOf('.') != -1) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.QualifiedName")); //$NON-NLS-1$
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(typeName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$
// continue checking
}
// must not exist
if (!isEnclosingTypeSelected()) {
IPackageFragment pack= getPackageFragment();
if (pack != null) {
ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$
if (cu.getResource().exists()) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
} else {
IType type= getEnclosingType();
if (type != null) {
IType member= type.getType(typeName);
if (member.exists()) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
}
return status;
}
/**
* Hook method that gets called when the superclass name has changed. The method
* validates the superclass name and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus superClassChanged() {
StatusInfo status= new StatusInfo();
IPackageFragmentRoot root= getPackageFragmentRoot();
fSuperClassDialogField.enableButton(root != null);
fSuperClass= null;
String sclassName= getSuperClass();
if (sclassName.length() == 0) {
// accept the empty field (stands for java.lang.Object)
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(sclassName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$
return status;
}
if (root != null) {
try {
IType type= resolveSuperTypeName(root.getJavaProject(), sclassName);
if (type == null) {
status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.SuperClassNotExists")); //$NON-NLS-1$
return status;
} else {
if (type.isInterface()) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$
return status;
}
int flags= type.getFlags();
if (Flags.isFinal(flags)) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$
return status;
} else if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$
return status;
}
}
fSuperClass= type;
} catch (JavaModelException e) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$
JavaPlugin.log(e);
}
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException {
if (!jproject.exists()) {
return null;
}
IType type= null;
if (isEnclosingTypeSelected()) {
// search in the context of the enclosing type
IType enclosingType= getEnclosingType();
if (enclosingType != null) {
String[][] res= enclosingType.resolveType(sclassName);
if (res != null && res.length > 0) {
type= jproject.findType(res[0][0], res[0][1]);
}
}
} else {
IPackageFragment currPack= getPackageFragment();
if (type == null && currPack != null) {
String packName= currPack.getElementName();
// search in own package
if (!currPack.isDefaultPackage()) {
type= jproject.findType(packName, sclassName);
}
// search in java.lang
if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$
type= jproject.findType("java.lang", sclassName); //$NON-NLS-1$
}
}
// search fully qualified
if (type == null) {
type= jproject.findType(sclassName);
}
}
return type;
}
private IType findType(IJavaProject project, String typeName) throws JavaModelException {
if (project.exists()) {
return project.findType(typeName);
}
return null;
}
/**
* Hook method that gets called when the list of super interface has changed. The method
* validates the superinterfaces and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus superInterfacesChanged() {
StatusInfo status= new StatusInfo();
IPackageFragmentRoot root= getPackageFragmentRoot();
fSuperInterfacesDialogField.enableButton(0, root != null);
if (root != null) {
List elements= fSuperInterfacesDialogField.getElements();
int nElements= elements.size();
for (int i= 0; i < nElements; i++) {
String intfname= (String)elements.get(i);
try {
IType type= findType(root.getJavaProject(), intfname);
if (type == null) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$
return status;
} else {
if (type.isClass()) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$
return status;
}
if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// let pass, checking is an extra
}
}
}
return status;
}
/**
* Hook method that gets called when the modifiers have changed. The method validates
* the modifiers and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus modifiersChanged() {
StatusInfo status= new StatusInfo();
int modifiers= getModifiers();
if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$
}
return status;
}
// selection dialogs
private IPackageFragment choosePackage() {
IPackageFragmentRoot froot= getPackageFragmentRoot();
IJavaElement[] packages= null;
try {
if (froot != null && froot.exists()) {
packages= froot.getChildren();
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
if (packages == null) {
packages= new IJavaElement[0];
}
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT));
dialog.setIgnoreCase(false);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.description")); //$NON-NLS-1$
dialog.setEmptyListMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.empty")); //$NON-NLS-1$
dialog.setElements(packages);
IPackageFragment pack= getPackageFragment();
if (pack != null) {
dialog.setInitialSelections(new Object[] { pack });
}
if (dialog.open() == Window.OK) {
return (IPackageFragment) dialog.getFirstResult();
}
return null;
}
private IType chooseEnclosingType() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return null;
}
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { root });
TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.TYPE, scope);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$
dialog.setFilter(Signature.getSimpleName(getEnclosingTypeText()));
if (dialog.open() == Window.OK) {
return (IType) dialog.getFirstResult();
}
return null;
}
private IType chooseSuperType() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return null;
}
IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() };
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);
TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.CLASS, scope);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.message")); //$NON-NLS-1$
dialog.setFilter(getSuperClass());
if (dialog.open() == Window.OK) {
return (IType) dialog.getFirstResult();
}
return null;
}
private void chooseSuperInterfaces() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return;
}
IJavaProject project= root.getJavaProject();
SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project);
dialog.setTitle(fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.class.title") : NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.interface.title")); //$NON-NLS-1$ //$NON-NLS-2$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.message")); //$NON-NLS-1$
dialog.open();
return;
}
// ---- creation ----------------
/**
* Creates the new type using the entered field values.
*
* @param monitor a progress monitor to report progress.
*/
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$
ICompilationUnit createdWorkingCopy= null;
try {
IPackageFragmentRoot root= getPackageFragmentRoot();
IPackageFragment pack= getPackageFragment();
if (pack == null) {
pack= root.getPackageFragment(""); //$NON-NLS-1$
}
if (!pack.exists()) {
String packName= pack.getElementName();
pack= root.createPackageFragment(packName, true, null);
}
monitor.worked(1);
String clName= getTypeName();
boolean isInnerClass= isEnclosingTypeSelected();
IType createdType;
ImportsManager imports;
int indent= 0;
String lineDelimiter= null;
if (!isInnerClass) {
lineDelimiter= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
ICompilationUnit parentCU= pack.createCompilationUnit(clName + ".java", "", false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$ //$NON-NLS-2$
// create a working copy with a new owner
createdWorkingCopy= parentCU.getWorkingCopy(null);
// use the compiler template a first time to read the imports
String content= CodeGeneration.getCompilationUnitContent(createdWorkingCopy, null, "", lineDelimiter); //$NON-NLS-1$
if (content != null) {
createdWorkingCopy.getBuffer().setContents(content);
}
imports= new ImportsManager(createdWorkingCopy);
// add an import that will be removed again. Having this import solves 14661
imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), getTypeName()));
String typeContent= constructTypeStub(imports, lineDelimiter);
String cuContent= constructCUContent(parentCU, typeContent, lineDelimiter);
createdWorkingCopy.getBuffer().setContents(cuContent);
createdType= createdWorkingCopy.getType(clName);
} else {
IType enclosingType= getEnclosingType();
// if we are working on a enclosed type that is open in an editor,
// then replace the enclosing type with its working copy
IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType);
if (workingCopy != null) {
enclosingType= workingCopy;
}
ICompilationUnit parentCU= enclosingType.getCompilationUnit();
imports= new ImportsManager(parentCU);
// add imports that will be removed again. Having the imports solves 14661
IType[] topLevelTypes= parentCU.getTypes();
for (int i= 0; i < topLevelTypes.length; i++) {
imports.addImport(topLevelTypes[i].getFullyQualifiedName('.'));
}
lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType);
StringBuffer content= new StringBuffer();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS)) {
String comment= getTypeComment(parentCU, lineDelimiter);
if (comment != null) {
content.append(comment);
content.append(lineDelimiter);
}
}
content.append(constructTypeStub(imports, lineDelimiter));
IJavaElement[] elems= enclosingType.getChildren();
IJavaElement sibling= elems.length > 0 ? elems[0] : null;
createdType= enclosingType.createType(content.toString(), sibling, false, new SubProgressMonitor(monitor, 1));
indent= StubUtility.getIndentUsed(enclosingType) + 1;
}
// add imports for superclass/interfaces, so types can be resolved correctly
ICompilationUnit cu= createdType.getCompilationUnit();
boolean needsSave= !cu.isWorkingCopy();
imports.create(needsSave, new SubProgressMonitor(monitor, 1));
JavaModelUtil.reconcile(cu);
createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1));
// add imports
imports.create(needsSave, new SubProgressMonitor(monitor, 1));
if (removeUnused(cu, imports)) {
imports.create(needsSave, null);
}
JavaModelUtil.reconcile(cu);
ISourceRange range= createdType.getSourceRange();
IBuffer buf= cu.getBuffer();
String originalContent= buf.getText(range.getOffset(), range.getLength());
String formattedContent= CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, indent, null, lineDelimiter, pack.getJavaProject());
buf.replace(range.getOffset(), range.getLength(), formattedContent);
if (!isInnerClass) {
String fileComment= getFileComment(cu);
if (fileComment != null && fileComment.length() > 0) {
buf.replace(0, 0, fileComment + lineDelimiter);
}
cu.commitWorkingCopy(false, new SubProgressMonitor(monitor, 1));
} else {
if (needsSave) {
buf.save(null, false);
}
monitor.worked(1);
}
if (createdWorkingCopy != null) {
fCreatedType= (IType) createdType.getPrimaryElement();
} else {
fCreatedType= createdType;
}
} finally {
if (createdWorkingCopy != null) {
createdWorkingCopy.discardWorkingCopy();
}
monitor.done();
}
}
private boolean removeUnused(ICompilationUnit cu, ImportsManager imports) {
CompilationUnit root= AST.parseCompilationUnit(cu, true, null, null);
IProblem[] problems= root.getProblems();
boolean importRemoved= false;
for (int i= 0; i < problems.length; i++) {
if (problems[i].getID() == IProblem.UnusedImport) {
String imp= problems[i].getArguments()[0];
imports.removeImport(imp);
importRemoved=true;
}
}
return importRemoved;
}
/**
* Uses the New Java file template from the code template page to generate a
* compilation unit with the given type content.
* @param cu The new created compilation unit
* @param typeContent The content of the type, including signature and type
* body.
* @param lineDelimiter The line delimiter to be used.
* @return String Returns the result of evaluating the new file template
* with the given type content.
* @throws CoreException
* @since 2.1
*/
protected String constructCUContent(ICompilationUnit cu, String typeContent, String lineDelimiter) throws CoreException {
String typeComment= getTypeComment(cu, lineDelimiter);
IPackageFragment pack= (IPackageFragment) cu.getParent();
String content= CodeGeneration.getCompilationUnitContent(cu, typeComment, typeContent, lineDelimiter);
if (content != null) {
CompilationUnit unit= AST.parseCompilationUnit(content.toCharArray());
if ((pack.isDefaultPackage() || unit.getPackage() != null) && !unit.types().isEmpty()) {
return content;
}
}
StringBuffer buf= new StringBuffer();
if (!pack.isDefaultPackage()) {
buf.append("package ").append(pack.getElementName()).append(';'); //$NON-NLS-1$
}
buf.append(lineDelimiter).append(lineDelimiter);
if (typeComment != null) {
buf.append(typeComment).append(lineDelimiter);
}
buf.append(typeContent);
return buf.toString();
}
/**
* Returns the created type. The method only returns a valid type
* after <code>createType</code> has been called.
*
* @return the created type
* @see #createType(IProgressMonitor)
*/
public IType getCreatedType() {
return fCreatedType;
}
// ---- construct cu body----------------
private void writeSuperClass(StringBuffer buf, ImportsManager imports) {
String typename= getSuperClass();
if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$
buf.append(" extends "); //$NON-NLS-1$
String qualifiedName= fSuperClass != null ? JavaModelUtil.getFullyQualifiedName(fSuperClass) : typename;
buf.append(imports.addImport(qualifiedName));
}
}
private void writeSuperInterfaces(StringBuffer buf, ImportsManager imports) {
List interfaces= getSuperInterfaces();
int last= interfaces.size() - 1;
if (last >= 0) {
if (fIsClass) {
buf.append(" implements "); //$NON-NLS-1$
} else {
buf.append(" extends "); //$NON-NLS-1$
}
for (int i= 0; i <= last; i++) {
String typename= (String) interfaces.get(i);
buf.append(imports.addImport(typename));
if (i < last) {
buf.append(',');
}
}
}
}
/*
* Called from createType to construct the source for this type
*/
private String constructTypeStub(ImportsManager imports, String lineDelimiter) {
StringBuffer buf= new StringBuffer();
int modifiers= getModifiers();
buf.append(Flags.toString(modifiers));
if (modifiers != 0) {
buf.append(' ');
}
buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$
buf.append(getTypeName());
writeSuperClass(buf, imports);
writeSuperInterfaces(buf, imports);
buf.append('{');
buf.append(lineDelimiter);
buf.append(lineDelimiter);
buf.append('}');
buf.append(lineDelimiter);
return buf.toString();
}
/**
* Hook method that gets called from <code>createType</code> to support adding of
* unanticipated methods, fields, and inner types to the created type.
* <p>
* Implementers can use any methods defined on <code>IType</code> to manipulate the
* new type.
* </p>
* <p>
* The source code of the new type will be formtted using the platform's formatter. Needed
* imports are added by the wizard at the end of the type creation process using the given
* import manager.
* </p>
*
* @param newType the new type created via <code>createType</code>
* @param imports an import manager which can be used to add new imports
* @param monitor a progress monitor to report progress. Must not be <code>null</code>
*
* @see #createType(IProgressMonitor)
*/
protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
// default implementation does nothing
// example would be
// String mainMathod= "public void foo(Vector vec) {}"
// createdType.createMethod(main, null, false, null);
// imports.addImport("java.lang.Vector");
}
/**
* @deprecated Instead of file templates, the new type code template
* specifies the stub for a compilation unit.
*/
protected String getFileComment(ICompilationUnit parentCU) {
return null;
}
private boolean isValidComment(String template) {
IScanner scanner= ToolFactory.createScanner(true, false, false, false);
scanner.setSource(template.toCharArray());
try {
int next= scanner.getNextToken();
while (TokenScanner.isComment(next)) {
next= scanner.getNextToken();
}
return next == ITerminalSymbols.TokenNameEOF;
} catch (InvalidInputException e) {
}
return false;
}
/**
* Hook method that gets called from <code>createType</code> to retrieve
* a type comment. This default implementation returns the content of the
* 'type comment' template.
*
* @return the type comment or <code>null</code> if a type comment
* is not desired
*/
protected String getTypeComment(ICompilationUnit parentCU, String lineDelimiter) {
try {
StringBuffer typeName= new StringBuffer();
if (isEnclosingTypeSelected()) {
typeName.append(JavaModelUtil.getTypeQualifiedName(getEnclosingType())).append('.');
}
typeName.append(getTypeName());
String comment= CodeGeneration.getTypeComment(parentCU, typeName.toString(), lineDelimiter);
if (comment != null && isValidComment(comment)) {
return comment;
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
return null;
}
/**
* @deprecated Use getTypeComment(ICompilationUnit, String)
*/
protected String getTypeComment(ICompilationUnit parentCU) {
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS)) {
return getTypeComment(parentCU, String.valueOf('\n'));
}
return null;
}
/**
* @deprecated Use getTemplate(String,ICompilationUnit,int)
*/
protected String getTemplate(String name, ICompilationUnit parentCU) {
return getTemplate(name, parentCU, 0);
}
/**
* Returns the string resulting from evaluation the given template in
* the context of the given compilation unit. This accesses the normal
* template page, not the code templates. To use code templates use
* <code>constructCUContent</code> to construct a compilation unit stub or
* getTypeComment for the comment of the type.
*
* @param name the template to be evaluated
* @param parentCU the templates evaluation context
* @param pos a source offset into the parent compilation unit. The
* template is evalutated at the given source offset
*/
protected String getTemplate(String name, ICompilationUnit parentCU, int pos) {
try {
Template[] templates= Templates.getInstance().getTemplates(name);
if (templates.length > 0) {
return JavaContext.evaluateTemplate(templates[0], parentCU, pos);
}
} catch (CoreException e) {
JavaPlugin.log(e);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return null;
}
/**
* Creates the bodies of all unimplemented methods and constructors and adds them to the type.
* Method is typically called by implementers of <code>NewTypeWizardPage</code> to add
* needed method and constructors.
*
* @param type the type for which the new methods and constructor are to be created
* @param doConstructors if <code>true</code> unimplemented constructors are created
* @param doUnimplementedMethods if <code>true</code> unimplemented methods are created
* @param imports an import manager to add all neded import statements
* @param monitor a progress monitor to report progress
*/
protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
ArrayList newMethods= new ArrayList();
ITypeHierarchy hierarchy= null;
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (doConstructors) {
hierarchy= type.newSupertypeHierarchy(monitor);
IType superclass= hierarchy.getSuperclass(type);
if (superclass != null) {
String[] constructors= StubUtility.evalConstructors(type, superclass, settings, imports.getImportsStructure());
if (constructors != null) {
for (int i= 0; i < constructors.length; i++) {
newMethods.add(constructors[i]);
}
}
}
}
if (doUnimplementedMethods) {
if (hierarchy == null) {
hierarchy= type.newSupertypeHierarchy(monitor);
}
String[] unimplemented= StubUtility.evalUnimplementedMethods(type, hierarchy, false, settings, imports.getImportsStructure());
if (unimplemented != null) {
for (int i= 0; i < unimplemented.length; i++) {
newMethods.add(unimplemented[i]);
}
}
}
IMethod[] createdMethods= new IMethod[newMethods.size()];
for (int i= 0; i < newMethods.size(); i++) {
String content= (String) newMethods.get(i) + '\n'; // content will be formatted, ok to use \n
createdMethods[i]= type.createMethod(content, null, false, null);
}
return createdMethods;
}
// ---- creation ----------------
/**
* Returns the runnable that creates the type using the current settings.
* The returned runnable must be executed in the UI thread.
*
* @return the runnable to create the new type
*/
public IRunnableWithProgress getRunnable() {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
createType(monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
}
}
|
54,595 |
Bug 54595 Load User Libraries dialog has layout problems
|
Reached through Pref Page Java/Build Path/User Libraries/Load...
|
verified fixed
|
58110bf
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-15T11:02:17Z | 2004-03-12T11:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/UserLibraryPreferencePage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.preferences;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.eclipse.core.resources.IResource;
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.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.Dialog;
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.preference.PreferencePage;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.corext.userlibrary.UserLibrary;
import org.eclipse.jdt.internal.corext.userlibrary.UserLibraryManager;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.IUIConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusDialog;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathSupport;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.CPListElement;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.CPListElementAttribute;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.CPListElementSorter;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.CPListLabelProvider;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.CPUserLibraryElement;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.JavadocPropertyDialog;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.SourceAttachmentDialog;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.CheckedListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField;
public class UserLibraryPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
public static final String ID= "org.eclipse.jdt.ui.preferences.UserLibraryPreferencePage"; //$NON-NLS-1$
public static class LibraryNameDialog extends StatusDialog implements IDialogFieldListener {
private StringDialogField fNameField;
private SelectionButtonDialogField fIsSystemField;
private CPUserLibraryElement fElementToEdit;
private List fExistingLibraries;
public LibraryNameDialog(Shell parent, CPUserLibraryElement elementToEdit, List existingLibraries) {
super(parent);
if (elementToEdit == null) {
setTitle(PreferencesMessages.getString("UserLibraryPreferencePage.LibraryNameDialog.new.title")); //$NON-NLS-1$
} else {
setTitle(PreferencesMessages.getString("UserLibraryPreferencePage.LibraryNameDialog.edit.title")); //$NON-NLS-1$
}
fElementToEdit= elementToEdit;
fExistingLibraries= existingLibraries;
fNameField= new StringDialogField();
fNameField.setDialogFieldListener(this);
fNameField.setLabelText(PreferencesMessages.getString("UserLibraryPreferencePage.LibraryNameDialog.name.label")); //$NON-NLS-1$
fIsSystemField= new SelectionButtonDialogField(SWT.CHECK);
fIsSystemField.setLabelText(PreferencesMessages.getString("UserLibraryPreferencePage.LibraryNameDialog.issystem.label")); //$NON-NLS-1$
if (elementToEdit != null) {
fNameField.setText(elementToEdit.getName());
fIsSystemField.setSelection(elementToEdit.isSystemLibrary());
} else {
fNameField.setText(""); //$NON-NLS-1$
fIsSystemField.setSelection(false);
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
protected Control createDialogArea(Composite parent) {
Composite composite= (Composite) super.createDialogArea(parent);
LayoutUtil.doDefaultLayout(composite, new DialogField[] { fNameField, fIsSystemField }, true, SWT.DEFAULT, SWT.DEFAULT);
return composite;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField)
*/
public void dialogFieldChanged(DialogField field) {
if (field == fNameField) {
updateStatus(validateSettings());
}
}
private IStatus validateSettings() {
String name= fNameField.getText();
if (name.length() == 0) {
return new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("UserLibraryPreferencePage.LibraryNameDialog.name.error.entername")); //$NON-NLS-1$
}
for (int i= 0; i < fExistingLibraries.size(); i++) {
CPUserLibraryElement curr= (CPUserLibraryElement) fExistingLibraries.get(i);
if (curr != fElementToEdit && name.equals(curr.getName())) {
return new StatusInfo(IStatus.ERROR, PreferencesMessages.getFormattedString("UserLibraryPreferencePage.LibraryNameDialog.name.error.exists", name)); //$NON-NLS-1$
}
}
IStatus status= ResourcesPlugin.getWorkspace().validateName(name, IResource.FILE);
if (status.matches(IStatus.ERROR)) {
return new StatusInfo(IStatus.ERROR, "Name contains invalid characters."); //$NON-NLS-1$
}
return Status.OK_STATUS;
}
public CPUserLibraryElement getNewLibrary() {
CPListElement[] entries= null;
if (fElementToEdit != null) {
entries= fElementToEdit.getChildren();
}
return new CPUserLibraryElement(fNameField.getText(), fIsSystemField.isSelected(), entries);
}
}
public static class LoadSaveDialog extends StatusDialog implements IStringButtonAdapter, IDialogFieldListener {
private static final String CURRENT_VERSION= "1"; //$NON-NLS-1$
private static final String TAG_ROOT= "eclipse-userlibraries"; //$NON-NLS-1$
private static final String TAG_VERSION= "version"; //$NON-NLS-1$
private static final String TAG_LIBRARY= "library"; //$NON-NLS-1$
private static final String TAG_SOURCEATTACHMENT= "source"; //$NON-NLS-1$
private static final String TAG_ARCHIVE_PATH= "path"; //$NON-NLS-1$
private static final String TAG_ARCHIVE= "archive"; //$NON-NLS-1$
private static final String TAG_SYSTEMLIBRARY= "systemlibrary"; //$NON-NLS-1$
private static final String TAG_NAME= "name"; //$NON-NLS-1$
private static final String TAG_JAVADOC= "javadoc"; //$NON-NLS-1$
private static final String PREF_LASTPATH= JavaUI.ID_PLUGIN + ".lastuserlibrary"; //$NON-NLS-1$
private List fExistingLibraries;
private IDialogSettings fSettings;
private File fLastFile;
private StringButtonDialogField fLocationField;
private CheckedListDialogField fExportImportList;
private Point fInitialSize;
public LoadSaveDialog(Shell shell, List existingLibraries, IDialogSettings dialogSettings) {
super(shell);
setShellStyle(getShellStyle() | SWT.MAX | SWT.RESIZE);
PixelConverter converter= new PixelConverter(shell);
fInitialSize= new Point(converter.convertWidthInCharsToPixels(80), converter.convertHeightInCharsToPixels(34));
fExistingLibraries= existingLibraries;
fSettings= dialogSettings;
fLastFile= null;
if (isSave()) {
setTitle(PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.save.title")); //$NON-NLS-1$
} else {
setTitle(PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.load.title")); //$NON-NLS-1$
}
fLocationField= new StringButtonDialogField(this);
fLocationField.setLabelText(PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.location.label")); //$NON-NLS-1$
fLocationField.setButtonLabel(PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.location.button")); //$NON-NLS-1$
fLocationField.setDialogFieldListener(this);
String[] buttonNames= new String[] {
PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.list.selectall.button"), //$NON-NLS-1$
PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.list.deselectall.button") //$NON-NLS-1$
};
fExportImportList= new CheckedListDialogField(null, buttonNames, new CPListLabelProvider());
fExportImportList.setCheckAllButtonIndex(0);
fExportImportList.setUncheckAllButtonIndex(1);
fExportImportList.setViewerSorter(new CPListElementSorter());
if (isSave()) {
fExportImportList.setLabelText(PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.list.save.label")); //$NON-NLS-1$
fExportImportList.setElements(fExistingLibraries);
fExportImportList.checkAll(true);
} else {
fExportImportList.setLabelText(PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.list.load.label")); //$NON-NLS-1$
}
String lastPath= fSettings.get(PREF_LASTPATH);
if (lastPath != null) {
fLocationField.setText(lastPath);
} else {
fLocationField.setText(""); //$NON-NLS-1$
}
}
protected Point getInitialSize() {
return fInitialSize;
}
private boolean isSave() {
return fExistingLibraries != null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
protected Control createDialogArea(Composite parent) {
Composite composite= (Composite) super.createDialogArea(parent);
DialogField[] fields;
if (isSave()) {
fields= new DialogField[] { fExportImportList, fLocationField };
} else {
fields= new DialogField[] { fLocationField, fExportImportList };
}
LayoutUtil.doDefaultLayout(composite, fields, true, SWT.DEFAULT, SWT.DEFAULT);
LayoutUtil.setHorizontalGrabbing(fLocationField.getTextControl(null));
fLocationField.postSetFocusOnDialogField(parent.getDisplay());
return composite;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter#changeControlPressed(org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField)
*/
public void changeControlPressed(DialogField field) {
String label= isSave() ? PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.filedialog.save.title") : PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.filedialog.load.title"); //$NON-NLS-1$ //$NON-NLS-2$
FileDialog dialog= new FileDialog(getShell(), isSave() ? SWT.SAVE : SWT.OPEN);
dialog.setText(label);
dialog.setFilterExtensions(new String[] {"*.userlibraries", "*.*"}); //$NON-NLS-1$ //$NON-NLS-2$
String lastPath= fLocationField.getText();
if (lastPath.length() == 0 || !new File(lastPath).exists()) {
lastPath= fSettings.get(PREF_LASTPATH);
}
if (lastPath != null) {
dialog.setFileName(lastPath);
}
String fileName= dialog.open();
if (fileName != null) {
fSettings.put(PREF_LASTPATH, fileName);
fLocationField.setText(fileName);
}
}
private IStatus updateShownLibraries(IStatus status) {
if (!status.isOK()) {
fExportImportList.removeAllElements();
fExportImportList.setEnabled(false);
fLastFile= null;
} else {
File file= new File(fLocationField.getText());
if (!file.equals(fLastFile)) {
fLastFile= file;
try {
List elements= loadLibraries(file);
fExportImportList.setElements(elements);
fExportImportList.checkAll(true);
fExportImportList.setEnabled(true);
if (elements.isEmpty()) {
return new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.error.empty")); //$NON-NLS-1$
}
} catch (IOException e) {
fExportImportList.removeAllElements();
fExportImportList.setEnabled(false);
return new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.error.invalidfile")); //$NON-NLS-1$
}
}
}
return status;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField)
*/
public void dialogFieldChanged(DialogField field) {
if (field == fLocationField) {
IStatus status= validateSettings();
if (!isSave()) {
status= updateShownLibraries(status);
}
updateStatus(status);
} else if (field == fExportImportList) {
updateStatus(validateSettings());
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
protected void okPressed() {
if (isSave()) {
final File file= new File(fLocationField.getText());
if (file.exists()) {
String title= PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.overwrite.title"); //$NON-NLS-1$
String message= PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.overwrite.message"); //$NON-NLS-1$
if (!MessageDialog.openQuestion(getShell(), title, message)) {
return;
}
}
final List elements= fExportImportList.getCheckedElements();
BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
try {
context.run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
saveLibraries(elements, file, monitor);
} catch (IOException e) {
throw new InvocationTargetException(e);
}
}
});
fSettings.put(PREF_LASTPATH, file.getPath());
} catch (InvocationTargetException e) {
String errorTitle= PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.save.errordialog.title"); //$NON-NLS-1$
String errorMessage= PreferencesMessages.getFormattedString("UserLibraryPreferencePage.LoadSaveDialog.save.errordialog.message", e.getMessage()); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), errorTitle, errorMessage);
} catch (InterruptedException e) {
// cancelled
return;
}
}
super.okPressed();
}
private IStatus validateSettings() {
String name= fLocationField.getText();
fLastFile= null;
if (isSave()) {
if (name.length() == 0) {
return new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.location.error.save.enterlocation")); //$NON-NLS-1$
}
File file= new File(name);
if (file.isDirectory()) {
return new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.location.error.save.invalid")); //$NON-NLS-1$
}
if (fExportImportList.getCheckedSize() == 0) {
return new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.list.error.save.nothingselected")); //$NON-NLS-1$
}
fLastFile= file;
} else {
if (name.length() == 0) {
return new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.location.error.load.enterlocation")); //$NON-NLS-1$
}
if (!new File(name).isFile()) {
return new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.location.error.load.invalid")); //$NON-NLS-1$
}
if (fExportImportList.getSize() > 0 && fExportImportList.getCheckedSize() == 0) {
return new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.list.error.load.nothingselected")); //$NON-NLS-1$
}
}
return new StatusInfo();
}
protected static void saveLibraries(List libraries, File file, IProgressMonitor monitor) throws IOException {
FileOutputStream outputStream= new FileOutputStream(file);
try {
DocumentBuilder docBuilder= null;
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
factory.setValidating(false);
docBuilder= factory.newDocumentBuilder();
Document document= docBuilder.newDocument();
// Create the document
Element rootElement= document.createElement(TAG_ROOT);
document.appendChild(rootElement);
rootElement.setAttribute(TAG_VERSION, CURRENT_VERSION);
for (int i= 0; i < libraries.size(); i++) {
Element libraryElement= document.createElement(TAG_LIBRARY);
rootElement.appendChild(libraryElement);
CPUserLibraryElement curr= (CPUserLibraryElement) libraries.get(i);
libraryElement.setAttribute(TAG_NAME, curr.getName());
libraryElement.setAttribute(TAG_SYSTEMLIBRARY, String.valueOf(curr.isSystemLibrary()));
CPListElement[] children= curr.getChildren();
for (int k= 0; k < children.length; k++) {
CPListElement child= children[k];
Element childElement= document.createElement(TAG_ARCHIVE);
libraryElement.appendChild(childElement);
childElement.setAttribute(TAG_ARCHIVE_PATH, child.getPath().toOSString());
IPath sourceAttachment= (IPath) child.getAttribute(CPListElement.SOURCEATTACHMENT);
if (sourceAttachment != null) {
childElement.setAttribute(TAG_SOURCEATTACHMENT, sourceAttachment.toOSString());
}
URL javadocLocation= (URL) child.getAttribute(CPListElement.JAVADOC);
if (javadocLocation != null) {
childElement.setAttribute(TAG_JAVADOC, javadocLocation.toExternalForm());
}
}
}
// Write the document to the stream
Transformer transformer=TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); //$NON-NLS-1$ //$NON-NLS-2$
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(outputStream);
transformer.transform(source, result);
} catch (ParserConfigurationException e) {
throw new IOException(e.getMessage());
} catch (TransformerException e) {
throw new IOException(e.getMessage());
} finally {
try {
outputStream.close();
} catch (IOException e) {
// ignore
}
if (monitor != null) {
monitor.done();
}
}
}
private static List loadLibraries(File file) throws IOException {
Reader reader= new FileReader(file);
Element cpElement;
try {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
cpElement = parser.parse(new InputSource(reader)).getDocumentElement();
} catch (SAXException e) {
throw new IOException(PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.load.badformat")); //$NON-NLS-1$
} catch (ParserConfigurationException e) {
throw new IOException(PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.load.badformat")); //$NON-NLS-1$
} finally {
reader.close();
}
if (!cpElement.getNodeName().equalsIgnoreCase(TAG_ROOT)) {
throw new IOException(PreferencesMessages.getString("UserLibraryPreferencePage.LoadSaveDialog.load.badformat")); //$NON-NLS-1$
}
NodeList libList= cpElement.getElementsByTagName(TAG_LIBRARY);
int length = libList.getLength();
ArrayList result= new ArrayList(length);
for (int i= 0; i < length; i++) {
Node lib= libList.item(i);
if (!(lib instanceof Element)) {
continue;
}
Element libElement= (Element) lib;
String name= libElement.getAttribute(TAG_NAME);
boolean isSystem= Boolean.valueOf(libElement.getAttribute(TAG_SYSTEMLIBRARY)).booleanValue();
CPUserLibraryElement newLibrary= new CPUserLibraryElement(name, isSystem, null);
result.add(newLibrary);
NodeList archiveList= libElement.getElementsByTagName(TAG_ARCHIVE);
for (int k= 0; k < length; k++) {
Node archiveNode= archiveList.item(k);
if (!(archiveNode instanceof Element)) {
continue;
}
Element archiveElement= (Element) archiveNode;
String path= archiveElement.getAttribute(TAG_ARCHIVE_PATH);
CPListElement newArchive= new CPListElement(null, IClasspathEntry.CPE_LIBRARY, new Path(path), null);
newLibrary.add(newArchive);
if (archiveElement.hasAttribute(TAG_SOURCEATTACHMENT)) {
IPath sourceAttach= new Path(archiveElement.getAttribute(TAG_SOURCEATTACHMENT));
newArchive.setAttribute(CPListElement.SOURCEATTACHMENT, sourceAttach);
}
if (archiveElement.hasAttribute(TAG_JAVADOC)) {
try {
URL javadoc= new URL(archiveElement.getAttribute(TAG_JAVADOC));
newArchive.setAttribute(CPListElement.JAVADOC, javadoc);
} catch (MalformedURLException e) {
// ignore
}
}
}
}
return result;
}
public List getLoadedLibraries() {
return fExportImportList.getCheckedElements();
}
}
private IDialogSettings fDialogSettings;
private TreeListDialogField fLibraryList;
private static final int IDX_NEW= 0;
private static final int IDX_EDIT= 1;
private static final int IDX_ADD= 2;
private static final int IDX_REMOVE= 3;
private static final int IDX_LOAD= 5;
private static final int IDX_SAVE= 6;
/**
* Constructor for ClasspathVariablesPreferencePage
*/
public UserLibraryPreferencePage() {
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
// title only used when page is shown programatically
setTitle(PreferencesMessages.getString("UserLibraryPreferencePage.title")); //$NON-NLS-1$
setDescription(PreferencesMessages.getString("UserLibraryPreferencePage.description")); //$NON-NLS-1$
noDefaultAndApplyButton();
fDialogSettings= JavaPlugin.getDefault().getDialogSettings();
UserLibraryAdapter adapter= new UserLibraryAdapter();
String[] buttonLabels= new String[] {
PreferencesMessages.getString("UserLibraryPreferencePage.libraries.new.button"), //$NON-NLS-1$
PreferencesMessages.getString("UserLibraryPreferencePage.libraries.edit.button"), //$NON-NLS-1$
PreferencesMessages.getString("UserLibraryPreferencePage.libraries.addjar.button"), //$NON-NLS-1$
PreferencesMessages.getString("UserLibraryPreferencePage.libraries.remove.button"), //$NON-NLS-1$
null,
PreferencesMessages.getString("UserLibraryPreferencePage.libraries.load.button"), //$NON-NLS-1$
PreferencesMessages.getString("UserLibraryPreferencePage.libraries.save.button") //$NON-NLS-1$
};
fLibraryList= new TreeListDialogField(adapter, buttonLabels, new CPListLabelProvider());
fLibraryList.setLabelText(PreferencesMessages.getString("UserLibraryPreferencePage.libraries.label")); //$NON-NLS-1$
String[] names= UserLibraryManager.getUserLibraryNames();
ArrayList elements= new ArrayList();
for (int i= 0; i < names.length; i++) {
elements.add(new CPUserLibraryElement(names[i]));
}
fLibraryList.setElements(elements);
fLibraryList.setViewerSorter(new CPListElementSorter());
doSelectionChanged(fLibraryList); //update button enable state
}
/**
* Constructor to be used when programatically showing the page
* @param selectedLibrary The entry to be selected by default.
*/
public UserLibraryPreferencePage(String selectedLibrary, boolean createIfNotFound) {
this();
if (selectedLibrary != null) {
int nElements= fLibraryList.getSize();
for (int i= 0; i < nElements; i++) {
CPUserLibraryElement curr= (CPUserLibraryElement) fLibraryList.getElement(i);
if (curr.getName().equals(selectedLibrary)) {
fLibraryList.selectElements(new StructuredSelection(curr));
fLibraryList.expandElement(curr, AbstractTreeViewer.ALL_LEVELS);
break;
}
}
if (createIfNotFound) {
CPUserLibraryElement elem= new CPUserLibraryElement(selectedLibrary);
fLibraryList.addElement(elem);
fLibraryList.selectElements(new StructuredSelection(elem));
}
}
}
/*
* (non-Javadoc)
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
*/
public void createControl(Composite parent) {
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.CP_USERLIBRARIES_PREFERENCE_PAGE);
}
/*
* @see PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
*/
protected Control createContents(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
LayoutUtil.doDefaultLayout(composite, new DialogField[] { fLibraryList }, true);
LayoutUtil.setHorizontalGrabbing(fLibraryList.getTreeControl(null));
Dialog.applyDialogFont(composite);
return composite;
}
/*
* @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
*/
public void init(IWorkbench workbench) {
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
super.performDefaults();
}
/*
* @see PreferencePage#performOk()
*/
public boolean performOk() {
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
updateUserLibararies(monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
});
} catch (InterruptedException e) {
// cancelled by user
} catch (InvocationTargetException e) {
String title= PreferencesMessages.getString("UserLibraryPreferencePage.config.error.title"); //$NON-NLS-1$
String message= PreferencesMessages.getString("UserLibraryPreferencePage.config.error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
}
return true;
}
private void updateUserLibararies(IProgressMonitor monitor) throws JavaModelException {
List list= fLibraryList.getElements();
HashSet oldNames= new HashSet(Arrays.asList(UserLibraryManager.getUserLibraryNames()));
int nExisting= list.size();
for (int i= 0; i < nExisting; i++) {
CPUserLibraryElement element= (CPUserLibraryElement) list.get(i);
oldNames.remove(element.getName());
}
ArrayList paths= new ArrayList();
ArrayList urls= new ArrayList();
int len= nExisting + oldNames.size();
String[] newNames= new String[len];
UserLibrary[] newLibs= new UserLibrary[len];
for (int i= 0; i < nExisting; i++) {
CPUserLibraryElement element= (CPUserLibraryElement) list.get(i);
newNames[i]= element.getName();
newLibs[i]= element.getUserLibrary();
element.collectJavaDocLocations(paths, urls);
}
Iterator iter= oldNames.iterator();
for (int i= nExisting; i < len; i++) {
newNames[i]= (String) iter.next();
newLibs[i]= null;
}
// save javadoc locations
JavaUI.setLibraryJavadocLocations((IPath[]) paths.toArray(new IPath[paths.size()]), (URL[]) urls.toArray(new URL[paths.size()]));
// save libararies
UserLibraryManager.setUserLibraries(newNames, newLibs, monitor);
}
private CPUserLibraryElement getSingleSelectedLibrary(List selected) {
if (selected.size() == 1 && selected.get(0) instanceof CPUserLibraryElement) {
return (CPUserLibraryElement) selected.get(0);
}
return null;
}
private void editAttributeEntry(CPListElementAttribute elem) {
String key= elem.getKey();
if (key.equals(CPListElement.SOURCEATTACHMENT)) {
CPListElement selElement= elem.getParent();
IPath containerPath= null;
SourceAttachmentDialog dialog= new SourceAttachmentDialog(getShell(), selElement.getClasspathEntry(), containerPath, null, false);
if (dialog.open() == Window.OK) {
selElement.setAttribute(CPListElement.SOURCEATTACHMENT, dialog.getSourceAttachmentPath());
fLibraryList.refresh();
}
} else if (key.equals(CPListElement.JAVADOC)) {
CPListElement selElement= elem.getParent();
JavadocPropertyDialog dialog= new JavadocPropertyDialog(getShell(), selElement);
if (dialog.open() == Window.OK) {
selElement.setAttribute(CPListElement.JAVADOC, dialog.getJavaDocLocation());
fLibraryList.refresh();
}
}
}
protected void doSelectionChanged(TreeListDialogField field) {
List list= field.getSelectedElements();
field.enableButton(IDX_REMOVE, canRemove(list));
field.enableButton(IDX_EDIT, canEdit(list));
field.enableButton(IDX_ADD, canAdd(list));
field.enableButton(IDX_SAVE, field.getSize() > 0);
}
protected void doCustomButtonPressed(TreeListDialogField field, int index) {
if (index == IDX_NEW) {
editUserLibraryElement(null);
} else if (index == IDX_ADD) {
doAdd(field.getSelectedElements());
} else if (index == IDX_REMOVE) {
doRemove(field.getSelectedElements());
} else if (index == IDX_EDIT) {
doEdit(field.getSelectedElements());
} else if (index == IDX_SAVE) {
doSave();
} else if (index == IDX_LOAD) {
doLoad();
}
}
protected void doDoubleClicked(TreeListDialogField field) {
List selected= field.getSelectedElements();
if (canEdit(selected)) {
doEdit(field.getSelectedElements());
}
}
protected void doKeyPressed(TreeListDialogField field, KeyEvent event) {
if (event.character == SWT.DEL && event.stateMask == 0) {
List selection= field.getSelectedElements();
if (canRemove(selection)) {
doRemove(selection);
}
}
}
private void doEdit(List selected) {
if (selected.size() == 1) {
Object curr= selected.get(0);
if (curr instanceof CPListElementAttribute) {
editAttributeEntry((CPListElementAttribute) curr);
} else if (curr instanceof CPUserLibraryElement) {
editUserLibraryElement((CPUserLibraryElement) curr);
} else if (curr instanceof CPListElement) {
CPListElement elem= (CPListElement) curr;
openExtJarFileDialog(elem, elem.getParentContainer());
}
}
}
private void editUserLibraryElement(CPUserLibraryElement element) {
LibraryNameDialog dialog= new LibraryNameDialog(getShell(), element, fLibraryList.getElements());
if (dialog.open() == Window.OK) {
CPUserLibraryElement newLibrary= dialog.getNewLibrary();
if (element != null) {
fLibraryList.replaceElement(element, newLibrary);
} else {
fLibraryList.addElement(newLibrary);
}
fLibraryList.expandElement(newLibrary, AbstractTreeViewer.ALL_LEVELS);
fLibraryList.selectElements(new StructuredSelection(newLibrary));
}
}
private void editArchiveElement(CPListElement existingElement, CPUserLibraryElement parent) {
CPListElement[] elements= openExtJarFileDialog(existingElement, parent);
if (elements != null) {
for (int i= 0; i < elements.length; i++) {
if (existingElement != null) {
parent.replace(existingElement, elements[i]);
} else {
parent.add(elements[i]);
}
}
fLibraryList.refresh(parent);
fLibraryList.expandElement(parent, AbstractTreeViewer.ALL_LEVELS);
fLibraryList.selectElements(new StructuredSelection(parent));
}
}
private void doRemove(List selected) {
Object selectionAfter= null;
for (int i= 0; i < selected.size(); i++) {
Object curr= selected.get(i);
if (curr instanceof CPUserLibraryElement) {
fLibraryList.removeElement(curr);
} else if (curr instanceof CPListElement) {
Object parent= ((CPListElement) curr).getParentContainer();
if (parent instanceof CPUserLibraryElement) {
CPUserLibraryElement elem= (CPUserLibraryElement) parent;
elem.remove((CPListElement) curr);
fLibraryList.refresh(elem);
selectionAfter= parent;
}
} else if (curr instanceof CPListElementAttribute) {
CPListElementAttribute attrib= (CPListElementAttribute) curr;
attrib.getParent().setAttribute(attrib.getKey(), null);
fLibraryList.refresh(attrib);
}
}
if (fLibraryList.getSelectedElements().isEmpty()) {
if (selectionAfter != null) {
fLibraryList.selectElements(new StructuredSelection(selectionAfter));
} else {
fLibraryList.selectFirstElement();
}
}
}
private void doAdd(List list) {
if (canAdd(list)) {
CPUserLibraryElement element= getSingleSelectedLibrary(list);
editArchiveElement(null, element);
}
}
private void doLoad() {
LoadSaveDialog dialog= new LoadSaveDialog(getShell(), null, fDialogSettings);
if (dialog.open() == Window.OK) {
List existing= fLibraryList.getElements();
HashMap map= new HashMap(existing.size());
for (int k= 0; k < existing.size(); k++) {
CPUserLibraryElement elem= (CPUserLibraryElement) existing.get(k);
map.put(elem.getName(), elem);
}
List list= dialog.getLoadedLibraries();
for (int i= 0; i < list.size(); i++) {
CPUserLibraryElement elem= (CPUserLibraryElement) list.get(i);
CPUserLibraryElement found= (CPUserLibraryElement) map.get(elem.getName());
if (found == null) {
existing.add(elem);
map.put(elem.getName(), elem);
} else {
existing.set(existing.indexOf(found), elem); // replace
}
}
fLibraryList.setElements(existing);
fLibraryList.selectElements(new StructuredSelection(list));
}
}
private void doSave() {
LoadSaveDialog dialog= new LoadSaveDialog(getShell(), fLibraryList.getElements(), fDialogSettings);
dialog.open();
}
private boolean canAdd(List list) {
return getSingleSelectedLibrary(list) != null;
}
private boolean canEdit(List list) {
if (list.size() == 1) {
return true;
}
return false;
}
private boolean canRemove(List list) {
return true;
}
private CPListElement[] openExtJarFileDialog(CPListElement existing, Object parent) {
String lastUsedPath;
if (existing != null) {
lastUsedPath= existing.getPath().removeLastSegments(1).toOSString();
} else {
lastUsedPath= fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTEXTJAR);
if (lastUsedPath == null) {
lastUsedPath= ""; //$NON-NLS-1$
}
}
String title= (existing == null) ? PreferencesMessages.getString("UserLibraryPreferencePage.browsejar.new.title") : PreferencesMessages.getString("UserLibraryPreferencePage.browseJAR.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
FileDialog dialog= new FileDialog(getShell(), existing == null ? SWT.MULTI : SWT.SINGLE);
dialog.setText(title);
dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$
dialog.setFilterPath(lastUsedPath);
if (existing != null) {
dialog.setFileName(existing.getPath().lastSegment());
}
String res= dialog.open();
if (res == null) {
return null;
}
String[] fileNames= dialog.getFileNames();
int nChosen= fileNames.length;
IPath filterPath= new Path(dialog.getFilterPath());
CPListElement[] elems= new CPListElement[nChosen];
for (int i= 0; i < nChosen; i++) {
IPath path= filterPath.append(fileNames[i]).makeAbsolute();
CPListElement curr= new CPListElement(parent, null, IClasspathEntry.CPE_LIBRARY, path, null);
curr.setAttribute(CPListElement.SOURCEATTACHMENT, BuildPathSupport.guessSourceAttachment(curr));
curr.setAttribute(CPListElement.JAVADOC, JavaUI.getLibraryJavadocLocation(curr.getPath()));
elems[i]= curr;
}
fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, filterPath.toOSString());
return elems;
}
private class UserLibraryAdapter implements ITreeListAdapter {
private final Object[] EMPTY= new Object[0];
public void customButtonPressed(TreeListDialogField field, int index) {
doCustomButtonPressed(field, index);
}
public void selectionChanged(TreeListDialogField field) {
doSelectionChanged(field);
}
public void doubleClicked(TreeListDialogField field) {
doDoubleClicked(field);
}
public void keyPressed(TreeListDialogField field, KeyEvent event) {
doKeyPressed(field, event);
}
public Object[] getChildren(TreeListDialogField field, Object element) {
if (element instanceof CPUserLibraryElement) {
CPUserLibraryElement elem= (CPUserLibraryElement) element;
return elem.getChildren();
} else if (element instanceof CPListElement) {
return ((CPListElement)element).getChildren(false);
}
return EMPTY;
}
public Object getParent(TreeListDialogField field, Object element) {
if (element instanceof CPListElementAttribute) {
return ((CPListElementAttribute) element).getParent();
} else if (element instanceof CPListElement) {
return ((CPListElement) element).getParentContainer();
}
return null;
}
public boolean hasChildren(TreeListDialogField field, Object element) {
return getChildren(field, element).length > 0;
}
}
}
|
54,737 |
Bug 54737 Libraries dialog doesn't remember status of items in library tree
|
Preferences > Java > Build Path > User Libraries: The dialog does not seem to correctly remember the status of the items in the "Defined user libraries" tree. When I leave the dialog I close (un-cascade) all items. When I open the dialog again, most of the items are open (cascaded) again. This is disturbing because I cannot overview the items. It's like opening the Windows explorer with not only the drives shown but all folders being open.
|
resolved fixed
|
91f4e29
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-15T14:43:22Z | 2004-03-13T12:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/TreeListDialogField.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.dialogfields;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
/**
* A list with a button bar.
* Typical buttons are 'Add', 'Remove', 'Up' and 'Down'.
* List model is independend of widget creation.
* DialogFields controls are: Label, List and Composite containing buttons.
*/
public class TreeListDialogField extends DialogField {
protected TreeViewer fTree;
protected ILabelProvider fLabelProvider;
protected TreeViewerAdapter fTreeViewerAdapter;
protected List fElements;
protected ViewerSorter fViewerSorter;
protected String[] fButtonLabels;
private Button[] fButtonControls;
private boolean[] fButtonsEnabled;
private int fRemoveButtonIndex;
private int fUpButtonIndex;
private int fDownButtonIndex;
private Label fLastSeparator;
private Tree fTreeControl;
private Composite fButtonsControl;
private ISelection fSelectionWhenEnabled;
private ITreeListAdapter fTreeAdapter;
private Object fParentElement;
private int fTreeExpandLevel;
/**
* @param adapter Can be <code>null</code>.
*/
public TreeListDialogField(ITreeListAdapter adapter, String[] buttonLabels, ILabelProvider lprovider) {
super();
fTreeAdapter= adapter;
fLabelProvider= lprovider;
fTreeViewerAdapter= new TreeViewerAdapter();
fParentElement= this;
fElements= new ArrayList(10);
fButtonLabels= buttonLabels;
if (fButtonLabels != null) {
int nButtons= fButtonLabels.length;
fButtonsEnabled= new boolean[nButtons];
for (int i= 0; i < nButtons; i++) {
fButtonsEnabled[i]= true;
}
}
fTree= null;
fTreeControl= null;
fButtonsControl= null;
fRemoveButtonIndex= -1;
fUpButtonIndex= -1;
fDownButtonIndex= -1;
fTreeExpandLevel= 0;
}
/**
* Sets the index of the 'remove' button in the button label array passed in
* the constructor. The behaviour of the button marked as the 'remove' button
* will then behandled internally. (enable state, button invocation
* behaviour)
*/
public void setRemoveButtonIndex(int removeButtonIndex) {
Assert.isTrue(removeButtonIndex < fButtonLabels.length);
fRemoveButtonIndex= removeButtonIndex;
}
/**
* Sets the index of the 'up' button in the button label array passed in the
* constructor. The behaviour of the button marked as the 'up' button will
* then behandled internally.
* (enable state, button invocation behaviour)
*/
public void setUpButtonIndex(int upButtonIndex) {
Assert.isTrue(upButtonIndex < fButtonLabels.length);
fUpButtonIndex= upButtonIndex;
}
/**
* Sets the index of the 'down' button in the button label array passed in
* the constructor. The behaviour of the button marked as the 'down' button
* will then be handled internally. (enable state, button invocation
* behaviour)
*/
public void setDownButtonIndex(int downButtonIndex) {
Assert.isTrue(downButtonIndex < fButtonLabels.length);
fDownButtonIndex= downButtonIndex;
}
/**
* Sets the viewerSorter.
* @param viewerSorter The viewerSorter to set
*/
public void setViewerSorter(ViewerSorter viewerSorter) {
fViewerSorter= viewerSorter;
}
/**
* Sets the viewerSorter.
* @param viewerSorter The viewerSorter to set
*/
public void setTreeExpansionLevel(int level) {
fTreeExpandLevel= level;
if (fTree != null) {
fTree.expandToLevel(level);
}
}
// ------ adapter communication
private void buttonPressed(int index) {
if (!managedButtonPressed(index) && fTreeAdapter != null) {
fTreeAdapter.customButtonPressed(this, index);
}
}
/**
* Checks if the button pressed is handled internally
* @return Returns true if button has been handled.
*/
protected boolean managedButtonPressed(int index) {
if (index == fRemoveButtonIndex) {
remove();
} else if (index == fUpButtonIndex) {
up();
} else if (index == fDownButtonIndex) {
down();
} else {
return false;
}
return true;
}
// ------ layout helpers
/*
* @see DialogField#doFillIntoGrid
*/
public Control[] doFillIntoGrid(Composite parent, int nColumns) {
PixelConverter converter= new PixelConverter(parent);
assertEnoughColumns(nColumns);
Label label= getLabelControl(parent);
GridData gd= gridDataForLabel(1);
gd.verticalAlignment= GridData.BEGINNING;
label.setLayoutData(gd);
Control list= getTreeControl(parent);
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= false;
gd.verticalAlignment= GridData.FILL;
gd.grabExcessVerticalSpace= true;
gd.horizontalSpan= nColumns - 2;
gd.widthHint= converter.convertWidthInCharsToPixels(50);
gd.heightHint= converter.convertHeightInCharsToPixels(6);
list.setLayoutData(gd);
Composite buttons= getButtonBox(parent);
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= false;
gd.verticalAlignment= GridData.FILL;
gd.grabExcessVerticalSpace= true;
gd.horizontalSpan= 1;
buttons.setLayoutData(gd);
return new Control[] { label, list, buttons };
}
/*
* @see DialogField#getNumberOfControls
*/
public int getNumberOfControls() {
return 3;
}
/**
* Sets the minimal width of the buttons. Must be called after widget creation.
*/
public void setButtonsMinWidth(int minWidth) {
if (fLastSeparator != null) {
((GridData) fLastSeparator.getLayoutData()).widthHint= minWidth;
}
}
// ------ ui creation
/**
* Returns the tree control. When called the first time, the control will be
* created.
* @param The parent composite when called the first time, or <code>null</code>
* after.
*/
public Control getTreeControl(Composite parent) {
if (fTreeControl == null) {
assertCompositeNotNull(parent);
fTree= createTreeViewer(parent);
fTreeControl= (Tree) fTree.getControl();
fTreeControl.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
handleKeyPressed(e);
}
});
fTree.setAutoExpandLevel(99);
fTree.setContentProvider(fTreeViewerAdapter);
fTree.setLabelProvider(fLabelProvider);
fTree.addSelectionChangedListener(fTreeViewerAdapter);
fTree.addDoubleClickListener(fTreeViewerAdapter);
fTree.setInput(fParentElement);
fTree.expandToLevel(fTreeExpandLevel);
if (fViewerSorter != null) {
fTree.setSorter(fViewerSorter);
}
fTreeControl.setEnabled(isEnabled());
if (fSelectionWhenEnabled != null) {
postSetSelection(fSelectionWhenEnabled);
}
}
return fTreeControl;
}
/**
* Returns the internally used table viewer.
*/
public TreeViewer getTreeViewer() {
return fTree;
}
/*
* Subclasses may override to specify a different style.
*/
protected int getTreeStyle() {
int style= SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL;
return style;
}
protected TreeViewer createTreeViewer(Composite parent) {
Tree tree= new Tree(parent, getTreeStyle());
return new TreeViewer(tree);
}
protected Button createButton(Composite parent, String label, SelectionListener listener) {
Button button= new Button(parent, SWT.PUSH);
button.setText(label);
button.addSelectionListener(listener);
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= true;
gd.verticalAlignment= GridData.BEGINNING;
gd.heightHint= SWTUtil.getButtonHeightHint(button);
gd.widthHint= SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
return button;
}
private Label createSeparator(Composite parent) {
Label separator= new Label(parent, SWT.NONE);
separator.setVisible(false);
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.verticalAlignment= GridData.BEGINNING;
gd.heightHint= 4;
separator.setLayoutData(gd);
return separator;
}
/**
* Returns the composite containing the buttons. When called the first time, the control
* will be created.
* @param The parent composite when called the first time, or <code>null</code>
* after.
*/
public Composite getButtonBox(Composite parent) {
if (fButtonsControl == null) {
assertCompositeNotNull(parent);
SelectionListener listener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
doButtonSelected(e);
}
public void widgetSelected(SelectionEvent e) {
doButtonSelected(e);
}
};
Composite contents= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
contents.setLayout(layout);
if (fButtonLabels != null) {
fButtonControls= new Button[fButtonLabels.length];
for (int i= 0; i < fButtonLabels.length; i++) {
String currLabel= fButtonLabels[i];
if (currLabel != null) {
fButtonControls[i]= createButton(contents, currLabel, listener);
fButtonControls[i].setEnabled(isEnabled() && fButtonsEnabled[i]);
} else {
fButtonControls[i]= null;
createSeparator(contents);
}
}
}
fLastSeparator= createSeparator(contents);
updateButtonState();
fButtonsControl= contents;
}
return fButtonsControl;
}
private void doButtonSelected(SelectionEvent e) {
if (fButtonControls != null) {
for (int i= 0; i < fButtonControls.length; i++) {
if (e.widget == fButtonControls[i]) {
buttonPressed(i);
return;
}
}
}
}
/**
* Handles key events in the table viewer. Specifically
* when the delete key is pressed.
*/
protected void handleKeyPressed(KeyEvent event) {
if (event.character == SWT.DEL && event.stateMask == 0) {
if (fRemoveButtonIndex != -1 && isButtonEnabled(fTree.getSelection(), fRemoveButtonIndex)) {
managedButtonPressed(fRemoveButtonIndex);
return;
}
}
fTreeAdapter.keyPressed(this, event);
}
// ------ enable / disable management
/*
* @see DialogField#dialogFieldChanged
*/
public void dialogFieldChanged() {
super.dialogFieldChanged();
updateButtonState();
}
/*
* Updates the enable state of the all buttons
*/
protected void updateButtonState() {
if (fButtonControls != null) {
ISelection sel= fTree.getSelection();
for (int i= 0; i < fButtonControls.length; i++) {
Button button= fButtonControls[i];
if (isOkToUse(button)) {
button.setEnabled(isButtonEnabled(sel, i));
}
}
}
}
protected boolean containsAttributes(List selected) {
for (int i= 0; i < selected.size(); i++) {
if (!fElements.contains(selected.get(i))) {
return true;
}
}
return false;
}
protected boolean getManagedButtonState(ISelection sel, int index) {
List selected= getSelectedElements();
boolean hasAttributes= containsAttributes(selected);
if (index == fRemoveButtonIndex) {
return !selected.isEmpty() && !hasAttributes;
} else if (index == fUpButtonIndex) {
return !sel.isEmpty() && !hasAttributes && canMoveUp(selected);
} else if (index == fDownButtonIndex) {
return !sel.isEmpty() && !hasAttributes && canMoveDown(selected);
}
return true;
}
/*
* @see DialogField#updateEnableState
*/
protected void updateEnableState() {
super.updateEnableState();
boolean enabled= isEnabled();
if (isOkToUse(fTreeControl)) {
if (!enabled) {
fSelectionWhenEnabled= fTree.getSelection();
selectElements(null);
} else {
selectElements(fSelectionWhenEnabled);
fSelectionWhenEnabled= null;
}
fTreeControl.setEnabled(enabled);
}
updateButtonState();
}
/**
* Sets a button enabled or disabled.
*/
public void enableButton(int index, boolean enable) {
if (fButtonsEnabled != null && index < fButtonsEnabled.length) {
fButtonsEnabled[index]= enable;
updateButtonState();
}
}
private boolean isButtonEnabled(ISelection sel, int index) {
boolean extraState= getManagedButtonState(sel, index);
return isEnabled() && extraState && fButtonsEnabled[index];
}
// ------ model access
/**
* Sets the elements shown in the list.
*/
public void setElements(List elements) {
fElements= new ArrayList(elements);
refresh();
if (fTree != null) {
fTree.expandToLevel(fTreeExpandLevel);
}
dialogFieldChanged();
}
/**
* Gets the elements shown in the list.
* The list returned is a copy, so it can be modified by the user.
*/
public List getElements() {
return new ArrayList(fElements);
}
/**
* Gets the element shown at the given index.
*/
public Object getElement(int index) {
return fElements.get(index);
}
/**
* Gets the index of an element in the list or -1 if element is not in list.
*/
public int getIndexOfElement(Object elem) {
return fElements.indexOf(elem);
}
/**
* Replace an element.
*/
public void replaceElement(Object oldElement, Object newElement) throws IllegalArgumentException {
int idx= fElements.indexOf(oldElement);
if (idx != -1) {
fElements.set(idx, newElement);
if (fTree != null) {
List selected= getSelectedElements();
if (selected.remove(oldElement)) {
selected.add(newElement);
}
boolean isExpanded= fTree.getExpandedState(oldElement);
fTree.remove(oldElement);
fTree.add(fParentElement, newElement);
if (isExpanded) {
fTree.expandToLevel(newElement, fTreeExpandLevel);
}
selectElements(new StructuredSelection(selected));
}
dialogFieldChanged();
} else {
throw new IllegalArgumentException();
}
}
/**
* Adds an element at the end of the tree list.
*/
public void addElement(Object element) {
if (fElements.contains(element)) {
return;
}
fElements.add(element);
if (fTree != null) {
fTree.add(fParentElement, element);
fTree.expandToLevel(element, fTreeExpandLevel);
}
dialogFieldChanged();
}
/**
* Adds elements at the end of the tree list.
*/
public void addElements(List elements) {
int nElements= elements.size();
if (nElements > 0) {
// filter duplicated
ArrayList elementsToAdd= new ArrayList(nElements);
for (int i= 0; i < nElements; i++) {
Object elem= elements.get(i);
if (!fElements.contains(elem)) {
elementsToAdd.add(elem);
}
}
fElements.addAll(elementsToAdd);
if (fTree != null) {
fTree.add(fParentElement, elementsToAdd.toArray());
for (int i= 0; i < elementsToAdd.size(); i++) {
fTree.expandToLevel(elementsToAdd.get(i), fTreeExpandLevel);
}
}
dialogFieldChanged();
}
}
/**
* Adds an element at a position.
*/
public void insertElementAt(Object element, int index) {
if (fElements.contains(element)) {
return;
}
fElements.add(index, element);
if (fTree != null) {
fTree.add(fParentElement, element);
if (fTreeExpandLevel != -1) {
fTree.expandToLevel(element, fTreeExpandLevel);
}
}
dialogFieldChanged();
}
/**
* Adds an element at a position.
*/
public void removeAllElements() {
if (fElements.size() > 0) {
fElements.clear();
refresh();
dialogFieldChanged();
}
}
/**
* Removes an element from the list.
*/
public void removeElement(Object element) throws IllegalArgumentException {
if (fElements.remove(element)) {
if (fTree != null) {
fTree.remove(element);
}
dialogFieldChanged();
} else {
throw new IllegalArgumentException();
}
}
/**
* Removes elements from the list.
*/
public void removeElements(List elements) {
if (elements.size() > 0) {
fElements.removeAll(elements);
if (fTree != null) {
fTree.remove(elements.toArray());
}
dialogFieldChanged();
}
}
/**
* Gets the number of elements
*/
public int getSize() {
return fElements.size();
}
public void selectElements(ISelection selection) {
fSelectionWhenEnabled= selection;
if (fTree != null) {
fTree.setSelection(selection, true);
}
}
public void selectFirstElement() {
Object element= null;
if (fViewerSorter != null) {
Object[] arr= fElements.toArray();
fViewerSorter.sort(fTree, arr);
if (arr.length > 0) {
element= arr[0];
}
} else {
if (fElements.size() > 0) {
element= fElements.get(0);
}
}
if (element != null) {
selectElements(new StructuredSelection(element));
}
}
public void postSetSelection(final ISelection selection) {
if (isOkToUse(fTreeControl)) {
Display d= fTreeControl.getDisplay();
d.asyncExec(new Runnable() {
public void run() {
if (isOkToUse(fTreeControl)) {
selectElements(selection);
}
}
});
}
}
/**
* Refreshes the tree.
*/
public void refresh() {
if (fTree != null) {
fTree.refresh();
}
}
/**
* Refreshes the tree.
*/
public void refresh(Object element) {
if (fTree != null) {
fTree.refresh(element);
}
}
// ------- list maintenance
private List moveUp(List elements, List move) {
int nElements= elements.size();
List res= new ArrayList(nElements);
Object floating= null;
for (int i= 0; i < nElements; i++) {
Object curr= elements.get(i);
if (move.contains(curr)) {
res.add(curr);
} else {
if (floating != null) {
res.add(floating);
}
floating= curr;
}
}
if (floating != null) {
res.add(floating);
}
return res;
}
private void moveUp(List toMoveUp) {
if (toMoveUp.size() > 0) {
setElements(moveUp(fElements, toMoveUp));
fTree.reveal(toMoveUp.get(0));
}
}
private void moveDown(List toMoveDown) {
if (toMoveDown.size() > 0) {
setElements(reverse(moveUp(reverse(fElements), toMoveDown)));
fTree.reveal(toMoveDown.get(toMoveDown.size() - 1));
}
}
private List reverse(List p) {
List reverse= new ArrayList(p.size());
for (int i= p.size() - 1; i >= 0; i--) {
reverse.add(p.get(i));
}
return reverse;
}
private void remove() {
removeElements(getSelectedElements());
}
private void up() {
moveUp(getSelectedElements());
}
private void down() {
moveDown(getSelectedElements());
}
private boolean canMoveUp(List selectedElements) {
if (isOkToUse(fTreeControl)) {
int nSelected= selectedElements.size();
int nElements= fElements.size();
for (int i= 0; i < nElements && nSelected > 0; i++) {
if (!selectedElements.contains(fElements.get(i))) {
return true;
}
nSelected--;
}
}
return false;
}
private boolean canMoveDown(List selectedElements) {
if (isOkToUse(fTreeControl)) {
int nSelected= selectedElements.size();
for (int i= fElements.size() - 1; i >= 0 && nSelected > 0; i--) {
if (!selectedElements.contains(fElements.get(i))) {
return true;
}
nSelected--;
}
}
return false;
}
/**
* Returns the selected elements.
*/
public List getSelectedElements() {
ArrayList result= new ArrayList();
if (fTree != null) {
ISelection selection= fTree.getSelection();
if (selection instanceof IStructuredSelection) {
Iterator iter= ((IStructuredSelection)selection).iterator();
while (iter.hasNext()) {
result.add(iter.next());
}
}
}
return result;
}
public void expandElement(Object element, int level) {
if (fTree != null) {
fTree.expandToLevel(element, level);
}
}
// ------- TreeViewerAdapter
private class TreeViewerAdapter implements ITreeContentProvider, ISelectionChangedListener, IDoubleClickListener {
private final Object[] NO_ELEMENTS= new Object[0];
// ------- ITreeContentProvider Interface ------------
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// will never happen
}
public boolean isDeleted(Object element) {
return false;
}
public void dispose() {
}
public Object[] getElements(Object obj) {
return fElements.toArray();
}
public Object[] getChildren(Object element) {
if (fTreeAdapter != null) {
return fTreeAdapter.getChildren(TreeListDialogField.this, element);
}
return NO_ELEMENTS;
}
public Object getParent(Object element) {
if (!fElements.contains(element) && fTreeAdapter != null) {
return fTreeAdapter.getParent(TreeListDialogField.this, element);
}
return fParentElement;
}
public boolean hasChildren(Object element) {
if (fTreeAdapter != null) {
return fTreeAdapter.hasChildren(TreeListDialogField.this, element);
}
return false;
}
// ------- ISelectionChangedListener Interface ------------
public void selectionChanged(SelectionChangedEvent event) {
doListSelected(event);
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IDoubleClickListener#doubleClick(org.eclipse.jface.viewers.DoubleClickEvent)
*/
public void doubleClick(DoubleClickEvent event) {
doDoubleClick(event);
}
}
protected void doListSelected(SelectionChangedEvent event) {
updateButtonState();
if (fTreeAdapter != null) {
fTreeAdapter.selectionChanged(this);
}
}
protected void doDoubleClick(DoubleClickEvent event) {
if (fTreeAdapter != null) {
fTreeAdapter.doubleClicked(this);
}
}
}
|
46,775 |
Bug 46775 [reconciling] Need a save synchronization method to ensure transactional updating of problem requestor
|
I20031113 Each working copy has a problem requestor for its lifetime. The problem requestor needs to be updated transactionally, i.e. no interleaving start/end call pairs. In order to ensure that, IWorkingCopy.reconcile should only be called when being in a monitor locking the working copy. This scheme is "per convention" and not satisfied by the Java core itself. We need a better scheme to also avoid the reconciler to become active during long running operations involving files open in editors such as refactorings across many files. A workspace operation using the working copy as scheduling rule seems appropriate. Need to check how to deal with working copies without an underlying resource. Need to check for the most appropriate location, i.e. caller or callee.
|
resolved fixed
|
805765d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-15T15:32:19Z | 2003-11-17T14:40:00Z |
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.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.IResource;
import org.eclipse.core.resources.IResourceRuleFactory;
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.ISynchronizable;
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.IAnnotationAccessExtension;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelListener;
import org.eclipse.jface.text.source.IAnnotationModelListenerExtension;
import org.eclipse.jface.text.source.IAnnotationPresentation;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.editors.text.TextFileDocumentProvider;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.AnnotationPreferenceLookup;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.MarkerUtilities;
import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.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.text.correction.JavaCorrectionProcessor;
import org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension;
import org.eclipse.jdt.internal.ui.text.spelling.SpellReconcileStrategy.SpellProblem;
public class CompilationUnitDocumentProvider 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, IAnnotationPresentation {
private static final String SPELLING_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.spelling"; //$NON-NLS-1$
//XXX: To be fully correct these constants should be non-static
/**
* The layer in which task problem annotations are located.
*/
private static final int TASK_LAYER;
/**
* The layer in which info problem annotations are located.
*/
private static final int INFO_LAYER;
/**
* The layer in which warning problem annotations representing are located.
*/
private static final int WARNING_LAYER;
/**
* The layer in which error problem annotations representing are located.
*/
private static final int ERROR_LAYER;
static {
AnnotationPreferenceLookup lookup= EditorsUI.getAnnotationPreferenceLookup();
TASK_LAYER= computeLayer("org.eclipse.ui.workbench.texteditor.task", lookup); //$NON-NLS-1$
INFO_LAYER= computeLayer("org.eclipse.jdt.ui.info", lookup); //$NON-NLS-1$
WARNING_LAYER= computeLayer("org.eclipse.jdt.ui.warning", lookup); //$NON-NLS-1$
ERROR_LAYER= computeLayer("org.eclipse.jdt.ui.error", lookup); //$NON-NLS-1$
}
private static int computeLayer(String annotationType, AnnotationPreferenceLookup lookup) {
Annotation annotation= new Annotation(annotationType, false, null);
AnnotationPreference preference= lookup.getAnnotationPreference(annotation);
if (preference != null)
return preference.getPresentationLayer() + 1;
else
return IAnnotationAccessExtension.DEFAULT_LAYER + 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 int fLayer= IAnnotationAccessExtension.DEFAULT_LAYER;
public ProblemAnnotation(IProblem problem, ICompilationUnit cu) {
fProblem= problem;
fCompilationUnit= cu;
if (SpellProblem.Spelling == fProblem.getID()) {
setType(SPELLING_ANNOTATION_TYPE);
fLayer= WARNING_LAYER;
} else if (IProblem.Task == fProblem.getID()) {
setType(JavaMarkerAnnotation.TASK_ANNOTATION_TYPE);
fLayer= TASK_LAYER;
} else if (fProblem.isWarning()) {
setType(JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE);
fLayer= WARNING_LAYER;
} else if (fProblem.isError()) {
setType(JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE);
fLayer= ERROR_LAYER;
} else {
setType(JavaMarkerAnnotation.INFO_ANNOTATION_TYPE);
fLayer= INFO_LAYER;
}
}
/*
* @see org.eclipse.jface.text.source.IAnnotationPresentation#getLayer()
*/
public int getLayer() {
return fLayer;
}
private void initializeImages() {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=18936
if (!fQuickFixImagesInitialized) {
if (isProblem() && indicateQuixFixableProblems() && JavaCorrectionProcessor.hasCorrections(this)) { // no light bulb for tasks
if (!fgQuickFixImagesInitialized) {
fgQuickFixImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM);
fgQuickFixErrorImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_ERROR);
fgQuickFixImagesInitialized= true;
}
if (JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(getType()))
fImage= fgQuickFixErrorImage;
else
fImage= fgQuickFixImage;
}
fQuickFixImagesInitialized= true;
}
}
private boolean indicateQuixFixableProblems() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION);
}
/*
* @see Annotation#paint
*/
public void paint(GC gc, Canvas canvas, Rectangle r) {
initializeImages();
if (fImage != null)
drawImage(fImage, gc, canvas, r, SWT.CENTER, SWT.TOP);
}
/*
* @see IJavaAnnotation#getImage(Display)
*/
public Image getImage(Display display) {
initializeImages();
return fImage;
}
/*
* @see IJavaAnnotation#getMessage()
*/
public String getText() {
return fProblem.getMessage();
}
/*
* @see IJavaAnnotation#getArguments()
*/
public String[] getArguments() {
return isProblem() ? fProblem.getArguments() : null;
}
/*
* @see IJavaAnnotation#getId()
*/
public int getId() {
return fProblem.getID();
}
/*
* @see IJavaAnnotation#isProblem()
*/
public boolean isProblem() {
String type= getType();
return JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE.equals(type) ||
JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(type) ||
SPELLING_ANNOTATION_TYPE.equals(type);
}
/*
* @see IJavaAnnotation#hasOverlay()
*/
public boolean hasOverlay() {
return false;
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation#getOverlay()
*/
public IJavaAnnotation getOverlay() {
return null;
}
/*
* @see IJavaAnnotation#addOverlaid(IJavaAnnotation)
*/
public void addOverlaid(IJavaAnnotation annotation) {
if (fOverlaids == null)
fOverlaids= new ArrayList(1);
fOverlaids.add(annotation);
}
/*
* @see IJavaAnnotation#removeOverlaid(IJavaAnnotation)
*/
public void removeOverlaid(IJavaAnnotation annotation) {
if (fOverlaids != null) {
fOverlaids.remove(annotation);
if (fOverlaids.size() == 0)
fOverlaids= null;
}
}
/*
* @see IJavaAnnotation#getOverlaidIterator()
*/
public Iterator getOverlaidIterator() {
if (fOverlaids != null)
return fOverlaids.iterator();
return null;
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation#getCompilationUnit()
*/
public ICompilationUnit getCompilationUnit() {
return fCompilationUnit;
}
}
/**
* Internal structure for mapping positions to some value.
* The reason for this specific structure is that positions can
* change over time. Thus a lookup is based on value and not
* on hash value.
*/
protected static class ReverseMap {
static class Entry {
Position fPosition;
Object fValue;
}
private List fList= new ArrayList(2);
private int fAnchor= 0;
public ReverseMap() {
}
public Object get(Position position) {
Entry entry;
// behind anchor
int length= fList.size();
for (int i= fAnchor; i < length; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position)) {
fAnchor= i;
return entry.fValue;
}
}
// before anchor
for (int i= 0; i < fAnchor; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position)) {
fAnchor= i;
return entry.fValue;
}
}
return null;
}
private int getIndex(Position position) {
Entry entry;
int length= fList.size();
for (int i= 0; i < length; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position))
return i;
}
return -1;
}
public void put(Position position, Object value) {
int index= getIndex(position);
if (index == -1) {
Entry entry= new Entry();
entry.fPosition= position;
entry.fValue= value;
fList.add(entry);
} else {
Entry entry= (Entry) fList.get(index);
entry.fValue= value;
}
}
public void remove(Position position) {
int index= getIndex(position);
if (index > -1)
fList.remove(index);
}
public void clear() {
fList.clear();
}
}
/**
* Annotation model dealing with java marker annotations and temporary problems.
* Also acts as problem requestor for its compilation unit. Initialiy inactive. Must explicitly be
* activated.
*/
protected static class CompilationUnitAnnotationModel extends ResourceMarkerAnnotationModel implements IProblemRequestor, IProblemRequestorExtension {
private boolean fInsideReportingSequence= false;
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();
public CompilationUnitAnnotationModel(IResource resource) {
super(resource);
}
public void setCompilationUnit(ICompilationUnit unit) {
fCompilationUnit= unit;
}
protected MarkerAnnotation createMarkerAnnotation(IMarker marker) {
String markerType= MarkerUtilities.getMarkerType(marker);
if (markerType != null && markerType.startsWith(JavaMarkerAnnotation.JAVA_MARKER_TYPE_PREFIX))
return new JavaMarkerAnnotation(marker);
return super.createMarkerAnnotation(marker);
}
/*
* @see org.eclipse.jface.text.source.AnnotationModel#createAnnotationModelEvent()
*/
protected AnnotationModelEvent createAnnotationModelEvent() {
return new CompilationUnitAnnotationModelEvent(this, getResource());
}
protected Position createPositionFromProblem(IProblem problem) {
int start= problem.getSourceStart();
if (start < 0)
return null;
int length= problem.getSourceEnd() - problem.getSourceStart() + 1;
if (length < 0)
return null;
return new Position(start, length);
}
/*
* @see IProblemRequestor#beginReporting()
*/
public void beginReporting() {
if (!fInsideReportingSequence)
internalBeginReporting();
}
/*
* @see org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension#beginReportingSequence()
*/
public void beginReportingSequence() {
fInsideReportingSequence= true;
internalBeginReporting();
}
/**
* Signals the beginning of problem reporting.
*/
private void internalBeginReporting() {
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 (!fInsideReportingSequence)
internalEndReporting();
}
/*
* @see org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension#endReportingSequence()
*/
public void endReportingSequence() {
internalEndReporting();
fInsideReportingSequence= false;
}
/**
* Signals the end of problem reporting.
*/
private void internalEndReporting() {
if (!isActive())
return;
if (fProgressMonitor != null && fProgressMonitor.isCanceled())
return;
boolean isCanceled= false;
boolean temporaryProblemsChanged= false;
synchronized (getLockObject()) {
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);
overlayMarkers(position, annotation);
addAnnotation(annotation, position, false);
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);
}
} else {
}
}
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 IProblemRequestor#isActive()
*/
public boolean isActive() {
return fIsActive && (fCollectedProblems != null);
}
/*
* @see IProblemRequestorExtension#setProgressMonitor(IProgressMonitor)
*/
public void setProgressMonitor(IProgressMonitor monitor) {
fProgressMonitor= monitor;
}
/*
* @see IProblemRequestorExtension#setIsActive(boolean)
*/
public void setIsActive(boolean isActive) {
if (fIsActive != isActive) {
fIsActive= isActive;
if (fIsActive)
startCollectingProblems();
else
stopCollectingProblems();
}
}
private Object getAnnotations(Position position) {
return fReverseMap.get(position);
}
/*
* @see AnnotationModel#addAnnotation(Annotation, Position, boolean)
*/
protected void addAnnotation(Annotation annotation, Position position, boolean fireModelChanged) throws BadLocationException {
super.addAnnotation(annotation, position, fireModelChanged);
Object cached= fReverseMap.get(position);
if (cached == null)
fReverseMap.put(position, annotation);
else if (cached instanceof List) {
List list= (List) cached;
list.add(annotation);
} else if (cached instanceof Annotation) {
List list= new ArrayList(2);
list.add(cached);
list.add(annotation);
fReverseMap.put(position, list);
}
}
/*
* @see AnnotationModel#removeAllAnnotations(boolean)
*/
protected void removeAllAnnotations(boolean fireModelChanged) {
super.removeAllAnnotations(fireModelChanged);
fReverseMap.clear();
}
/*
* @see AnnotationModel#removeAnnotation(Annotation, boolean)
*/
protected void removeAnnotation(Annotation annotation, boolean fireModelChanged) {
Position position= getPosition(annotation);
Object cached= fReverseMap.get(position);
if (cached instanceof List) {
List list= (List) cached;
list.remove(annotation);
if (list.size() == 1) {
fReverseMap.put(position, list.get(0));
list.clear();
}
} else if (cached instanceof Annotation) {
fReverseMap.remove(position);
}
super.removeAnnotation(annotation, fireModelChanged);
}
}
protected static class GlobalAnnotationModelListener implements IAnnotationModelListener, IAnnotationModelListenerExtension {
private ListenerList fListenerList;
public GlobalAnnotationModelListener() {
fListenerList= new ListenerList();
}
/**
* @see IAnnotationModelListener#modelChanged(IAnnotationModel)
*/
public void modelChanged(IAnnotationModel model) {
Object[] listeners= fListenerList.getListeners();
for (int i= 0; i < listeners.length; i++) {
((IAnnotationModelListener) listeners[i]).modelChanged(model);
}
}
/**
* @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent)
*/
public void modelChanged(AnnotationModelEvent event) {
Object[] listeners= fListenerList.getListeners();
for (int i= 0; i < listeners.length; i++) {
Object curr= listeners[i];
if (curr instanceof IAnnotationModelListenerExtension) {
((IAnnotationModelListenerExtension) curr).modelChanged(event);
}
}
}
public void addListener(IAnnotationModelListener listener) {
fListenerList.add(listener);
}
public void removeListener(IAnnotationModelListener listener) {
fListenerList.remove(listener);
}
}
/** Preference key for temporary problems */
private final static String HANDLE_TEMPORARY_PROBLEMS= PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS;
/** Indicates whether the save has been initialized by this provider */
private boolean fIsAboutToSave= false;
/** The save policy used by this provider */
private ISavePolicy fSavePolicy;
/** Internal property changed listener */
private IPropertyChangeListener fPropertyListener;
/** Annotation model listener added to all created CU annotation models */
private GlobalAnnotationModelListener fGlobalAnnotationModelListener;
/**
* Constructor
*/
public CompilationUnitDocumentProvider() {
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;
setUpSynchronization(cuInfo);
IProblemRequestor requestor= cuInfo.fModel instanceof IProblemRequestor ? (IProblemRequestor) cuInfo.fModel : null;
original.becomeWorkingCopy(requestor, getProgressMonitor());
cuInfo.fCopy= original;
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;
}
private void setUpSynchronization(CompilationUnitInfo cuInfo) {
IDocument document= cuInfo.fTextFileBuffer.getDocument();
IAnnotationModel model= cuInfo.fModel;
if (document instanceof ISynchronizable && model instanceof ISynchronizable) {
Object lock= ((ISynchronizable) document).getLockObject();
((ISynchronizable) model).setLockObject(lock);
}
}
/*
* @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;
try {
cuInfo.fCopy.discardWorkingCopy();
} catch (JavaModelException x) {
handleCoreException(x, x.getMessage());
}
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();
IResource resource= info.fCopy.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;
info.fCopy.commitWorkingCopy(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.
if (info.fModel instanceof AbstractMarkerAnnotationModel) {
AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel;
model.updateMarkers(document);
}
if (fSavePolicy != null) {
ICompilationUnit unit= fSavePolicy.postSave(info.fCopy);
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() {
/*
* @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor)
*/
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) {
IFile file= ((IFileEditorInput) info.fElement).getFile();
IResourceRuleFactory ruleFactory= ResourcesPlugin.getWorkspace().getRuleFactory();
if (file == null || !file.exists())
return ruleFactory.createRule(file);
else
return ruleFactory.modifyRule(file);
} 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();
}
}
|
54,799 |
Bug 54799 NPE in QuickAssistLightBulbUpdater.hasQuickFixLightBulb(QuickAssistLightBulbUpdater
|
I200340310 + plug-in export Sorry no steps. I got a job error dialog plus this .log entry: !ENTRY org.eclipse.core.runtime 4 2 Mrz 15, 2004 12:04:41.328 !MESSAGE An internal error occurred during: "Java AST creation". !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.correction.QuickAssistLightBulbUpdater.hasQuickFixLightBulb(QuickAssistLightBulbUpdater.java:250) at org.eclipse.jdt.internal.ui.text.correction.QuickAssistLightBulbUpdater.doSelectionChanged(QuickAssistLightBulbUpdater.java:212) at org.eclipse.jdt.internal.ui.text.correction.QuickAssistLightBulbUpdater.access$0(QuickAssistLightBulbUpdater.java:201) at org.eclipse.jdt.internal.ui.text.correction.QuickAssistLightBulbUpdater$1.selectionChanged(QuickAssistLightBulbUpdater.java:128) at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:149) at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$1.run(SelectionListenerWithASTManager.java:99) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:62)
|
verified fixed
|
ad54b61
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-15T15:43:25Z | 2004-03-15T11:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickAssistLightBulbUpdater.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.Iterator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationAccessExtension;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationPresentation;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.java.IInvocationContext;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation;
import org.eclipse.jdt.internal.ui.javaeditor.JavaAnnotationIterator;
import org.eclipse.jdt.internal.ui.viewsupport.ISelectionListenerWithAST;
import org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager;
/**
*
*/
public class QuickAssistLightBulbUpdater {
public static class AssistAnnotation extends Annotation implements IAnnotationPresentation {
//XXX: To be fully correct this should be a non-static fields in QuickAssistLightBulbUpdater
private static final int LAYER;
static {
Annotation annotation= new Annotation("org.eclipse.jdt.ui.error", false, null); //$NON-NLS-1$
AnnotationPreference preference= EditorsUI.getAnnotationPreferenceLookup().getAnnotationPreference(annotation);
if (preference != null)
LAYER= preference.getPresentationLayer() + 1;
else
LAYER= IAnnotationAccessExtension.DEFAULT_LAYER + 1;
}
private Image fImage;
public AssistAnnotation() {
}
/*
* @see org.eclipse.jface.text.source.IAnnotationPresentation#getLayer()
*/
public int getLayer() {
return LAYER;
}
private Image getImage() {
if (fImage == null) {
fImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_QUICK_ASSIST);
}
return fImage;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.source.Annotation#paint(org.eclipse.swt.graphics.GC, org.eclipse.swt.widgets.Canvas, org.eclipse.swt.graphics.Rectangle)
*/
public void paint(GC gc, Canvas canvas, Rectangle r) {
drawImage(getImage(), gc, canvas, r, SWT.CENTER, SWT.TOP);
}
}
private final Annotation fAnnotation;
private boolean fIsAnnotationShown;
private IEditorPart fEditor;
private ITextViewer fViewer;
private ISelectionListenerWithAST fListener;
private IPropertyChangeListener fPropertyChangeListener;
public QuickAssistLightBulbUpdater(IEditorPart part, ITextViewer viewer) {
fEditor= part;
fViewer= viewer;
fAnnotation= new AssistAnnotation();
fIsAnnotationShown= false;
fPropertyChangeListener= null;
}
public boolean isSetInPreferences() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.APPEARANCE_QUICKASSIST_LIGHTBULB);
}
private void installSelectionListener() {
fListener= new ISelectionListenerWithAST() {
public void selectionChanged(IEditorPart part, ITextSelection selection, CompilationUnit astRoot) {
doSelectionChanged(selection.getOffset(), selection.getLength(), astRoot);
}
};
SelectionListenerWithASTManager.getDefault().addListener(fEditor, fListener);
}
private void uninstallSelectionListener() {
if (fListener != null) {
SelectionListenerWithASTManager.getDefault().removeListener(fEditor, fListener);
fListener= null;
}
IAnnotationModel model= getAnnotationModel();
if (model != null) {
removeLightBulb(model);
}
}
public void install() {
if (isSetInPreferences()) {
installSelectionListener();
}
if (fPropertyChangeListener == null) {
fPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
doPropertyChanged(event.getProperty());
}
};
PreferenceConstants.getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
}
}
public void uninstall() {
uninstallSelectionListener();
if (fPropertyChangeListener != null) {
PreferenceConstants.getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
}
protected void doPropertyChanged(String property) {
if (property.equals(PreferenceConstants.APPEARANCE_QUICKASSIST_LIGHTBULB)) {
if (isSetInPreferences()) {
ICompilationUnit cu= getCompilationUnit();
if (cu != null) {
installSelectionListener();
Point point= fViewer.getSelectedRange();
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
doSelectionChanged(point.x, point.y, astRoot);
}
} else {
uninstallSelectionListener();
}
}
}
private ICompilationUnit getCompilationUnit() {
IEditorInput input= fEditor.getEditorInput();
Object elem= input.getAdapter(IJavaElement.class);
if (elem instanceof ICompilationUnit) {
return (ICompilationUnit) elem;
}
return null;
}
private IAnnotationModel getAnnotationModel() {
return JavaUI.getDocumentProvider().getAnnotationModel(fEditor.getEditorInput());
}
private IDocument getDocument() {
return JavaUI.getDocumentProvider().getDocument(fEditor.getEditorInput());
}
private void doSelectionChanged(int offset, int length, CompilationUnit astRoot) {
final IAnnotationModel model= getAnnotationModel();
final ICompilationUnit cu= getCompilationUnit();
if (model == null || cu == null) {
return;
}
final AssistContext context= new AssistContext(cu, offset, length);
context.setASTRoot(astRoot);
boolean hasQuickFix= hasQuickFixLightBulb(model, context.getSelectionOffset());
if (hasQuickFix) {
removeLightBulb(model);
return; // there is already a quick fix light bulb at the new location
}
calculateLightBulb(model, context);
}
/*
* Needs to be called synchronized
*/
private void calculateLightBulb(IAnnotationModel model, IInvocationContext context) {
boolean needsAnnotation= JavaCorrectionProcessor.hasAssists(context);
if (fIsAnnotationShown) {
model.removeAnnotation(fAnnotation);
}
if (needsAnnotation) {
model.addAnnotation(fAnnotation, new Position(context.getSelectionOffset(), context.getSelectionLength()));
}
fIsAnnotationShown= needsAnnotation;
}
private void removeLightBulb(IAnnotationModel model) {
synchronized (this) {
if (fIsAnnotationShown) {
model.removeAnnotation(fAnnotation);
fIsAnnotationShown= false;
}
}
}
/*
* Tests if there is already a quick fix light bulb on the current line
*/
private boolean hasQuickFixLightBulb(IAnnotationModel model, int offset) {
try {
IDocument document= getDocument();
int currLine= document.getLineOfOffset(offset);
Iterator iter= new JavaAnnotationIterator(model, true);
while (iter.hasNext()) {
IJavaAnnotation annot= (IJavaAnnotation) iter.next();
Position pos= model.getPosition((Annotation) annot);
if (pos != null) {
int startLine= document.getLineOfOffset(pos.getOffset());
if (startLine == currLine && JavaCorrectionProcessor.hasCorrections(annot)) {
return true;
}
}
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return false;
}
}
|
54,806 |
Bug 54806 Change method signature table doesn't get updated on deletion
|
I200403100800 for the following File ------------------ class A { void method(int a, int b, int c, int d) { } } ---------------------------------- 1. Refactor->Change Method signature on the method 2. In the table that shows select rows 2 and 3 (b and c) and press Remove. 3. Press Add 4. Press Up 5. Press Up (observer nothing happens) 6. Press Up (observer nothing happens) 7. Press Up - It finally does what you expect it to. Steps 5 and 6 shouldn't happen!
|
resolved fixed
|
d3eaaa8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-15T19:39:32Z | 2004-03-15T14:13:20Z |
org.eclipse.jdt.ui/ui
| |
54,806 |
Bug 54806 Change method signature table doesn't get updated on deletion
|
I200403100800 for the following File ------------------ class A { void method(int a, int b, int c, int d) { } } ---------------------------------- 1. Refactor->Change Method signature on the method 2. In the table that shows select rows 2 and 3 (b and c) and press Remove. 3. Press Add 4. Press Up 5. Press Up (observer nothing happens) 6. Press Up (observer nothing happens) 7. Press Up - It finally does what you expect it to. Steps 5 and 6 shouldn't happen!
|
resolved fixed
|
d3eaaa8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-15T19:39:32Z | 2004-03-15T14:13:20Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeParametersControl.java
| |
54,717 |
Bug 54717 JUnit contextual launch must port to new XML Expr Language
|
Conextual Launch has migrated to use the new XML Expression Langauge for enablement logic. Unfortunately, the JUnit plugin.xml will need to be updated in order to support the Run context menu feature. A patch will be provided.
|
resolved fixed
|
759443c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-16T09:22:50Z | 2004-03-12T22:20:00Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/launcher/JUnitLaunchShortcut.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.junit.launcher;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.debug.ui.IDebugModelPresentation;
import org.eclipse.debug.ui.ILaunchFilter;
import org.eclipse.debug.ui.ILaunchShortcut;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.debug.ui.JavaUISourceLocator;
import org.eclipse.jdt.internal.junit.ui.JUnitMessages;
import org.eclipse.jdt.internal.junit.ui.JUnitPlugin;
import org.eclipse.jdt.internal.junit.util.TestSearchEngine;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
public class JUnitLaunchShortcut implements ILaunchShortcut, ILaunchFilter {
/**
* @see ILaunchShortcut#launch(IEditorPart, String)
*/
public void launch(IEditorPart editor, String mode) {
IJavaElement element= null;
IEditorInput input = editor.getEditorInput();
element = (IJavaElement) input.getAdapter(IJavaElement.class);
if (element != null) {
searchAndLaunch(new Object[] {element}, mode);
}
}
/**
* @see ILaunchShortcut#launch(ISelection, String)
*/
public void launch(ISelection selection, String mode) {
if (selection instanceof IStructuredSelection) {
searchAndLaunch(((IStructuredSelection)selection).toArray(), mode);
}
}
protected void searchAndLaunch(Object[] search, String mode) {
if (search != null) {
if (search.length == 0) {
MessageDialog.openInformation(getShell(), JUnitMessages.getString("LaunchTestAction.dialog.title"), JUnitMessages.getString("LaunchTestAction.message.notests")); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
if (search[0] instanceof IJavaElement) {
IJavaElement element= (IJavaElement)search[0];
if (element.getElementType() < IJavaElement.COMPILATION_UNIT) {
launchContainer(element, mode);
return;
}
if (element.getElementType() == IJavaElement.METHOD) {
launchMethod((IMethod)element, mode);
return;
}
}
// launch a CU or type
launchType(search, mode);
}
}
protected void launchType(Object[] search, String mode) {
IType[] types= null;
try {
types= TestSearchEngine.findTests(new ProgressMonitorDialog(getShell()), search);
} catch (InterruptedException e) {
JUnitPlugin.log(e);
return;
} catch (InvocationTargetException e) {
JUnitPlugin.log(e);
return;
}
IType type= null;
if (types.length == 0) {
MessageDialog.openInformation(getShell(), JUnitMessages.getString("LaunchTestAction.dialog.title"), JUnitMessages.getString("LaunchTestAction.message.notests")); //$NON-NLS-1$ //$NON-NLS-2$
} else if (types.length > 1) {
type= chooseType(types, mode);
} else {
type= types[0];
}
if (type != null) {
launch(type, mode);
}
}
private void launchContainer(IJavaElement container, String mode) {
String handleIdentifier= container.getHandleIdentifier();
ILaunchConfiguration config = findLaunchConfiguration(
mode,
container,
handleIdentifier,
"", //$NON-NLS-1$
"" //$NON-NLS-1$
);
if (config == null) {
config = createConfiguration(
container.getJavaProject(),
container.getElementName(),
"", //$NON-NLS-1$
handleIdentifier,
"" //$NON-NLS-1$
);
}
launchConfiguration(mode, config);
}
private void launch(IType type, String mode) {
String fullyQualifiedName= type.getFullyQualifiedName();
ILaunchConfiguration config = findLaunchConfiguration(
mode,
type,
"", //$NON-NLS-1$
fullyQualifiedName,
"" //$NON-NLS-1$
);
if (config == null) {
config= createConfiguration(
type.getJavaProject(),
type.getElementName(),
fullyQualifiedName,
"", //$NON-NLS-1$
"" //$NON-NLS-1$
);
}
launchConfiguration(mode, config);
}
private void launchMethod(IMethod method, String mode) {
IType declaringType= method.getDeclaringType();
String fullyQualifiedName= declaringType.getFullyQualifiedName();
ILaunchConfiguration config = findLaunchConfiguration(
mode,
method,
"", //$NON-NLS-1$
fullyQualifiedName,
method.getElementName()
);
if (config == null) {
config= createConfiguration(
method.getJavaProject(),
declaringType.getElementName()+"."+method.getElementName(), //$NON-NLS-1$
fullyQualifiedName,
"", //$NON-NLS-1$
method.getElementName()
);
}
launchConfiguration(mode, config);
}
protected void launchConfiguration(String mode, ILaunchConfiguration config) {
try {
if (config != null) {
DebugUITools.saveAndBuildBeforeLaunch();
config.launch(mode, null);
}
} catch (CoreException e) {
ErrorDialog.openError(getShell(), JUnitMessages.getString("LaunchTestAction.message.launchFailed"), e.getMessage(), e.getStatus()); //$NON-NLS-1$
}
}
/**
* Prompts the user to select a type
*
* @return the selected type or <code>null</code> if none.
*/
protected IType chooseType(IType[] types, String mode) {
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_POST_QUALIFIED));
dialog.setElements(types);
dialog.setTitle(JUnitMessages.getString("LaunchTestAction.dialog.title2")); //$NON-NLS-1$
if (mode.equals(ILaunchManager.DEBUG_MODE)) {
dialog.setMessage(JUnitMessages.getString("LaunchTestAction.message.selectTestToRun")); //$NON-NLS-1$
} else {
dialog.setMessage(JUnitMessages.getString("LaunchTestAction.message.selectTestToDebug")); //$NON-NLS-1$
}
dialog.setMultipleSelection(false);
if (dialog.open() == ElementListSelectionDialog.OK) {
return (IType)dialog.getFirstResult();
}
return null;
}
private ILaunchConfiguration findLaunchConfiguration(String mode, IJavaElement element, String container, String testClass, String testName) {
ILaunchConfigurationType configType= getJUnitLaunchConfigType();
List candidateConfigs= Collections.EMPTY_LIST;
try {
ILaunchConfiguration[] configs= getLaunchManager().getLaunchConfigurations(configType);
candidateConfigs= new ArrayList(configs.length);
for (int i= 0; i < configs.length; i++) {
ILaunchConfiguration config= configs[i];
if ((config.getAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, "").equals(container)) && //$NON-NLS-1$
(config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, "").equals(testClass)) && //$NON-NLS-1$
(config.getAttribute(JUnitBaseLaunchConfiguration.TESTNAME_ATTR,"").equals(testName)) && //$NON-NLS-1$
(config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, "").equals(element.getJavaProject().getElementName()))) { //$NON-NLS-1$
candidateConfigs.add(config);
}
}
} catch (CoreException e) {
JUnitPlugin.log(e);
}
// If there are no existing configs associated with the IType, create one.
// If there is exactly one config associated with the IType, return it.
// Otherwise, if there is more than one config associated with the IType, prompt the
// user to choose one.
int candidateCount= candidateConfigs.size();
if (candidateCount < 1) {
return null;
} else if (candidateCount == 1) {
return (ILaunchConfiguration) candidateConfigs.get(0);
} else {
// Prompt the user to choose a config. A null result means the user
// cancelled the dialog, in which case this method returns null,
// since cancelling the dialog should also cancel launching anything.
ILaunchConfiguration config= chooseConfiguration(candidateConfigs, mode);
if (config != null) {
return config;
}
}
return null;
}
/**
* Show a selection dialog that allows the user to choose one of the specified
* launch configurations. Return the chosen config, or <code>null</code> if the
* user cancelled the dialog.
*/
protected ILaunchConfiguration chooseConfiguration(List configList, String mode) {
IDebugModelPresentation labelProvider = DebugUITools.newDebugModelPresentation();
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), labelProvider);
dialog.setElements(configList.toArray());
dialog.setTitle(JUnitMessages.getString("LaunchTestAction.message.selectConfiguration")); //$NON-NLS-1$
if (mode.equals(ILaunchManager.DEBUG_MODE)) {
dialog.setMessage(JUnitMessages.getString("LaunchTestAction.message.selectDebugConfiguration")); //$NON-NLS-1$
} else {
dialog.setMessage(JUnitMessages.getString("LaunchTestAction.message.selectRunConfiguration")); //$NON-NLS-1$
}
dialog.setMultipleSelection(false);
int result= dialog.open();
labelProvider.dispose();
if (result == ElementListSelectionDialog.OK) {
return (ILaunchConfiguration)dialog.getFirstResult();
}
return null;
}
protected ILaunchConfiguration createConfiguration(
IJavaProject project, String name, String mainType,
String container, String testName) {
ILaunchConfiguration config= null;
try {
ILaunchConfigurationType configType= getJUnitLaunchConfigType();
ILaunchConfigurationWorkingCopy wc = configType.newInstance(null, getLaunchManager().generateUniqueLaunchConfigurationNameFrom(name));
wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, mainType);
wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, project.getElementName());
wc.setAttribute(ILaunchConfiguration.ATTR_SOURCE_LOCATOR_ID, JavaUISourceLocator.ID_PROMPTING_JAVA_SOURCE_LOCATOR);
wc.setAttribute(JUnitBaseLaunchConfiguration.ATTR_KEEPRUNNING, false);
wc.setAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, container);
if (testName.length() > 0)
wc.setAttribute(JUnitBaseLaunchConfiguration.TESTNAME_ATTR, testName);
config= wc.doSave();
} catch (CoreException ce) {
JUnitPlugin.log(ce);
}
return config;
}
/**
* Returns the local java launch config type
*/
protected ILaunchConfigurationType getJUnitLaunchConfigType() {
ILaunchManager lm= DebugPlugin.getDefault().getLaunchManager();
return lm.getLaunchConfigurationType(JUnitLaunchConfiguration.ID_JUNIT_APPLICATION);
}
protected ILaunchManager getLaunchManager() {
return DebugPlugin.getDefault().getLaunchManager();
}
/**
* Convenience method to get the window that owns this action's Shell.
*/
protected Shell getShell() {
return JUnitPlugin.getActiveWorkbenchShell();
}
public boolean testAttribute(IResource target, String name, String value) {
if ("ContextualLaunchActionFilter".equals(name)) { //$NON-NLS-1$
return isJUnitTest(target);
}
return false;
}
private boolean isJUnitTest(IResource target) {
if (target != null) {
IJavaElement element = JavaCore.create(target);
if (element instanceof ICompilationUnit) {
ICompilationUnit cu = (ICompilationUnit) element;
IType mainType= cu.getType(Signature.getQualifier(cu.getElementName()));
try {
return TestSearchEngine.isTestOrTestSuite(mainType);
} catch (JavaModelException e) {
return false;
}
}
}
return false;
}
}
|
54,717 |
Bug 54717 JUnit contextual launch must port to new XML Expr Language
|
Conextual Launch has migrated to use the new XML Expression Langauge for enablement logic. Unfortunately, the JUnit plugin.xml will need to be updated in order to support the Run context menu feature. A patch will be provided.
|
resolved fixed
|
759443c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-16T09:22:50Z | 2004-03-12T22:20:00Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/launcher/ResourceExtender.java
| |
54,992 |
Bug 54992 'Hide Local Types' button hides all types
|
I20040316 The 'Hide Local Types' button in the outline view/page hides all types of the compilation unit. Only the package declaration and the imports are displayed.
|
resolved fixed
|
33ad625
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-17T15:18:53Z | 2004-03-16T18:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/MemberFilter.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.viewsupport;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
/**
* Filter for the methods viewer.
* Changing a filter property does not trigger a refiltering of the viewer
*/
public class MemberFilter extends ViewerFilter {
public static final int FILTER_NONPUBLIC= 1;
public static final int FILTER_STATIC= 2;
public static final int FILTER_FIELDS= 4;
public static final int FILTER_LOCALTYPES= 8;
private int fFilterProperties;
/**
* Modifies filter and add a property to filter for
*/
public final void addFilter(int filter) {
fFilterProperties |= filter;
}
/**
* Modifies filter and remove a property to filter for
*/
public final void removeFilter(int filter) {
fFilterProperties &= (-1 ^ filter);
}
/**
* Tests if a property is filtered
*/
public final boolean hasFilter(int filter) {
return (fFilterProperties & filter) != 0;
}
/*
* @see ViewerFilter@isFilterProperty
*/
public boolean isFilterProperty(Object element, Object property) {
return false;
}
/*
* @see ViewerFilter@select
*/
public boolean select(Viewer viewer, Object parentElement, Object element) {
try {
if (element instanceof IMember) {
IMember member= (IMember) element;
int memberType= member.getElementType();
if (hasFilter(FILTER_FIELDS) && memberType == IJavaElement.FIELD) {
return false;
}
if (hasFilter(FILTER_LOCALTYPES) && memberType == IJavaElement.TYPE && !(member.getParent() instanceof IType)) {
return false;
}
if (member.getElementName().startsWith("<")) { // filter out <clinit> //$NON-NLS-1$
return false;
}
int flags= member.getFlags();
if (hasFilter(FILTER_STATIC) && (Flags.isStatic(flags) || isFieldInInterface(member)) && memberType != IJavaElement.TYPE) {
return false;
}
if (hasFilter(FILTER_NONPUBLIC) && !Flags.isPublic(flags) && !isMemberInInterface(member) && !isTopLevelType(member)) {
return false;
}
}
} catch (JavaModelException e) {
// ignore
}
return true;
}
private boolean isMemberInInterface(IMember member) throws JavaModelException {
IType parent= member.getDeclaringType();
return parent != null && parent.isInterface();
}
private boolean isFieldInInterface(IMember member) throws JavaModelException {
return (member.getElementType() == IJavaElement.FIELD) && member.getDeclaringType().isInterface();
}
private boolean isTopLevelType(IMember member) {
IType parent= member.getDeclaringType();
return parent == null;
}
}
|
51,566 |
Bug 51566 Quick Assist failure
|
Given this simple class: package whatever; public class ShowBroken extends Thread { ShowBroken() { name = getName(); } } Placing the cursor on the variable 'name'. Notice that quick assist only offers 'Local Rename' as an option. Changing the variable to 'foo' will convince quick assist to offer: Create local variable 'foo' Create field 'foo' Create parameter 'foo' Remove assignment Local Rename The variable 'name' is defined as a private member of Thread and should not be visible to class ShowBroken.
|
resolved fixed
|
57ac851
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-17T16:09:58Z | 2004-02-11T00:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ModifierCorrectionSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.Collection;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.ui.text.java.IInvocationContext;
import org.eclipse.jdt.ui.text.java.IProblemLocation;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
/**
*/
public class ModifierCorrectionSubProcessor {
public static final int TO_STATIC= 1;
public static final int TO_VISIBLE= 2;
public static final int TO_NON_PRIVATE= 3;
public static final int TO_NON_STATIC= 4;
public static final int TO_NON_FINAL= 5;
public static void addNonAccessibleMemberProposal(IInvocationContext context, IProblemLocation problem, Collection proposals, int kind, int relevance) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (selectedNode == null) {
return;
}
IBinding binding=null;
switch (selectedNode.getNodeType()) {
case ASTNode.SIMPLE_NAME:
binding= ((SimpleName) selectedNode).resolveBinding();
break;
case ASTNode.QUALIFIED_NAME:
binding= ((QualifiedName) selectedNode).resolveBinding();
break;
case ASTNode.SIMPLE_TYPE:
binding= ((SimpleType) selectedNode).resolveBinding();
break;
case ASTNode.METHOD_INVOCATION:
binding= ((MethodInvocation) selectedNode).getName().resolveBinding();
break;
case ASTNode.SUPER_METHOD_INVOCATION:
binding= ((SuperMethodInvocation) selectedNode).getName().resolveBinding();
break;
case ASTNode.FIELD_ACCESS:
binding= ((FieldAccess) selectedNode).getName().resolveBinding();
break;
case ASTNode.SUPER_FIELD_ACCESS:
binding= ((SuperFieldAccess) selectedNode).getName().resolveBinding();
break;
case ASTNode.CLASS_INSTANCE_CREATION:
binding= ((ClassInstanceCreation) selectedNode).resolveConstructorBinding();
break;
case ASTNode.SUPER_CONSTRUCTOR_INVOCATION:
binding= ((SuperConstructorInvocation) selectedNode).resolveConstructorBinding();
break;
default:
return;
}
ITypeBinding typeBinding= null;
String name;
boolean isLocalVar= false;
if (binding instanceof IMethodBinding) {
typeBinding= ((IMethodBinding) binding).getDeclaringClass();
name= binding.getName() + "()"; //$NON-NLS-1$
} else if (binding instanceof IVariableBinding) {
typeBinding= ((IVariableBinding) binding).getDeclaringClass();
name= binding.getName();
isLocalVar= !((IVariableBinding) binding).isField();
} else if (binding instanceof ITypeBinding) {
typeBinding= (ITypeBinding) binding;
name= binding.getName();
} else {
return;
}
if (typeBinding != null && typeBinding.isFromSource() || isLocalVar) {
int includedModifiers= 0;
int excludedModifiers= 0;
String label;
switch (kind) {
case TO_VISIBLE:
excludedModifiers= Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC;
includedModifiers= getNeededVisibility(selectedNode, typeBinding);
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changevisibility.description", new String[] { name, getVisibilityString(includedModifiers) }); //$NON-NLS-1$
break;
case TO_STATIC:
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertostatic.description", name); //$NON-NLS-1$
includedModifiers= Modifier.STATIC;
break;
case TO_NON_STATIC:
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertononstatic.description", name); //$NON-NLS-1$
excludedModifiers= Modifier.STATIC;
break;
case TO_NON_PRIVATE:
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertodefault.description", name); //$NON-NLS-1$
excludedModifiers= Modifier.PRIVATE;
break;
case TO_NON_FINAL:
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertononfinal.description", name); //$NON-NLS-1$
excludedModifiers= Modifier.FINAL;
break;
default:
return;
}
ICompilationUnit targetCU= isLocalVar ? cu : ASTResolving.findCompilationUnitForBinding(cu, context.getASTRoot(), typeBinding);
if (targetCU != null) {
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
proposals.add(new ModifierChangeCompletionProposal(label, targetCU, binding, selectedNode, includedModifiers, excludedModifiers, relevance, image));
}
if (kind == TO_VISIBLE && binding.getKind() == IBinding.VARIABLE && Modifier.isPrivate(binding.getModifiers())) {
if (selectedNode instanceof SimpleName || selectedNode instanceof FieldAccess && ((FieldAccess) selectedNode).getExpression() instanceof ThisExpression) {
UnresolvedElementsSubProcessor.getVariableProposals(context, problem, proposals);
}
}
}
}
public static void addOverridesFinalProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws JavaModelException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (!(selectedNode instanceof MethodDeclaration)) {
return;
}
IMethodBinding method= ((MethodDeclaration) selectedNode).resolveBinding();
ITypeBinding curr= method.getDeclaringClass();
IMethodBinding overridden= null;
while (overridden == null && curr.getSuperclass() != null) {
curr= curr.getSuperclass();
overridden= Bindings.findMethodInType(curr, method.getName(), method.getParameterTypes());
}
if (overridden == null) {
return;
}
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, context.getASTRoot(), curr);
if (targetCU != null) {
String methodName= curr.getName() + '.' + overridden.getName();
String label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemethodtononfinal.description", methodName); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
proposals.add(new ModifierChangeCompletionProposal(label, targetCU, overridden, selectedNode, 0, Modifier.FINAL, 9, image));
}
}
public static void addNonFinalLocalProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (!(selectedNode instanceof SimpleName)) {
return;
}
IBinding binding= ((SimpleName) selectedNode).resolveBinding();
if (binding instanceof IVariableBinding) {
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
String label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertofinal.description", binding.getName()); //$NON-NLS-1$
proposals.add(new ModifierChangeCompletionProposal(label, cu, binding, selectedNode, Modifier.FINAL, 0, 5, image));
}
}
private static String getVisibilityString(int code) {
if (Modifier.isPublic(code)) {
return "public"; //$NON-NLS-1$
}else if (Modifier.isProtected(code)) {
return "protected"; //$NON-NLS-1$
}
return "default"; //$NON-NLS-1$
}
private static int getNeededVisibility(ASTNode currNode, ITypeBinding targetType) {
ITypeBinding currNodeBinding= Bindings.getBindingOfParentType(currNode);
if (currNodeBinding == null) { // import
return Modifier.PUBLIC;
}
if (Bindings.isSuperType(targetType, currNodeBinding)) {
return Modifier.PROTECTED;
}
if (currNodeBinding.getPackage().getKey().equals(targetType.getPackage().getKey())) {
return 0;
}
return Modifier.PUBLIC;
}
public static void addAbstractMethodProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(astRoot);
if (selectedNode == null) {
return;
}
MethodDeclaration decl;
if (selectedNode instanceof SimpleName) {
decl= (MethodDeclaration) selectedNode.getParent();
} else if (selectedNode instanceof MethodDeclaration) {
decl= (MethodDeclaration) selectedNode;
} else {
return;
}
ASTNode parentType= ASTResolving.findParentType(decl);
TypeDeclaration parentTypeDecl= null;
boolean parentIsAbstractClass= false;
if (parentType instanceof TypeDeclaration) {
parentTypeDecl= (TypeDeclaration) parentType;
parentIsAbstractClass= !parentTypeDecl.isInterface() && Modifier.isAbstract(parentTypeDecl.getModifiers());
}
boolean hasNoBody= (decl.getBody() == null);
if (problem.getProblemId() == IProblem.AbstractMethodInAbstractClass || parentIsAbstractClass) {
ASTRewrite rewrite= new ASTRewrite(decl.getParent());
AST ast= astRoot.getAST();
int newModifiers= decl.getModifiers() & ~Modifier.ABSTRACT;
rewrite.set(decl, MethodDeclaration.MODIFIERS_PROPERTY, new Integer(newModifiers), null);
if (hasNoBody) {
Block newBody= ast.newBlock();
rewrite.set(decl, MethodDeclaration.BODY_PROPERTY, newBody, null);
Expression expr= ASTNodeFactory.newDefaultExpression(ast, decl.getReturnType(), decl.getExtraDimensions());
if (expr != null) {
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(expr);
newBody.statements().add(returnStatement);
}
}
String label= CorrectionMessages.getString("ModifierCorrectionSubProcessor.removeabstract.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
if (!hasNoBody && problem.getProblemId() == IProblem.BodyForAbstractMethod) {
ASTRewrite rewrite= new ASTRewrite(decl.getParent());
rewrite.markAsRemoved(decl.getBody(), null);
String label= CorrectionMessages.getString("ModifierCorrectionSubProcessor.removebody.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal2= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image);
proposal2.ensureNoModifications();
proposals.add(proposal2);
}
if (problem.getProblemId() == IProblem.AbstractMethodInAbstractClass && (parentTypeDecl != null)) {
ASTRewriteCorrectionProposal proposal= getMakeTypeAbstractProposal(cu, parentTypeDecl, 5);
proposals.add(proposal);
}
}
public static void addNativeMethodProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(astRoot);
if (selectedNode == null) {
return;
}
MethodDeclaration decl;
if (selectedNode instanceof SimpleName) {
decl= (MethodDeclaration) selectedNode.getParent();
} else if (selectedNode instanceof MethodDeclaration) {
decl= (MethodDeclaration) selectedNode;
} else {
return;
}
{
ASTRewrite rewrite= new ASTRewrite(decl.getParent());
AST ast= astRoot.getAST();
int newModifiers= decl.getModifiers() & ~Modifier.NATIVE;
rewrite.set(decl, MethodDeclaration.MODIFIERS_PROPERTY, new Integer(newModifiers), null);
Block newBody= ast.newBlock();
rewrite.set(decl, MethodDeclaration.BODY_PROPERTY, newBody, null);
Expression expr= ASTNodeFactory.newDefaultExpression(ast, decl.getReturnType(), decl.getExtraDimensions());
if (expr != null) {
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(expr);
newBody.statements().add(returnStatement);
}
String label= CorrectionMessages.getString("ModifierCorrectionSubProcessor.removenative.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
if (decl.getBody() != null) {
ASTRewrite rewrite= new ASTRewrite(decl.getParent());
rewrite.markAsRemoved(decl.getBody(), null);
String label= CorrectionMessages.getString("ModifierCorrectionSubProcessor.removebody.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal2= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image);
proposal2.ensureNoModifications();
proposals.add(proposal2);
}
}
public static ASTRewriteCorrectionProposal getMakeTypeAbstractProposal(ICompilationUnit cu, TypeDeclaration typeDeclaration, int relevance) throws CoreException {
ASTRewrite rewrite= new ASTRewrite(typeDeclaration.getParent());
int newModifiers= typeDeclaration.getModifiers() | Modifier.ABSTRACT;
rewrite.set(typeDeclaration, TypeDeclaration.MODIFIERS_PROPERTY, new Integer(newModifiers), null);
String label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.addabstract.description", typeDeclaration.getName().getIdentifier()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, relevance, image);
proposal.ensureNoModifications();
return proposal;
}
public static void addMethodRequiresBodyProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
AST ast= context.getASTRoot().getAST();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (!(selectedNode instanceof MethodDeclaration)) {
return;
}
MethodDeclaration decl= (MethodDeclaration) selectedNode;
{
ASTRewrite rewrite= new ASTRewrite(decl);
int newModifiers= decl.getModifiers() & ~Modifier.ABSTRACT;
rewrite.set(decl, MethodDeclaration.MODIFIERS_PROPERTY, new Integer(newModifiers), null);
Block body= ast.newBlock();
rewrite.set(decl, MethodDeclaration.BODY_PROPERTY, body, null);
Type returnType= decl.getReturnType();
if (!decl.isConstructor()) {
Expression expression= ASTNodeFactory.newDefaultExpression(ast, returnType, decl.getExtraDimensions());
if (expression != null) {
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(expression);
body.statements().add(returnStatement);
}
}
String label= CorrectionMessages.getString("ModifierCorrectionSubProcessor.addmissingbody.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 9, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
{
ASTRewrite rewrite= new ASTRewrite(decl);
int newModifiers= decl.getModifiers() | Modifier.ABSTRACT;
rewrite.set(decl, MethodDeclaration.MODIFIERS_PROPERTY, new Integer(newModifiers), null);
String label= CorrectionMessages.getString("ModifierCorrectionSubProcessor.setmethodabstract.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 8, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
public static void addNeedToEmulateProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (!(selectedNode instanceof SimpleName)) {
return;
}
IBinding binding= ((SimpleName) selectedNode).resolveBinding();
if (binding instanceof IVariableBinding) {
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
String label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertofinal.description", binding.getName()); //$NON-NLS-1$
proposals.add(new ModifierChangeCompletionProposal(label, cu, binding, selectedNode, Modifier.FINAL, 0, 5, image));
}
}
}
|
47,016 |
Bug 47016 JDT new wizards do not follow schema [code manipulation]
|
20031119 The JDT new wizards all have an extra tag "javatype" which does not follow the schema from org.eclipse.ui.newWizards. If this is useful to you we should consider adding an "args" tag to the new wizards for general use.
|
resolved fixed
|
aa7b8f1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-18T10:39:21Z | 2003-11-19T19:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewTypeDropDownAction.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.util.ArrayList;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuCreator;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowPulldownDelegate2;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.internal.IWorkbenchConstants;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
public class NewTypeDropDownAction extends Action implements IMenuCreator, IWorkbenchWindowPulldownDelegate2 {
private final static String TAG_WIZARD = "wizard";//$NON-NLS-1$
private final static String ATT_JAVATYPE = "javatype";//$NON-NLS-1$
private Menu fMenu;
public NewTypeDropDownAction() {
fMenu= null;
setMenuCreator(this);
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.OPEN_CLASS_WIZARD_ACTION);
}
public void dispose() {
if (fMenu != null) {
fMenu.dispose();
fMenu= null;
}
}
public Menu getMenu(Menu parent) {
return null;
}
public Menu getMenu(Control parent) {
if (fMenu == null) {
fMenu= new Menu(parent);
Action[] actions= getActionFromDescriptors();
for (int i= 0; i < actions.length; i++) {
ActionContributionItem item= new ActionContributionItem(actions[i]);
item.fill(fMenu, -1);
}
}
return fMenu;
}
public void run() {
(new OpenClassWizardAction()).run();
}
public static Action[] getActionFromDescriptors() {
ArrayList containers= new ArrayList();
IExtensionPoint extensionPoint = Platform.getPluginRegistry().getExtensionPoint(PlatformUI.PLUGIN_ID, IWorkbenchConstants.PL_NEW);
if (extensionPoint != null) {
IConfigurationElement[] elements = extensionPoint.getConfigurationElements();
for (int i = 0; i < elements.length; i++) {
IConfigurationElement element= elements[i];
if (element.getName().equals(TAG_WIZARD)) {
if ("true".equals(element.getAttribute(ATT_JAVATYPE))) { //$NON-NLS-1$
containers.add(new OpenTypeWizardAction(element));
}
}
}
}
return (Action[]) containers.toArray(new Action[containers.size()]);
}
/* (non-Javadoc)
* @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow)
*/
public void init(IWorkbenchWindow window) {
}
/* (non-Javadoc)
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
public void run(IAction action) {
run();
}
/* (non-Javadoc)
* @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
}
}
|
37,763 |
Bug 37763 Reorg: doesn't support to move an internal JAR [refactoring] [ccp] [dnd]
|
It should be possible to move an internal JAR to another project and have the build class path updated. feedback from thoughtworks: I couldn't find a simple way to move a jar file and have the build path automatically correct itself. I ended up moving it in the resource perspective and then manually editing the classpath file
|
resolved fixed
|
a9ae01a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-18T20:09:39Z | 2003-05-16T13:00:00Z |
org.eclipse.jdt.ui/core
| |
37,763 |
Bug 37763 Reorg: doesn't support to move an internal JAR [refactoring] [ccp] [dnd]
|
It should be possible to move an internal JAR to another project and have the build class path updated. feedback from thoughtworks: I couldn't find a simple way to move a jar file and have the build path automatically correct itself. I ended up moving it in the resource perspective and then manually editing the classpath file
|
resolved fixed
|
a9ae01a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-18T20:09:39Z | 2003-05-16T13:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/changes/PackageFragmentRootReorgChange.java
| |
37,763 |
Bug 37763 Reorg: doesn't support to move an internal JAR [refactoring] [ccp] [dnd]
|
It should be possible to move an internal JAR to another project and have the build class path updated. feedback from thoughtworks: I couldn't find a simple way to move a jar file and have the build path automatically correct itself. I ended up moving it in the resource perspective and then manually editing the classpath file
|
resolved fixed
|
a9ae01a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-18T20:09:39Z | 2003-05-16T13:00:00Z |
org.eclipse.jdt.ui/core
| |
37,763 |
Bug 37763 Reorg: doesn't support to move an internal JAR [refactoring] [ccp] [dnd]
|
It should be possible to move an internal JAR to another project and have the build class path updated. feedback from thoughtworks: I couldn't find a simple way to move a jar file and have the build path automatically correct itself. I ended up moving it in the resource perspective and then manually editing the classpath file
|
resolved fixed
|
a9ae01a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-18T20:09:39Z | 2003-05-16T13:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/ReorgPolicyFactory.java
| |
37,763 |
Bug 37763 Reorg: doesn't support to move an internal JAR [refactoring] [ccp] [dnd]
|
It should be possible to move an internal JAR to another project and have the build class path updated. feedback from thoughtworks: I couldn't find a simple way to move a jar file and have the build path automatically correct itself. I ended up moving it in the resource perspective and then manually editing the classpath file
|
resolved fixed
|
a9ae01a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-18T20:09:39Z | 2003-05-16T13:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/SelectionTransferDragAdapter.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.Iterator;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.internal.ui.dnd.BasicSelectionTransferDragAdapter;
public class SelectionTransferDragAdapter extends BasicSelectionTransferDragAdapter {
public SelectionTransferDragAdapter(ISelectionProvider provider) {
super(provider);
}
protected boolean isDragable(ISelection selection) {
if (selection instanceof IStructuredSelection) {
for (Iterator iter= ((IStructuredSelection)selection).iterator(); iter.hasNext();) {
Object element= iter.next();
if (element instanceof IJavaElement) {
IPackageFragmentRoot root= (IPackageFragmentRoot)((IJavaElement)element).getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
if (root != null && root.isArchive())
return false;
}
}
return true;
}
return false;
}
}
|
47,798 |
Bug 47798 convert local variable to field gives erroneous error [refactoring]
|
perform the "convert local variable to field" refactoring on the variable x and select "initialize in field declaration" and the "make final" options on the text below: --------------------------------------------------- public class Test { public static void method2(final int i) { final I x = new I()//<-- refactor->convert local variable x to field { public void methodI() { int y = 3; } }; } } interface I { void methodI(); } ---------------------------------------------------------------- gives the error message: Cannot promote this local variable to a field because it uses types or variables declared locally in this method. Which is clearly wrong!
|
resolved fixed
|
497e282
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-18T21:36:17Z | 2003-12-01T14:46:40Z |
org.eclipse.jdt.ui.tests.refactoring/resources/PromoteTempToField/canPromote/A_test21_in.java
| |
47,798 |
Bug 47798 convert local variable to field gives erroneous error [refactoring]
|
perform the "convert local variable to field" refactoring on the variable x and select "initialize in field declaration" and the "make final" options on the text below: --------------------------------------------------- public class Test { public static void method2(final int i) { final I x = new I()//<-- refactor->convert local variable x to field { public void methodI() { int y = 3; } }; } } interface I { void methodI(); } ---------------------------------------------------------------- gives the error message: Cannot promote this local variable to a field because it uses types or variables declared locally in this method. Which is clearly wrong!
|
resolved fixed
|
497e282
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-18T21:36:17Z | 2003-12-01T14:46:40Z |
org.eclipse.jdt.ui.tests.refactoring/resources/PromoteTempToField/canPromote/A_test21_out.java
| |
47,798 |
Bug 47798 convert local variable to field gives erroneous error [refactoring]
|
perform the "convert local variable to field" refactoring on the variable x and select "initialize in field declaration" and the "make final" options on the text below: --------------------------------------------------- public class Test { public static void method2(final int i) { final I x = new I()//<-- refactor->convert local variable x to field { public void methodI() { int y = 3; } }; } } interface I { void methodI(); } ---------------------------------------------------------------- gives the error message: Cannot promote this local variable to a field because it uses types or variables declared locally in this method. Which is clearly wrong!
|
resolved fixed
|
497e282
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-18T21:36:17Z | 2003-12-01T14:46:40Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
47,798 |
Bug 47798 convert local variable to field gives erroneous error [refactoring]
|
perform the "convert local variable to field" refactoring on the variable x and select "initialize in field declaration" and the "make final" options on the text below: --------------------------------------------------- public class Test { public static void method2(final int i) { final I x = new I()//<-- refactor->convert local variable x to field { public void methodI() { int y = 3; } }; } } interface I { void methodI(); } ---------------------------------------------------------------- gives the error message: Cannot promote this local variable to a field because it uses types or variables declared locally in this method. Which is clearly wrong!
|
resolved fixed
|
497e282
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-18T21:36:17Z | 2003-12-01T14:46:40Z |
cases/org/eclipse/jdt/ui/tests/refactoring/PromoteTempToFieldTests.java
| |
47,798 |
Bug 47798 convert local variable to field gives erroneous error [refactoring]
|
perform the "convert local variable to field" refactoring on the variable x and select "initialize in field declaration" and the "make final" options on the text below: --------------------------------------------------- public class Test { public static void method2(final int i) { final I x = new I()//<-- refactor->convert local variable x to field { public void methodI() { int y = 3; } }; } } interface I { void methodI(); } ---------------------------------------------------------------- gives the error message: Cannot promote this local variable to a field because it uses types or variables declared locally in this method. Which is clearly wrong!
|
resolved fixed
|
497e282
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-18T21:36:17Z | 2003-12-01T14:46:40Z |
org.eclipse.jdt.ui/core
| |
47,798 |
Bug 47798 convert local variable to field gives erroneous error [refactoring]
|
perform the "convert local variable to field" refactoring on the variable x and select "initialize in field declaration" and the "make final" options on the text below: --------------------------------------------------- public class Test { public static void method2(final int i) { final I x = new I()//<-- refactor->convert local variable x to field { public void methodI() { int y = 3; } }; } } interface I { void methodI(); } ---------------------------------------------------------------- gives the error message: Cannot promote this local variable to a field because it uses types or variables declared locally in this method. Which is clearly wrong!
|
resolved fixed
|
497e282
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-18T21:36:17Z | 2003-12-01T14:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/PromoteTempToFieldRefactoring.java
| |
55,340 |
Bug 55340 Documentation (Javadoc) location selector does not show up with ZIP files
|
When having a ZIP (not JAR) file included as library there can no documentation location be selected on its properties page. When I rename the file to "*.jar" then it works.
|
resolved fixed
|
0977368
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-19T10:50:50Z | 2004-03-19T09:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavadocConfigurationPropertyPage.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.net.URL;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.ui.dialogs.PropertyPage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IJavaElement;
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.ui.JavaUI;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.ArchiveFileFilter;
/**
* Property page used to set the project's Javadoc location for sources
*/
public class JavadocConfigurationPropertyPage extends PropertyPage implements IStatusChangeListener {
private JavadocConfigurationBlock fJavadocConfigurationBlock;
public JavadocConfigurationPropertyPage() {
}
/**
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
*/
public void createControl(Composite parent) {
IJavaElement elem= getJavaElement();
if (elem instanceof IPackageFragmentRoot)
setDescription(PreferencesMessages.getString("JavadocConfigurationPropertyPage.IsPackageFragmentRoot.description")); //$NON-NLS-1$
else if (elem instanceof IJavaProject)
setDescription(PreferencesMessages.getString("JavadocConfigurationPropertyPage.IsJavaProject.description")); //$NON-NLS-1$
else
setDescription(PreferencesMessages.getString("JavadocConfigurationPropertyPage.IsIncorrectElement.description")); //$NON-NLS-1$
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.JAVADOC_CONFIGURATION_PROPERTY_PAGE);
}
/*
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
IJavaElement elem= getJavaElement();
URL initialLocation= null;
if (elem != null) {
try {
initialLocation= JavaUI.getJavadocBaseLocation(elem);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
boolean isProject= (elem instanceof IJavaProject);
fJavadocConfigurationBlock= new JavadocConfigurationBlock(getShell(), this, initialLocation, isProject);
Control control= fJavadocConfigurationBlock.createContents(parent);
control.setVisible(elem != null);
Dialog.applyDialogFont(control);
return control;
}
private IJavaElement getJavaElement() {
IAdaptable adaptable= getElement();
IJavaElement elem= (IJavaElement) adaptable.getAdapter(IJavaElement.class);
if (elem == null) {
IResource resource= (IResource) adaptable.getAdapter(IResource.class);
//special case when the .jar is a file
try {
if (resource instanceof IFile && ArchiveFileFilter.isArchivePath(resource.getFullPath())) {
IProject proj= resource.getProject();
if (proj.hasNature(JavaCore.NATURE_ID)) {
IJavaProject jproject= JavaCore.create(proj);
elem= jproject.getPackageFragmentRoot(resource); // create a handle
}
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
return elem;
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
fJavadocConfigurationBlock.performDefaults();
super.performDefaults();
}
/**
* @see org.eclipse.jface.preference.IPreferencePage#performOk()
*/
public boolean performOk() {
URL javadocLocation= fJavadocConfigurationBlock.getJavadocLocation();
IJavaElement elem= getJavaElement();
if (elem instanceof IJavaProject) {
JavaUI.setProjectJavadocLocation((IJavaProject) elem, javadocLocation);
} else if (elem instanceof IPackageFragmentRoot) {
JavaUI.setLibraryJavadocLocation(elem.getPath(), javadocLocation);
}
return true;
}
/**
* @see IStatusChangeListener#statusChanged(IStatus)
*/
public void statusChanged(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
}
|
54,787 |
Bug 54787 Classpath Variable preference page not updated
|
Our plugins have their own set of preference pages. If someone press the apply button, some settings are performed and some Java classpath variables are set/updated. If someone has opened (instanciated) the Java classpath variable preference page before, then modified our page, then pressed apply, and then reselect it, its internal model is not updated. It still contains the old classpath variables. The Platform's path variable has excactly the same problem. I have to close and reopen the preferences dialog to see the new values.
|
resolved fixed
|
0a4a67a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-19T11:18:09Z | 2004-03-15T05:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ClasspathVariablesPreferencePage.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 org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.VariableBlock;
public class ClasspathVariablesPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
public static final String ID= "org.eclipse.jdt.ui.preferences.ClasspathVariablesPreferencePage"; //$NON-NLS-1$
private VariableBlock fVariableBlock;
/**
* Constructor for ClasspathVariablesPreferencePage
*/
public ClasspathVariablesPreferencePage() {
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
fVariableBlock= new VariableBlock(true, null);
// title only used when page is shown programatically
setTitle(PreferencesMessages.getString("ClasspathVariablesPreferencePage.title")); //$NON-NLS-1$
setDescription(PreferencesMessages.getString("ClasspathVariablesPreferencePage.description")); //$NON-NLS-1$
noDefaultAndApplyButton();
}
/*
* (non-Javadoc)
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
*/
public void createControl(Composite parent) {
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.CP_VARIABLES_PREFERENCE_PAGE);
}
/*
* @see PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
*/
protected Control createContents(Composite parent) {
Control result= fVariableBlock.createContents(parent);
Dialog.applyDialogFont(result);
return result;
}
/*
* @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
*/
public void init(IWorkbench workbench) {
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
fVariableBlock.performDefaults();
super.performDefaults();
}
/*
* @see PreferencePage#performOk()
*/
public boolean performOk() {
JavaPlugin.getDefault().savePluginPreferences();
return fVariableBlock.performOk();
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
*/
public void setVisible(boolean visible) {
if (visible) {
fVariableBlock.refresh();
}
super.setVisible(visible);
}
}
|
54,787 |
Bug 54787 Classpath Variable preference page not updated
|
Our plugins have their own set of preference pages. If someone press the apply button, some settings are performed and some Java classpath variables are set/updated. If someone has opened (instanciated) the Java classpath variable preference page before, then modified our page, then pressed apply, and then reselect it, its internal model is not updated. It still contains the old classpath variables. The Platform's path variable has excactly the same problem. I have to close and reopen the preferences dialog to see the new values.
|
resolved fixed
|
0a4a67a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-19T11:18:09Z | 2004-03-15T05:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/VariableBlock.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.eclipse.core.resources.IncrementalProjectBuilder;
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.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jface.window.Window;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
public class VariableBlock {
private ListDialogField fVariablesList;
private Control fControl;
private List fSelectedElements;
private boolean fAskToBuild;
private boolean fInPreferencePage;
/**
* Constructor for VariableBlock
*/
public VariableBlock(boolean inPreferencePage, String initSelection) {
fSelectedElements= new ArrayList(0);
fInPreferencePage= inPreferencePage;
fAskToBuild= true;
String[] buttonLabels= new String[] {
/* 0 */ NewWizardMessages.getString("VariableBlock.vars.add.button"), //$NON-NLS-1$
/* 1 */ NewWizardMessages.getString("VariableBlock.vars.edit.button"), //$NON-NLS-1$
/* 2 */ NewWizardMessages.getString("VariableBlock.vars.remove.button") //$NON-NLS-1$
};
VariablesAdapter adapter= new VariablesAdapter();
CPVariableElementLabelProvider labelProvider= new CPVariableElementLabelProvider(!inPreferencePage);
fVariablesList= new ListDialogField(adapter, buttonLabels, labelProvider);
fVariablesList.setDialogFieldListener(adapter);
fVariablesList.setLabelText(NewWizardMessages.getString("VariableBlock.vars.label")); //$NON-NLS-1$
fVariablesList.setRemoveButtonIndex(2);
fVariablesList.enableButton(1, false);
fVariablesList.setViewerSorter(new ViewerSorter() {
public int compare(Viewer viewer, Object e1, Object e2) {
if (e1 instanceof CPVariableElement && e2 instanceof CPVariableElement) {
return ((CPVariableElement)e1).getName().compareTo(((CPVariableElement)e2).getName());
}
return super.compare(viewer, e1, e2);
}
});
CPVariableElement initSelectedElement= null;
String[] reservedName= getReservedVariableNames();
ArrayList reserved= new ArrayList(reservedName.length);
addAll(reservedName, reserved);
String[] entries= JavaCore.getClasspathVariableNames();
ArrayList elements= new ArrayList(entries.length);
for (int i= 0; i < entries.length; i++) {
String name= entries[i];
CPVariableElement elem;
IPath entryPath= JavaCore.getClasspathVariable(name);
if (entryPath != null) {
elem= new CPVariableElement(name, entryPath, reserved.contains(name));
elements.add(elem);
if (name.equals(initSelection)) {
initSelectedElement= elem;
}
} else {
JavaPlugin.logErrorMessage("VariableBlock: Classpath variable with null value: " + name); //$NON-NLS-1$
}
}
fVariablesList.setElements(elements);
if (initSelectedElement != null) {
ISelection sel= new StructuredSelection(initSelectedElement);
fVariablesList.selectElements(sel);
} else {
fVariablesList.selectFirstElement();
}
}
private String[] getReservedVariableNames() {
return new String[] {
JavaRuntime.JRELIB_VARIABLE,
JavaRuntime.JRESRC_VARIABLE,
JavaRuntime.JRESRCROOT_VARIABLE,
};
}
public Control createContents(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
LayoutUtil.doDefaultLayout(composite, new DialogField[] { fVariablesList }, true, 0, 0);
LayoutUtil.setHorizontalGrabbing(fVariablesList.getListControl(null));
fControl= composite;
return composite;
}
public void addDoubleClickListener(IDoubleClickListener listener) {
fVariablesList.getTableViewer().addDoubleClickListener(listener);
}
public void addSelectionChangedListener(ISelectionChangedListener listener) {
fVariablesList.getTableViewer().addSelectionChangedListener(listener);
}
private Shell getShell() {
if (fControl != null) {
return fControl.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
private class VariablesAdapter implements IDialogFieldListener, IListAdapter {
// -------- IListAdapter --------
public void customButtonPressed(ListDialogField field, int index) {
switch (index) {
case 0: /* add */
editEntries(null);
break;
case 1: /* edit */
List selected= field.getSelectedElements();
editEntries((CPVariableElement)selected.get(0));
break;
}
}
public void selectionChanged(ListDialogField field) {
doSelectionChanged(field);
}
public void doubleClicked(ListDialogField field) {
if (fInPreferencePage) {
List selected= field.getSelectedElements();
if (canEdit(selected, containsReserved(selected))) {
editEntries((CPVariableElement) selected.get(0));
}
}
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
}
}
private boolean containsReserved(List selected) {
for (int i= selected.size()-1; i >= 0; i--) {
if (((CPVariableElement)selected.get(i)).isReserved()) {
return true;
}
}
return false;
}
private static void addAll(Object[] objs, Collection dest) {
for (int i= 0; i < objs.length; i++) {
dest.add(objs[i]);
}
}
private boolean canEdit(List selected, boolean containsReserved) {
return selected.size() == 1 && !containsReserved;
}
private void doSelectionChanged(DialogField field) {
List selected= fVariablesList.getSelectedElements();
boolean containsReserved= containsReserved(selected);
// edit
fVariablesList.enableButton(1, canEdit(selected, containsReserved));
// remove button
fVariablesList.enableButton(2, !containsReserved);
fSelectedElements= selected;
}
private void editEntries(CPVariableElement entry) {
List existingEntries= fVariablesList.getElements();
VariableCreationDialog dialog= new VariableCreationDialog(getShell(), entry, existingEntries);
if (dialog.open() != Window.OK) {
return;
}
CPVariableElement newEntry= dialog.getClasspathElement();
if (entry == null) {
fVariablesList.addElement(newEntry);
entry= newEntry;
} else {
entry.setName(newEntry.getName());
entry.setPath(newEntry.getPath());
fVariablesList.refresh();
}
fVariablesList.selectElements(new StructuredSelection(entry));
}
public List getSelectedElements() {
return fSelectedElements;
}
public void performDefaults() {
fVariablesList.removeAllElements();
String[] reservedName= getReservedVariableNames();
for (int i= 0; i < reservedName.length; i++) {
CPVariableElement elem= new CPVariableElement(reservedName[i], Path.EMPTY, true);
elem.setReserved(true);
fVariablesList.addElement(elem);
}
}
public boolean performOk() {
ArrayList removedVariables= new ArrayList();
ArrayList changedVariables= new ArrayList();
removedVariables.addAll(Arrays.asList(JavaCore.getClasspathVariableNames()));
// remove all unchanged
List changedElements= fVariablesList.getElements();
for (int i= changedElements.size()-1; i >= 0; i--) {
CPVariableElement curr= (CPVariableElement) changedElements.get(i);
if (curr.isReserved()) {
changedElements.remove(curr);
} else {
IPath path= curr.getPath();
IPath prevPath= JavaCore.getClasspathVariable(curr.getName());
if (prevPath != null && prevPath.equals(path)) {
changedElements.remove(curr);
} else {
changedVariables.add(curr.getName());
}
}
removedVariables.remove(curr.getName());
}
int steps= changedElements.size() + removedVariables.size();
if (steps > 0) {
boolean needsBuild= false;
if (fAskToBuild && doesChangeRequireFullBuild(removedVariables, changedVariables)) {
String title= NewWizardMessages.getString("VariableBlock.needsbuild.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("VariableBlock.needsbuild.message"); //$NON-NLS-1$
MessageDialog buildDialog= new MessageDialog(getShell(), title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2);
int res= buildDialog.open();
if (res != 0 && res != 1) {
return false;
}
needsBuild= (res == 0);
}
IRunnableWithProgress runnable= new VariableBlockRunnable(removedVariables, changedElements, needsBuild);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(true, true, runnable);
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), NewWizardMessages.getString("VariableBlock.operation_errror.title"), NewWizardMessages.getString("VariableBlock.operation_errror.message")); //$NON-NLS-1$ //$NON-NLS-2$
return false;
} catch (InterruptedException e) {
return true;
}
}
return true;
}
private boolean doesChangeRequireFullBuild(List removed, List changed) {
try {
IJavaModel model= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
IJavaProject[] projects= model.getJavaProjects();
for (int i= 0; i < projects.length; i++) {
IClasspathEntry[] entries= projects[i].getRawClasspath();
for (int k= 0; k < entries.length; k++) {
IClasspathEntry curr= entries[k];
if (curr.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
String var= curr.getPath().segment(0);
if (removed.contains(var) || changed.contains(var)) {
return true;
}
}
}
}
} catch (JavaModelException e) {
return true;
}
return false;
}
private class VariableBlockRunnable implements IRunnableWithProgress {
private List fToRemove;
private List fToChange;
private boolean fDoBuild;
public VariableBlockRunnable(List toRemove, List toChange, boolean doBuild) {
fToRemove= toRemove;
fToChange= toChange;
fDoBuild= doBuild;
}
/*
* @see IRunnableWithProgress#run(IProgressMonitor)
*/
public void run(IProgressMonitor monitor) throws InvocationTargetException {
monitor.beginTask(NewWizardMessages.getString("VariableBlock.operation_desc"), fDoBuild ? 2 : 1); //$NON-NLS-1$
try {
int nVariables= fToChange.size() + fToRemove.size();
String[] names= new String[nVariables];
IPath[] paths= new IPath[nVariables];
int k= 0;
for (int i= 0; i < fToChange.size(); i++) {
CPVariableElement curr= (CPVariableElement) fToChange.get(i);
names[k]= curr.getName();
paths[k]= curr.getPath();
k++;
}
for (int i= 0; i < fToRemove.size(); i++) {
names[k]= (String) fToRemove.get(i);
paths[k]= null;
k++;
}
JavaCore.setClasspathVariables(names, paths, new SubProgressMonitor(monitor, 1));
if (fDoBuild) {
JavaPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, new SubProgressMonitor(monitor, 1));
}
} catch (CoreException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
}
/**
* If set to true, a dialog will ask the user to build on variable changed
* @param askToBuild The askToBuild to set
*/
public void setAskToBuild(boolean askToBuild) {
fAskToBuild= askToBuild;
}
/**
*
*/
public void refresh() {
int nElements= fVariablesList.getSize();
for (int i= 0; i < nElements; i++) {
CPVariableElement curr= (CPVariableElement) fVariablesList.getElement(i);
IPath entryPath= JavaCore.getClasspathVariable(curr.getName());
if (entryPath != null) {
curr.setPath(entryPath);
} else {
curr.setPath(Path.EMPTY);
}
}
fVariablesList.refresh();
}
}
|
20,446 |
Bug 20446 cannot create protected or private interfaces [code manipulation]
|
F3 the spec allows creating protected or private nested interfaces but eclipse disallows it (the new interface wizard)
|
resolved fixed
|
73204b2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-19T11:51:37Z | 2002-06-17T13:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.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.wizards;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
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.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
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.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
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.Text;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.dom.TokenScanner;
import org.eclipse.jdt.internal.corext.template.java.JavaContext;
import org.eclipse.jdt.internal.corext.template.java.Templates;
import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
import org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaPackageCompletionProcessor;
import org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.SuperInterfaceSelectionDialog;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
import org.eclipse.jdt.ui.CodeGeneration;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.PreferenceConstants;
/**
* The class <code>NewTypeWizardPage</code> contains controls and validation routines
* for a 'New Type WizardPage'. Implementors decide which components to add and to enable.
* Implementors can also customize the validation code. <code>NewTypeWizardPage</code>
* is intended to serve as base class of all wizards that create types like applets, servlets, classes,
* interfaces, etc.
* <p>
* See <code>NewClassWizardPage</code> or <code>NewInterfaceWizardPage</code> for an
* example usage of <code>NewTypeWizardPage</code>.
* </p>
*
* @see org.eclipse.jdt.ui.wizards.NewClassWizardPage
* @see org.eclipse.jdt.ui.wizards.NewInterfaceWizardPage
*
* @since 2.0
*/
public abstract class NewTypeWizardPage extends NewContainerWizardPage {
/**
* Class used in stub creation routines to add needed imports to a
* compilation unit.
*/
public static class ImportsManager {
private ImportsStructure fImportsStructure;
private HashSet fAddedTypes;
/* package */ ImportsManager(ICompilationUnit createdWorkingCopy) throws CoreException {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store);
int threshold= JavaPreferencesSettings.getImportNumberThreshold(store);
fAddedTypes= new HashSet();
fImportsStructure= new ImportsStructure(createdWorkingCopy, prefOrder, threshold, true);
}
/* package */ ImportsStructure getImportsStructure() {
return fImportsStructure;
}
/**
* Adds a new import declaration that is sorted in the existing imports.
* If an import already exists or the import would conflict with another import
* of an other type with the same simple name the import is not added.
*
* @param qualifiedTypeName The fully qualified name of the type to import
* (dot separated)
* @return Returns the simple type name that can be used in the code or the
* fully qualified type name if an import conflict prevented the import
*/
public String addImport(String qualifiedTypeName) {
fAddedTypes.add(qualifiedTypeName);
return fImportsStructure.addImport(qualifiedTypeName);
}
/* package */ void create(boolean needsSave, SubProgressMonitor monitor) throws CoreException {
fImportsStructure.create(needsSave, monitor);
}
/* package */ void removeImport(String qualifiedName) {
if (fAddedTypes.contains(qualifiedName)) {
fImportsStructure.removeImport(qualifiedName);
}
}
}
/** Public access flag. See The Java Virtual Machine Specification for more details. */
public int F_PUBLIC = Flags.AccPublic;
/** Private access flag. See The Java Virtual Machine Specification for more details. */
public int F_PRIVATE = Flags.AccPrivate;
/** Protected access flag. See The Java Virtual Machine Specification for more details. */
public int F_PROTECTED = Flags.AccProtected;
/** Static access flag. See The Java Virtual Machine Specification for more details. */
public int F_STATIC = Flags.AccStatic;
/** Final access flag. See The Java Virtual Machine Specification for more details. */
public int F_FINAL = Flags.AccFinal;
/** Abstract property flag. See The Java Virtual Machine Specification for more details. */
public int F_ABSTRACT = Flags.AccAbstract;
private final static String PAGE_NAME= "NewTypeWizardPage"; //$NON-NLS-1$
/** Field ID of the package input field */
protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$
/** Field ID of the eclosing type input field */
protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$
/** Field ID of the enclosing type checkbox */
protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$
/** Field ID of the type name input field */
protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$
/** Field ID of the super type input field */
protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$
/** Field ID of the super interfaces input field */
protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$
/** Field ID of the modifier checkboxes */
protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$
/** Field ID of the method stubs checkboxes */
protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$
private class InterfacesListLabelProvider extends LabelProvider {
private Image fInterfaceImage;
public InterfacesListLabelProvider() {
super();
fInterfaceImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_INTERFACE);
}
public Image getImage(Object element) {
return fInterfaceImage;
}
}
private StringButtonStatusDialogField fPackageDialogField;
private SelectionButtonDialogField fEnclosingTypeSelection;
private StringButtonDialogField fEnclosingTypeDialogField;
private boolean fCanModifyPackage;
private boolean fCanModifyEnclosingType;
private IPackageFragment fCurrPackage;
private IType fCurrEnclosingType;
private StringDialogField fTypeNameDialogField;
private StringButtonDialogField fSuperClassDialogField;
private ListDialogField fSuperInterfacesDialogField;
private IType fSuperClass;
private SelectionButtonDialogFieldGroup fAccMdfButtons;
private SelectionButtonDialogFieldGroup fOtherMdfButtons;
private IType fCreatedType;
private JavaPackageCompletionProcessor fCurrPackageCompletionProcessor;
private JavaTypeCompletionProcessor fEnclosingTypeCompletionProcessor;
private JavaTypeCompletionProcessor fSuperClassCompletionProcessor;
protected IStatus fEnclosingTypeStatus;
protected IStatus fPackageStatus;
protected IStatus fTypeNameStatus;
protected IStatus fSuperClassStatus;
protected IStatus fModifierStatus;
protected IStatus fSuperInterfacesStatus;
private boolean fIsClass;
private int fStaticMdfIndex;
private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3;
private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1;
/**
* Creates a new <code>NewTypeWizardPage</code>
*
* @param isClass <code>true</code> if a new class is to be created; otherwise
* an interface is to be created
* @param pageName the wizard page's name
*/
public NewTypeWizardPage(boolean isClass, String pageName) {
super(pageName);
fCreatedType= null;
fIsClass= isClass;
TypeFieldsAdapter adapter= new TypeFieldsAdapter();
fPackageDialogField= new StringButtonStatusDialogField(adapter);
fPackageDialogField.setDialogFieldListener(adapter);
fPackageDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.package.label")); //$NON-NLS-1$
fPackageDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.package.button")); //$NON-NLS-1$
fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$
fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK);
fEnclosingTypeSelection.setDialogFieldListener(adapter);
fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.enclosing.selection.label")); //$NON-NLS-1$
fEnclosingTypeDialogField= new StringButtonDialogField(adapter);
fEnclosingTypeDialogField.setDialogFieldListener(adapter);
fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.enclosing.button")); //$NON-NLS-1$
fTypeNameDialogField= new StringDialogField();
fTypeNameDialogField.setDialogFieldListener(adapter);
fTypeNameDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.typename.label")); //$NON-NLS-1$
fSuperClassDialogField= new StringButtonDialogField(adapter);
fSuperClassDialogField.setDialogFieldListener(adapter);
fSuperClassDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.superclass.label")); //$NON-NLS-1$
fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.superclass.button")); //$NON-NLS-1$
String[] addButtons= new String[] {
/* 0 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.add"), //$NON-NLS-1$
/* 1 */ null,
/* 2 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.remove") //$NON-NLS-1$
};
fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider());
fSuperInterfacesDialogField.setDialogFieldListener(adapter);
String interfaceLabel= fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.interfaces.class.label") : NewWizardMessages.getString("NewTypeWizardPage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$
fSuperInterfacesDialogField.setLabelText(interfaceLabel);
fSuperInterfacesDialogField.setRemoveButtonIndex(2);
String[] buttonNames1= new String[] {
/* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.public"), //$NON-NLS-1$
/* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.default"), //$NON-NLS-1$
/* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.private"), //$NON-NLS-1$
/* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("NewTypeWizardPage.modifiers.protected") //$NON-NLS-1$
};
fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4);
fAccMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.modifiers.acc.label")); //$NON-NLS-1$
fAccMdfButtons.setSelection(0, true);
String[] buttonNames2;
if (fIsClass) {
buttonNames2= new String[] {
/* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.abstract"), //$NON-NLS-1$
/* 1 == FINAL_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.final"), //$NON-NLS-1$
/* 2 */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$
};
fStaticMdfIndex= 2; // index of the static checkbox is 2
} else {
buttonNames2= new String[] {
NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$
};
fStaticMdfIndex= 0; // index of the static checkbox is 0
}
fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4);
fOtherMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false);
fCurrPackageCompletionProcessor= new JavaPackageCompletionProcessor();
fEnclosingTypeCompletionProcessor= new JavaTypeCompletionProcessor(false, false);
fSuperClassCompletionProcessor= new JavaTypeCompletionProcessor(false, false);
fPackageStatus= new StatusInfo();
fEnclosingTypeStatus= new StatusInfo();
fCanModifyPackage= true;
fCanModifyEnclosingType= true;
updateEnableState();
fTypeNameStatus= new StatusInfo();
fSuperClassStatus= new StatusInfo();
fSuperInterfacesStatus= new StatusInfo();
fModifierStatus= new StatusInfo();
}
/**
* Initializes all fields provided by the page with a given selection.
*
* @param elem the selection used to intialize this page or <code>
* null</code> if no selection was available
*/
protected void initTypePage(IJavaElement elem) {
String initSuperclass= "java.lang.Object"; //$NON-NLS-1$
ArrayList initSuperinterfaces= new ArrayList(5);
IPackageFragment pack= null;
IType enclosingType= null;
if (elem != null) {
// evaluate the enclosing type
pack= (IPackageFragment) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
IType typeInCU= (IType) elem.getAncestor(IJavaElement.TYPE);
if (typeInCU != null) {
if (typeInCU.getCompilationUnit() != null) {
enclosingType= typeInCU;
}
} else {
ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
enclosingType= cu.findPrimaryType();
}
}
try {
IType type= null;
if (elem.getElementType() == IJavaElement.TYPE) {
type= (IType)elem;
if (type.exists()) {
String superName= JavaModelUtil.getFullyQualifiedName(type);
if (type.isInterface()) {
initSuperinterfaces.add(superName);
} else {
initSuperclass= superName;
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// ignore this exception now
}
}
String typeName= ""; //$NON-NLS-1$
ITextSelection selection= getCurrentTextSelection();
if (selection != null) {
String text= selection.getText();
if (JavaConventions.validateJavaTypeName(text).isOK()) {
typeName= text;
}
}
setPackageFragment(pack, true);
setEnclosingType(enclosingType, true);
setEnclosingTypeSelection(false, true);
setTypeName(typeName, true);
setSuperClass(initSuperclass, true);
setSuperInterfaces(initSuperinterfaces, true);
}
// -------- UI Creation ---------
/**
* Creates a separator line. Expects a <code>GridLayout</code> with at least 1 column.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSeparator(Composite composite, int nColumns) {
(new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1));
}
/**
* Creates the controls for the package name field. Expects a <code>GridLayout</code> with at
* least 4 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createPackageControls(Composite composite, int nColumns) {
fPackageDialogField.doFillIntoGrid(composite, nColumns);
Text text= fPackageDialogField.getTextControl(null);
LayoutUtil.setWidthHint(text, getMaxFieldWidth());
LayoutUtil.setHorizontalGrabbing(text);
ControlContentAssistHelper.createTextContentAssistant(text, fCurrPackageCompletionProcessor);
}
/**
* Creates the controls for the enclosing type name field. Expects a <code>GridLayout</code> with at
* least 4 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createEnclosingTypeControls(Composite composite, int nColumns) {
// #6891
Composite tabGroup= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
tabGroup.setLayout(layout);
fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1);
Text text= fEnclosingTypeDialogField.getTextControl(composite);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint= getMaxFieldWidth();
gd.horizontalSpan= 2;
text.setLayoutData(gd);
Button button= fEnclosingTypeDialogField.getChangeControl(composite);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.heightHint = SWTUtil.getButtonHeightHint(button);
gd.widthHint = SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
ControlContentAssistHelper.createTextContentAssistant(text, fEnclosingTypeCompletionProcessor);
}
/**
* Creates the controls for the type name field. Expects a <code>GridLayout</code> with at
* least 2 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createTypeNameControls(Composite composite, int nColumns) {
fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1);
DialogField.createEmptySpace(composite);
LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* Creates the controls for the modifiers radio/ceckbox buttons. Expects a
* <code>GridLayout</code> with at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createModifierControls(Composite composite, int nColumns) {
LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1);
Control control= fAccMdfButtons.getSelectionButtonsGroup(composite);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
DialogField.createEmptySpace(composite);
control= fOtherMdfButtons.getSelectionButtonsGroup(composite);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
}
/**
* Creates the controls for the superclass name field. Expects a <code>GridLayout</code>
* with at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSuperClassControls(Composite composite, int nColumns) {
fSuperClassDialogField.doFillIntoGrid(composite, nColumns);
Text text= fSuperClassDialogField.getTextControl(null);
LayoutUtil.setWidthHint(text, getMaxFieldWidth());
ControlContentAssistHelper.createTextContentAssistant(text, fSuperClassCompletionProcessor);
}
/**
* Creates the controls for the superclass name field. Expects a <code>GridLayout</code> with
* at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSuperInterfacesControls(Composite composite, int nColumns) {
fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns);
GridData gd= (GridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData();
if (fIsClass) {
gd.heightHint= convertHeightInCharsToPixels(3);
} else {
gd.heightHint= convertHeightInCharsToPixels(6);
}
gd.grabExcessVerticalSpace= false;
gd.widthHint= getMaxFieldWidth();
}
/**
* Sets the focus on the type name input field.
*/
protected void setFocus() {
fTypeNameDialogField.setFocus();
}
// -------- TypeFieldsAdapter --------
private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter {
// -------- IStringButtonAdapter
public void changeControlPressed(DialogField field) {
typePageChangeControlPressed(field);
}
// -------- IListAdapter
public void customButtonPressed(ListDialogField field, int index) {
typePageCustomButtonPressed(field, index);
}
public void selectionChanged(ListDialogField field) {}
// -------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
typePageDialogFieldChanged(field);
}
public void doubleClicked(ListDialogField field) {
}
}
private void typePageChangeControlPressed(DialogField field) {
if (field == fPackageDialogField) {
IPackageFragment pack= choosePackage();
if (pack != null) {
fPackageDialogField.setText(pack.getElementName());
}
} else if (field == fEnclosingTypeDialogField) {
IType type= chooseEnclosingType();
if (type != null) {
fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
} else if (field == fSuperClassDialogField) {
IType type= chooseSuperType();
if (type != null) {
fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
}
}
private void typePageCustomButtonPressed(DialogField field, int index) {
if (field == fSuperInterfacesDialogField) {
chooseSuperInterfaces();
}
}
/*
* A field on the type has changed. The fields' status and all dependend
* status are updated.
*/
private void typePageDialogFieldChanged(DialogField field) {
String fieldName= null;
if (field == fPackageDialogField) {
fPackageStatus= packageChanged();
updatePackageStatusLabel();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= PACKAGE;
} else if (field == fEnclosingTypeDialogField) {
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSING;
} else if (field == fEnclosingTypeSelection) {
updateEnableState();
boolean isEnclosedType= isEnclosingTypeSelected();
if (!isEnclosedType) {
if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, false);
fAccMdfButtons.setSelection(PROTECTED_INDEX, false);
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
fOtherMdfButtons.setSelection(fStaticMdfIndex, false);
}
}
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType);
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSINGSELECTION;
} else if (field == fTypeNameDialogField) {
fTypeNameStatus= typeNameChanged();
fieldName= TYPENAME;
} else if (field == fSuperClassDialogField) {
fSuperClassStatus= superClassChanged();
fieldName= SUPER;
} else if (field == fSuperInterfacesDialogField) {
fSuperInterfacesStatus= superInterfacesChanged();
fieldName= INTERFACES;
} else if (field == fOtherMdfButtons || field == fAccMdfButtons) {
fModifierStatus= modifiersChanged();
fieldName= MODIFIERS;
} else {
fieldName= METHODS;
}
// tell all others
handleFieldChanged(fieldName);
}
// -------- update message ----------------
/*
* @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String)
*/
protected void handleFieldChanged(String fieldName) {
super.handleFieldChanged(fieldName);
if (fieldName == CONTAINER) {
fPackageStatus= packageChanged();
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fSuperInterfacesStatus= superInterfacesChanged();
}
}
// ---- set / get ----------------
/**
* Returns the text of the package input field.
*
* @return the text of the package input field
*/
public String getPackageText() {
return fPackageDialogField.getText();
}
/**
* Returns the text of the enclosing type input field.
*
* @return the text of the enclosing type input field
*/
public String getEnclosingTypeText() {
return fEnclosingTypeDialogField.getText();
}
/**
* Returns the package fragment corresponding to the current input.
*
* @return a package fragement or <code>null</code> if the input
* could not be resolved.
*/
public IPackageFragment getPackageFragment() {
if (!isEnclosingTypeSelected()) {
return fCurrPackage;
} else {
if (fCurrEnclosingType != null) {
return fCurrEnclosingType.getPackageFragment();
}
}
return null;
}
/**
* Sets the package fragment to the given value. The method updates the model
* and the text of the control.
*
* @param pack the package fragement to be set
* @param canBeModified if <code>true</code> the package fragment is
* editable; otherwise it is read-only.
*/
public void setPackageFragment(IPackageFragment pack, boolean canBeModified) {
fCurrPackage= pack;
fCanModifyPackage= canBeModified;
String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$
fPackageDialogField.setText(str);
updateEnableState();
}
/**
* Returns the enclosing type corresponding to the current input.
*
* @return the enclosing type or <code>null</code> if the enclosing type is
* not selected or the input could not be resolved
*/
public IType getEnclosingType() {
if (isEnclosingTypeSelected()) {
return fCurrEnclosingType;
}
return null;
}
/**
* Sets the enclosing type. The method updates the underlying model
* and the text of the control.
*
* @param type the enclosing type
* @param canBeModified if <code>true</code> the enclosing type field is
* editable; otherwise it is read-only.
*/
public void setEnclosingType(IType type, boolean canBeModified) {
fCurrEnclosingType= type;
fCanModifyEnclosingType= canBeModified;
String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$
fEnclosingTypeDialogField.setText(str);
updateEnableState();
}
/**
* Returns the selection state of the enclosing type checkbox.
*
* @return the seleciton state of the enclosing type checkbox
*/
public boolean isEnclosingTypeSelected() {
return fEnclosingTypeSelection.isSelected();
}
/**
* Sets the enclosing type checkbox's selection state.
*
* @param isSelected the checkbox's selection state
* @param canBeModified if <code>true</code> the enclosing type checkbox is
* modifiable; otherwise it is read-only.
*/
public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) {
fEnclosingTypeSelection.setSelection(isSelected);
fEnclosingTypeSelection.setEnabled(canBeModified);
updateEnableState();
}
/**
* Returns the type name entered into the type input field.
*
* @return the type name
*/
public String getTypeName() {
return fTypeNameDialogField.getText();
}
/**
* Sets the type name input field's text to the given value. Method doesn't update
* the model.
*
* @param name the new type name
* @param canBeModified if <code>true</code> the enclosing type name field is
* editable; otherwise it is read-only.
*/
public void setTypeName(String name, boolean canBeModified) {
fTypeNameDialogField.setText(name);
fTypeNameDialogField.setEnabled(canBeModified);
}
/**
* Returns the selected modifiers.
*
* @return the selected modifiers
* @see Flags
*/
public int getModifiers() {
int mdf= 0;
if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) {
mdf+= F_PUBLIC;
} else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) {
mdf+= F_PRIVATE;
} else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
mdf+= F_PROTECTED;
}
if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) {
mdf+= F_ABSTRACT;
}
if (fOtherMdfButtons.isSelected(FINAL_INDEX)) {
mdf+= F_FINAL;
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
mdf+= F_STATIC;
}
return mdf;
}
/**
* Sets the modifiers.
*
* @param modifiers <code>F_PUBLIC</code>, <code>F_PRIVATE</code>,
* <code>F_PROTECTED</code>, <code>F_ABSTRACT, F_FINAL</code>
* or <code>F_STATIC</code> or, a valid combination.
* @param canBeModified if <code>true</code> the modifier fields are
* editable; otherwise they are read-only
* @see Flags
*/
public void setModifiers(int modifiers, boolean canBeModified) {
if (Flags.isPublic(modifiers)) {
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
} else if (Flags.isPrivate(modifiers)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, true);
} else if (Flags.isProtected(modifiers)) {
fAccMdfButtons.setSelection(PROTECTED_INDEX, true);
} else {
fAccMdfButtons.setSelection(DEFAULT_INDEX, true);
}
if (Flags.isAbstract(modifiers)) {
fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true);
}
if (Flags.isFinal(modifiers)) {
fOtherMdfButtons.setSelection(FINAL_INDEX, true);
}
if (Flags.isStatic(modifiers)) {
fOtherMdfButtons.setSelection(fStaticMdfIndex, true);
}
fAccMdfButtons.setEnabled(canBeModified);
fOtherMdfButtons.setEnabled(canBeModified);
}
/**
* Returns the content of the superclass input field.
*
* @return the superclass name
*/
public String getSuperClass() {
return fSuperClassDialogField.getText();
}
/**
* Sets the super class name.
*
* @param name the new superclass name
* @param canBeModified if <code>true</code> the superclass name field is
* editable; otherwise it is read-only.
*/
public void setSuperClass(String name, boolean canBeModified) {
fSuperClassDialogField.setText(name);
fSuperClassDialogField.setEnabled(canBeModified);
}
/**
* Returns the chosen super interfaces.
*
* @return a list of chosen super interfaces. The list's elements
* are of type <code>String</code>
*/
public List getSuperInterfaces() {
return fSuperInterfacesDialogField.getElements();
}
/**
* Sets the super interfaces.
*
* @param interfacesNames a list of super interface. The method requires that
* the list's elements are of type <code>String</code>
* @param canBeModified if <code>true</code> the super interface field is
* editable; otherwise it is read-only.
*/
public void setSuperInterfaces(List interfacesNames, boolean canBeModified) {
fSuperInterfacesDialogField.setElements(interfacesNames);
fSuperInterfacesDialogField.setEnabled(canBeModified);
}
/**
* Returns the resource handle that corresponds to the compilation unit to was or
* will be created or modified.
* @return A resource or null if the page contains illegal values.
* @since 3.0
*/
public IResource getModifiedResource() {
IType enclosing= getEnclosingType();
if (enclosing != null) {
return enclosing.getResource();
}
IPackageFragment pack= getPackageFragment();
if (pack != null) {
return pack.getCompilationUnit(getTypeName() + ".java").getResource(); //$NON-NLS-1$
}
return null;
}
// ----------- validation ----------
/*
* @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#containerChanged()
*/
protected IStatus containerChanged() {
IStatus status= super.containerChanged();
fCurrPackageCompletionProcessor.setPackageFragmentRoot(getPackageFragmentRoot());
if (getPackageFragmentRoot() != null)
fEnclosingTypeCompletionProcessor.setPackageFragment(getPackageFragmentRoot().getPackageFragment("")); //$NON-NLS-1$
return status;
}
/**
* A hook method that gets called when the package field has changed. The method
* validates the package name and returns the status of the validation. The validation
* also updates the package fragment model.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus packageChanged() {
StatusInfo status= new StatusInfo();
fPackageDialogField.enableButton(getPackageFragmentRoot() != null);
String packName= getPackageText();
if (packName.length() > 0) {
IStatus val= JavaConventions.validatePackageName(packName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$
// continue
}
} else {
status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.DefaultPackageDiscouraged")); //$NON-NLS-1$
}
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root != null) {
if (root.getJavaProject().exists() && packName.length() > 0) {
try {
IPath rootPath= root.getPath();
IPath outputPath= root.getJavaProject().getOutputLocation();
if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
// if the bin folder is inside of our root, dont allow to name a package
// like the bin folder
IPath packagePath= rootPath.append(packName.replace('.', '/'));
if (outputPath.isPrefixOf(packagePath)) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// let pass
}
}
fCurrPackage= root.getPackageFragment(packName);
fSuperClassCompletionProcessor.setPackageFragment(fCurrPackage);
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
/*
* Updates the 'default' label next to the package field.
*/
private void updatePackageStatusLabel() {
String packName= getPackageText();
if (packName.length() == 0) {
fPackageDialogField.setStatus(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$
} else {
fPackageDialogField.setStatus(""); //$NON-NLS-1$
}
}
/*
* Updates the enable state of buttons related to the enclosing type selection checkbox.
*/
private void updateEnableState() {
boolean enclosing= isEnclosingTypeSelected();
fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing);
fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing);
}
/**
* Hook method that gets called when the enclosing type name has changed. The method
* validates the enclosing type and returns the status of the validation. It also updates the
* enclosing type model.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus enclosingTypeChanged() {
StatusInfo status= new StatusInfo();
fCurrEnclosingType= null;
IPackageFragmentRoot root= getPackageFragmentRoot();
fEnclosingTypeDialogField.enableButton(root != null);
if (root == null) {
status.setError(""); //$NON-NLS-1$
return status;
}
String enclName= getEnclosingTypeText();
if (enclName.length() == 0) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeEnterName")); //$NON-NLS-1$
return status;
}
try {
IType type= findType(root.getJavaProject(), enclName);
if (type == null) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$
return status;
}
if (type.getCompilationUnit() == null) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotInCU")); //$NON-NLS-1$
return status;
}
if (!JavaModelUtil.isEditable(type.getCompilationUnit())) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotEditable")); //$NON-NLS-1$
return status;
}
fCurrEnclosingType= type;
IPackageFragmentRoot enclosingRoot= JavaModelUtil.getPackageFragmentRoot(type);
if (!enclosingRoot.equals(root)) {
status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.EnclosingNotInSourceFolder")); //$NON-NLS-1$
}
return status;
} catch (JavaModelException e) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$
JavaPlugin.log(e);
return status;
}
}
/**
* Hook method that gets called when the type name has changed. The method validates the
* type name and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus typeNameChanged() {
StatusInfo status= new StatusInfo();
String typeName= getTypeName();
// must not be empty
if (typeName.length() == 0) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnterTypeName")); //$NON-NLS-1$
return status;
}
if (typeName.indexOf('.') != -1) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.QualifiedName")); //$NON-NLS-1$
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(typeName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$
// continue checking
}
// must not exist
if (!isEnclosingTypeSelected()) {
IPackageFragment pack= getPackageFragment();
if (pack != null) {
ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$
if (cu.getResource().exists()) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
} else {
IType type= getEnclosingType();
if (type != null) {
IType member= type.getType(typeName);
if (member.exists()) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
}
return status;
}
/**
* Hook method that gets called when the superclass name has changed. The method
* validates the superclass name and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus superClassChanged() {
StatusInfo status= new StatusInfo();
IPackageFragmentRoot root= getPackageFragmentRoot();
fSuperClassDialogField.enableButton(root != null);
fSuperClass= null;
String sclassName= getSuperClass();
if (sclassName.length() == 0) {
// accept the empty field (stands for java.lang.Object)
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(sclassName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$
return status;
}
if (root != null) {
try {
IType type= resolveSuperTypeName(root.getJavaProject(), sclassName);
if (type == null) {
status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.SuperClassNotExists")); //$NON-NLS-1$
return status;
} else {
if (type.isInterface()) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$
return status;
}
int flags= type.getFlags();
if (Flags.isFinal(flags)) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$
return status;
} else if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$
return status;
}
}
fSuperClass= type;
} catch (JavaModelException e) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$
JavaPlugin.log(e);
}
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException {
if (!jproject.exists()) {
return null;
}
IType type= null;
if (isEnclosingTypeSelected()) {
// search in the context of the enclosing type
IType enclosingType= getEnclosingType();
if (enclosingType != null) {
String[][] res= enclosingType.resolveType(sclassName);
if (res != null && res.length > 0) {
type= jproject.findType(res[0][0], res[0][1]);
}
}
} else {
IPackageFragment currPack= getPackageFragment();
if (type == null && currPack != null) {
String packName= currPack.getElementName();
// search in own package
if (!currPack.isDefaultPackage()) {
type= jproject.findType(packName, sclassName);
}
// search in java.lang
if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$
type= jproject.findType("java.lang", sclassName); //$NON-NLS-1$
}
}
// search fully qualified
if (type == null) {
type= jproject.findType(sclassName);
}
}
return type;
}
private IType findType(IJavaProject project, String typeName) throws JavaModelException {
if (project.exists()) {
return project.findType(typeName);
}
return null;
}
/**
* Hook method that gets called when the list of super interface has changed. The method
* validates the superinterfaces and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus superInterfacesChanged() {
StatusInfo status= new StatusInfo();
IPackageFragmentRoot root= getPackageFragmentRoot();
fSuperInterfacesDialogField.enableButton(0, root != null);
if (root != null) {
List elements= fSuperInterfacesDialogField.getElements();
int nElements= elements.size();
for (int i= 0; i < nElements; i++) {
String intfname= (String)elements.get(i);
try {
IType type= findType(root.getJavaProject(), intfname);
if (type == null) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$
return status;
} else {
if (type.isClass()) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$
return status;
}
if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// let pass, checking is an extra
}
}
}
return status;
}
/**
* Hook method that gets called when the modifiers have changed. The method validates
* the modifiers and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus modifiersChanged() {
StatusInfo status= new StatusInfo();
int modifiers= getModifiers();
if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$
}
return status;
}
// selection dialogs
private IPackageFragment choosePackage() {
IPackageFragmentRoot froot= getPackageFragmentRoot();
IJavaElement[] packages= null;
try {
if (froot != null && froot.exists()) {
packages= froot.getChildren();
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
if (packages == null) {
packages= new IJavaElement[0];
}
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT));
dialog.setIgnoreCase(false);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.description")); //$NON-NLS-1$
dialog.setEmptyListMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.empty")); //$NON-NLS-1$
dialog.setElements(packages);
IPackageFragment pack= getPackageFragment();
if (pack != null) {
dialog.setInitialSelections(new Object[] { pack });
}
if (dialog.open() == Window.OK) {
return (IPackageFragment) dialog.getFirstResult();
}
return null;
}
private IType chooseEnclosingType() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return null;
}
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { root });
TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.TYPE, scope);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$
dialog.setFilter(Signature.getSimpleName(getEnclosingTypeText()));
if (dialog.open() == Window.OK) {
return (IType) dialog.getFirstResult();
}
return null;
}
private IType chooseSuperType() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return null;
}
IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() };
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);
TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.CLASS, scope);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.message")); //$NON-NLS-1$
dialog.setFilter(getSuperClass());
if (dialog.open() == Window.OK) {
return (IType) dialog.getFirstResult();
}
return null;
}
private void chooseSuperInterfaces() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return;
}
IJavaProject project= root.getJavaProject();
SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project);
dialog.setTitle(fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.class.title") : NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.interface.title")); //$NON-NLS-1$ //$NON-NLS-2$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.message")); //$NON-NLS-1$
dialog.open();
return;
}
// ---- creation ----------------
/**
* Creates the new type using the entered field values.
*
* @param monitor a progress monitor to report progress.
*/
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$
ICompilationUnit createdWorkingCopy= null;
try {
IPackageFragmentRoot root= getPackageFragmentRoot();
IPackageFragment pack= getPackageFragment();
if (pack == null) {
pack= root.getPackageFragment(""); //$NON-NLS-1$
}
if (!pack.exists()) {
String packName= pack.getElementName();
pack= root.createPackageFragment(packName, true, null);
}
monitor.worked(1);
String clName= getTypeName();
boolean isInnerClass= isEnclosingTypeSelected();
IType createdType;
ImportsManager imports;
int indent= 0;
String lineDelimiter= null;
if (!isInnerClass) {
lineDelimiter= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
ICompilationUnit parentCU= pack.createCompilationUnit(clName + ".java", "", false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$ //$NON-NLS-2$
// create a working copy with a new owner
createdWorkingCopy= parentCU.getWorkingCopy(null);
// use the compiler template a first time to read the imports
String content= CodeGeneration.getCompilationUnitContent(createdWorkingCopy, null, "", lineDelimiter); //$NON-NLS-1$
if (content != null) {
createdWorkingCopy.getBuffer().setContents(content);
}
imports= new ImportsManager(createdWorkingCopy);
// add an import that will be removed again. Having this import solves 14661
imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), getTypeName()));
String typeContent= constructTypeStub(imports, lineDelimiter);
String cuContent= constructCUContent(parentCU, typeContent, lineDelimiter);
createdWorkingCopy.getBuffer().setContents(cuContent);
createdType= createdWorkingCopy.getType(clName);
} else {
IType enclosingType= getEnclosingType();
// if we are working on a enclosed type that is open in an editor,
// then replace the enclosing type with its working copy
IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType);
if (workingCopy != null) {
enclosingType= workingCopy;
}
ICompilationUnit parentCU= enclosingType.getCompilationUnit();
imports= new ImportsManager(parentCU);
// add imports that will be removed again. Having the imports solves 14661
IType[] topLevelTypes= parentCU.getTypes();
for (int i= 0; i < topLevelTypes.length; i++) {
imports.addImport(topLevelTypes[i].getFullyQualifiedName('.'));
}
lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType);
StringBuffer content= new StringBuffer();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS)) {
String comment= getTypeComment(parentCU, lineDelimiter);
if (comment != null) {
content.append(comment);
content.append(lineDelimiter);
}
}
content.append(constructTypeStub(imports, lineDelimiter));
IJavaElement[] elems= enclosingType.getChildren();
IJavaElement sibling= elems.length > 0 ? elems[0] : null;
createdType= enclosingType.createType(content.toString(), sibling, false, new SubProgressMonitor(monitor, 1));
indent= StubUtility.getIndentUsed(enclosingType) + 1;
}
// add imports for superclass/interfaces, so types can be resolved correctly
ICompilationUnit cu= createdType.getCompilationUnit();
boolean needsSave= !cu.isWorkingCopy();
imports.create(needsSave, new SubProgressMonitor(monitor, 1));
JavaModelUtil.reconcile(cu);
createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1));
// add imports
imports.create(needsSave, new SubProgressMonitor(monitor, 1));
if (removeUnused(cu, imports)) {
imports.create(needsSave, null);
}
JavaModelUtil.reconcile(cu);
ISourceRange range= createdType.getSourceRange();
IBuffer buf= cu.getBuffer();
String originalContent= buf.getText(range.getOffset(), range.getLength());
String formattedContent= CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, indent, null, lineDelimiter, pack.getJavaProject());
buf.replace(range.getOffset(), range.getLength(), formattedContent);
if (!isInnerClass) {
String fileComment= getFileComment(cu);
if (fileComment != null && fileComment.length() > 0) {
buf.replace(0, 0, fileComment + lineDelimiter);
}
cu.commitWorkingCopy(false, new SubProgressMonitor(monitor, 1));
} else {
if (needsSave) {
buf.save(null, false);
}
monitor.worked(1);
}
if (createdWorkingCopy != null) {
fCreatedType= (IType) createdType.getPrimaryElement();
} else {
fCreatedType= createdType;
}
} finally {
if (createdWorkingCopy != null) {
createdWorkingCopy.discardWorkingCopy();
}
monitor.done();
}
}
private boolean removeUnused(ICompilationUnit cu, ImportsManager imports) {
ASTParser parser= ASTParser.newParser(AST.LEVEL_2_0);
parser.setSource(cu);
parser.setResolveBindings(true);
CompilationUnit root= (CompilationUnit) parser.createAST(null);
IProblem[] problems= root.getProblems();
boolean importRemoved= false;
for (int i= 0; i < problems.length; i++) {
if (problems[i].getID() == IProblem.UnusedImport) {
String imp= problems[i].getArguments()[0];
imports.removeImport(imp);
importRemoved=true;
}
}
return importRemoved;
}
/**
* Uses the New Java file template from the code template page to generate a
* compilation unit with the given type content.
* @param cu The new created compilation unit
* @param typeContent The content of the type, including signature and type
* body.
* @param lineDelimiter The line delimiter to be used.
* @return String Returns the result of evaluating the new file template
* with the given type content.
* @throws CoreException
* @since 2.1
*/
protected String constructCUContent(ICompilationUnit cu, String typeContent, String lineDelimiter) throws CoreException {
String typeComment= getTypeComment(cu, lineDelimiter);
IPackageFragment pack= (IPackageFragment) cu.getParent();
String content= CodeGeneration.getCompilationUnitContent(cu, typeComment, typeContent, lineDelimiter);
if (content != null) {
ASTParser parser= ASTParser.newParser(AST.LEVEL_2_0);
parser.setSource(content.toCharArray());
CompilationUnit unit= (CompilationUnit) parser.createAST(null);
if ((pack.isDefaultPackage() || unit.getPackage() != null) && !unit.types().isEmpty()) {
return content;
}
}
StringBuffer buf= new StringBuffer();
if (!pack.isDefaultPackage()) {
buf.append("package ").append(pack.getElementName()).append(';'); //$NON-NLS-1$
}
buf.append(lineDelimiter).append(lineDelimiter);
if (typeComment != null) {
buf.append(typeComment).append(lineDelimiter);
}
buf.append(typeContent);
return buf.toString();
}
/**
* Returns the created type. The method only returns a valid type
* after <code>createType</code> has been called.
*
* @return the created type
* @see #createType(IProgressMonitor)
*/
public IType getCreatedType() {
return fCreatedType;
}
// ---- construct cu body----------------
private void writeSuperClass(StringBuffer buf, ImportsManager imports) {
String typename= getSuperClass();
if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$
buf.append(" extends "); //$NON-NLS-1$
String qualifiedName= fSuperClass != null ? JavaModelUtil.getFullyQualifiedName(fSuperClass) : typename;
buf.append(imports.addImport(qualifiedName));
}
}
private void writeSuperInterfaces(StringBuffer buf, ImportsManager imports) {
List interfaces= getSuperInterfaces();
int last= interfaces.size() - 1;
if (last >= 0) {
if (fIsClass) {
buf.append(" implements "); //$NON-NLS-1$
} else {
buf.append(" extends "); //$NON-NLS-1$
}
for (int i= 0; i <= last; i++) {
String typename= (String) interfaces.get(i);
buf.append(imports.addImport(typename));
if (i < last) {
buf.append(',');
}
}
}
}
/*
* Called from createType to construct the source for this type
*/
private String constructTypeStub(ImportsManager imports, String lineDelimiter) {
StringBuffer buf= new StringBuffer();
int modifiers= getModifiers();
buf.append(Flags.toString(modifiers));
if (modifiers != 0) {
buf.append(' ');
}
buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$
buf.append(getTypeName());
writeSuperClass(buf, imports);
writeSuperInterfaces(buf, imports);
buf.append('{');
buf.append(lineDelimiter);
buf.append(lineDelimiter);
buf.append('}');
buf.append(lineDelimiter);
return buf.toString();
}
/**
* Hook method that gets called from <code>createType</code> to support adding of
* unanticipated methods, fields, and inner types to the created type.
* <p>
* Implementers can use any methods defined on <code>IType</code> to manipulate the
* new type.
* </p>
* <p>
* The source code of the new type will be formtted using the platform's formatter. Needed
* imports are added by the wizard at the end of the type creation process using the given
* import manager.
* </p>
*
* @param newType the new type created via <code>createType</code>
* @param imports an import manager which can be used to add new imports
* @param monitor a progress monitor to report progress. Must not be <code>null</code>
*
* @see #createType(IProgressMonitor)
*/
protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
// default implementation does nothing
// example would be
// String mainMathod= "public void foo(Vector vec) {}"
// createdType.createMethod(main, null, false, null);
// imports.addImport("java.lang.Vector");
}
/**
* @deprecated Instead of file templates, the new type code template
* specifies the stub for a compilation unit.
*/
protected String getFileComment(ICompilationUnit parentCU) {
return null;
}
private boolean isValidComment(String template) {
IScanner scanner= ToolFactory.createScanner(true, false, false, false);
scanner.setSource(template.toCharArray());
try {
int next= scanner.getNextToken();
while (TokenScanner.isComment(next)) {
next= scanner.getNextToken();
}
return next == ITerminalSymbols.TokenNameEOF;
} catch (InvalidInputException e) {
}
return false;
}
/**
* Hook method that gets called from <code>createType</code> to retrieve
* a type comment. This default implementation returns the content of the
* 'type comment' template.
*
* @return the type comment or <code>null</code> if a type comment
* is not desired
*/
protected String getTypeComment(ICompilationUnit parentCU, String lineDelimiter) {
try {
StringBuffer typeName= new StringBuffer();
if (isEnclosingTypeSelected()) {
typeName.append(JavaModelUtil.getTypeQualifiedName(getEnclosingType())).append('.');
}
typeName.append(getTypeName());
String comment= CodeGeneration.getTypeComment(parentCU, typeName.toString(), lineDelimiter);
if (comment != null && isValidComment(comment)) {
return comment;
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
return null;
}
/**
* @deprecated Use getTypeComment(ICompilationUnit, String)
*/
protected String getTypeComment(ICompilationUnit parentCU) {
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS)) {
return getTypeComment(parentCU, String.valueOf('\n'));
}
return null;
}
/**
* @deprecated Use getTemplate(String,ICompilationUnit,int)
*/
protected String getTemplate(String name, ICompilationUnit parentCU) {
return getTemplate(name, parentCU, 0);
}
/**
* Returns the string resulting from evaluation the given template in
* the context of the given compilation unit. This accesses the normal
* template page, not the code templates. To use code templates use
* <code>constructCUContent</code> to construct a compilation unit stub or
* getTypeComment for the comment of the type.
*
* @param name the template to be evaluated
* @param parentCU the templates evaluation context
* @param pos a source offset into the parent compilation unit. The
* template is evalutated at the given source offset
*/
protected String getTemplate(String name, ICompilationUnit parentCU, int pos) {
try {
Template[] templates= Templates.getInstance().getTemplates(name);
if (templates.length > 0) {
return JavaContext.evaluateTemplate(templates[0], parentCU, pos);
}
} catch (CoreException e) {
JavaPlugin.log(e);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return null;
}
/**
* Creates the bodies of all unimplemented methods and constructors and adds them to the type.
* Method is typically called by implementers of <code>NewTypeWizardPage</code> to add
* needed method and constructors.
*
* @param type the type for which the new methods and constructor are to be created
* @param doConstructors if <code>true</code> unimplemented constructors are created
* @param doUnimplementedMethods if <code>true</code> unimplemented methods are created
* @param imports an import manager to add all neded import statements
* @param monitor a progress monitor to report progress
*/
protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
ArrayList newMethods= new ArrayList();
ITypeHierarchy hierarchy= null;
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (doConstructors) {
hierarchy= type.newSupertypeHierarchy(monitor);
IType superclass= hierarchy.getSuperclass(type);
if (superclass != null) {
String[] constructors= StubUtility.evalConstructors(type, superclass, settings, imports.getImportsStructure());
if (constructors != null) {
for (int i= 0; i < constructors.length; i++) {
newMethods.add(constructors[i]);
}
}
}
}
if (doUnimplementedMethods) {
if (hierarchy == null) {
hierarchy= type.newSupertypeHierarchy(monitor);
}
String[] unimplemented= StubUtility.evalUnimplementedMethods(type, hierarchy, false, settings, imports.getImportsStructure());
if (unimplemented != null) {
for (int i= 0; i < unimplemented.length; i++) {
newMethods.add(unimplemented[i]);
}
}
}
IMethod[] createdMethods= new IMethod[newMethods.size()];
for (int i= 0; i < newMethods.size(); i++) {
String content= (String) newMethods.get(i) + '\n'; // content will be formatted, ok to use \n
createdMethods[i]= type.createMethod(content, null, false, null);
}
return createdMethods;
}
// ---- creation ----------------
/**
* Returns the runnable that creates the type using the current settings.
* The returned runnable must be executed in the UI thread.
*
* @return the runnable to create the new type
*/
public IRunnableWithProgress getRunnable() {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
createType(monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
}
}
|
20,633 |
Bug 20633 inner "new interface" in a class - why option "static"? [code manipulation]
|
When you add an inner interface to a class or interface, the "new interface" dialog offers a checkbox "static". Wether an inner interface is static or not does not make a bit of a difference. So the main effect that checkbox is likely to have is, it confuses Java-newcomers. "Could you please tell me what this decision I have to make means?" (Nothing.) Get rid of that checkbox.
|
resolved fixed
|
4bc0b05
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-19T12:02:18Z | 2002-06-19T12:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.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.wizards;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
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.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
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.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
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.Text;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.dom.TokenScanner;
import org.eclipse.jdt.internal.corext.template.java.JavaContext;
import org.eclipse.jdt.internal.corext.template.java.Templates;
import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
import org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaPackageCompletionProcessor;
import org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.SuperInterfaceSelectionDialog;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
import org.eclipse.jdt.ui.CodeGeneration;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.PreferenceConstants;
/**
* The class <code>NewTypeWizardPage</code> contains controls and validation routines
* for a 'New Type WizardPage'. Implementors decide which components to add and to enable.
* Implementors can also customize the validation code. <code>NewTypeWizardPage</code>
* is intended to serve as base class of all wizards that create types like applets, servlets, classes,
* interfaces, etc.
* <p>
* See <code>NewClassWizardPage</code> or <code>NewInterfaceWizardPage</code> for an
* example usage of <code>NewTypeWizardPage</code>.
* </p>
*
* @see org.eclipse.jdt.ui.wizards.NewClassWizardPage
* @see org.eclipse.jdt.ui.wizards.NewInterfaceWizardPage
*
* @since 2.0
*/
public abstract class NewTypeWizardPage extends NewContainerWizardPage {
/**
* Class used in stub creation routines to add needed imports to a
* compilation unit.
*/
public static class ImportsManager {
private ImportsStructure fImportsStructure;
private HashSet fAddedTypes;
/* package */ ImportsManager(ICompilationUnit createdWorkingCopy) throws CoreException {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store);
int threshold= JavaPreferencesSettings.getImportNumberThreshold(store);
fAddedTypes= new HashSet();
fImportsStructure= new ImportsStructure(createdWorkingCopy, prefOrder, threshold, true);
}
/* package */ ImportsStructure getImportsStructure() {
return fImportsStructure;
}
/**
* Adds a new import declaration that is sorted in the existing imports.
* If an import already exists or the import would conflict with another import
* of an other type with the same simple name the import is not added.
*
* @param qualifiedTypeName The fully qualified name of the type to import
* (dot separated)
* @return Returns the simple type name that can be used in the code or the
* fully qualified type name if an import conflict prevented the import
*/
public String addImport(String qualifiedTypeName) {
fAddedTypes.add(qualifiedTypeName);
return fImportsStructure.addImport(qualifiedTypeName);
}
/* package */ void create(boolean needsSave, SubProgressMonitor monitor) throws CoreException {
fImportsStructure.create(needsSave, monitor);
}
/* package */ void removeImport(String qualifiedName) {
if (fAddedTypes.contains(qualifiedName)) {
fImportsStructure.removeImport(qualifiedName);
}
}
}
/** Public access flag. See The Java Virtual Machine Specification for more details. */
public int F_PUBLIC = Flags.AccPublic;
/** Private access flag. See The Java Virtual Machine Specification for more details. */
public int F_PRIVATE = Flags.AccPrivate;
/** Protected access flag. See The Java Virtual Machine Specification for more details. */
public int F_PROTECTED = Flags.AccProtected;
/** Static access flag. See The Java Virtual Machine Specification for more details. */
public int F_STATIC = Flags.AccStatic;
/** Final access flag. See The Java Virtual Machine Specification for more details. */
public int F_FINAL = Flags.AccFinal;
/** Abstract property flag. See The Java Virtual Machine Specification for more details. */
public int F_ABSTRACT = Flags.AccAbstract;
private final static String PAGE_NAME= "NewTypeWizardPage"; //$NON-NLS-1$
/** Field ID of the package input field */
protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$
/** Field ID of the eclosing type input field */
protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$
/** Field ID of the enclosing type checkbox */
protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$
/** Field ID of the type name input field */
protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$
/** Field ID of the super type input field */
protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$
/** Field ID of the super interfaces input field */
protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$
/** Field ID of the modifier checkboxes */
protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$
/** Field ID of the method stubs checkboxes */
protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$
private class InterfacesListLabelProvider extends LabelProvider {
private Image fInterfaceImage;
public InterfacesListLabelProvider() {
super();
fInterfaceImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_INTERFACE);
}
public Image getImage(Object element) {
return fInterfaceImage;
}
}
private StringButtonStatusDialogField fPackageDialogField;
private SelectionButtonDialogField fEnclosingTypeSelection;
private StringButtonDialogField fEnclosingTypeDialogField;
private boolean fCanModifyPackage;
private boolean fCanModifyEnclosingType;
private IPackageFragment fCurrPackage;
private IType fCurrEnclosingType;
private StringDialogField fTypeNameDialogField;
private StringButtonDialogField fSuperClassDialogField;
private ListDialogField fSuperInterfacesDialogField;
private IType fSuperClass;
private SelectionButtonDialogFieldGroup fAccMdfButtons;
private SelectionButtonDialogFieldGroup fOtherMdfButtons;
private IType fCreatedType;
private JavaPackageCompletionProcessor fCurrPackageCompletionProcessor;
private JavaTypeCompletionProcessor fEnclosingTypeCompletionProcessor;
private JavaTypeCompletionProcessor fSuperClassCompletionProcessor;
protected IStatus fEnclosingTypeStatus;
protected IStatus fPackageStatus;
protected IStatus fTypeNameStatus;
protected IStatus fSuperClassStatus;
protected IStatus fModifierStatus;
protected IStatus fSuperInterfacesStatus;
private boolean fIsClass;
private int fStaticMdfIndex;
private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3;
private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1;
/**
* Creates a new <code>NewTypeWizardPage</code>
*
* @param isClass <code>true</code> if a new class is to be created; otherwise
* an interface is to be created
* @param pageName the wizard page's name
*/
public NewTypeWizardPage(boolean isClass, String pageName) {
super(pageName);
fCreatedType= null;
fIsClass= isClass;
TypeFieldsAdapter adapter= new TypeFieldsAdapter();
fPackageDialogField= new StringButtonStatusDialogField(adapter);
fPackageDialogField.setDialogFieldListener(adapter);
fPackageDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.package.label")); //$NON-NLS-1$
fPackageDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.package.button")); //$NON-NLS-1$
fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$
fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK);
fEnclosingTypeSelection.setDialogFieldListener(adapter);
fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.enclosing.selection.label")); //$NON-NLS-1$
fEnclosingTypeDialogField= new StringButtonDialogField(adapter);
fEnclosingTypeDialogField.setDialogFieldListener(adapter);
fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.enclosing.button")); //$NON-NLS-1$
fTypeNameDialogField= new StringDialogField();
fTypeNameDialogField.setDialogFieldListener(adapter);
fTypeNameDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.typename.label")); //$NON-NLS-1$
fSuperClassDialogField= new StringButtonDialogField(adapter);
fSuperClassDialogField.setDialogFieldListener(adapter);
fSuperClassDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.superclass.label")); //$NON-NLS-1$
fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.superclass.button")); //$NON-NLS-1$
String[] addButtons= new String[] {
/* 0 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.add"), //$NON-NLS-1$
/* 1 */ null,
/* 2 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.remove") //$NON-NLS-1$
};
fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider());
fSuperInterfacesDialogField.setDialogFieldListener(adapter);
String interfaceLabel= fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.interfaces.class.label") : NewWizardMessages.getString("NewTypeWizardPage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$
fSuperInterfacesDialogField.setLabelText(interfaceLabel);
fSuperInterfacesDialogField.setRemoveButtonIndex(2);
String[] buttonNames1= new String[] {
/* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.public"), //$NON-NLS-1$
/* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.default"), //$NON-NLS-1$
/* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.private"), //$NON-NLS-1$
/* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("NewTypeWizardPage.modifiers.protected") //$NON-NLS-1$
};
fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4);
fAccMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.modifiers.acc.label")); //$NON-NLS-1$
fAccMdfButtons.setSelection(0, true);
String[] buttonNames2;
if (fIsClass) {
buttonNames2= new String[] {
/* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.abstract"), //$NON-NLS-1$
/* 1 == FINAL_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.final"), //$NON-NLS-1$
/* 2 */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$
};
fStaticMdfIndex= 2; // index of the static checkbox is 2
} else {
buttonNames2= new String[] {
NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$
};
fStaticMdfIndex= 0; // index of the static checkbox is 0
}
fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4);
fOtherMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false);
fCurrPackageCompletionProcessor= new JavaPackageCompletionProcessor();
fEnclosingTypeCompletionProcessor= new JavaTypeCompletionProcessor(false, false);
fSuperClassCompletionProcessor= new JavaTypeCompletionProcessor(false, false);
fPackageStatus= new StatusInfo();
fEnclosingTypeStatus= new StatusInfo();
fCanModifyPackage= true;
fCanModifyEnclosingType= true;
updateEnableState();
fTypeNameStatus= new StatusInfo();
fSuperClassStatus= new StatusInfo();
fSuperInterfacesStatus= new StatusInfo();
fModifierStatus= new StatusInfo();
}
/**
* Initializes all fields provided by the page with a given selection.
*
* @param elem the selection used to intialize this page or <code>
* null</code> if no selection was available
*/
protected void initTypePage(IJavaElement elem) {
String initSuperclass= "java.lang.Object"; //$NON-NLS-1$
ArrayList initSuperinterfaces= new ArrayList(5);
IPackageFragment pack= null;
IType enclosingType= null;
if (elem != null) {
// evaluate the enclosing type
pack= (IPackageFragment) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
IType typeInCU= (IType) elem.getAncestor(IJavaElement.TYPE);
if (typeInCU != null) {
if (typeInCU.getCompilationUnit() != null) {
enclosingType= typeInCU;
}
} else {
ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
enclosingType= cu.findPrimaryType();
}
}
try {
IType type= null;
if (elem.getElementType() == IJavaElement.TYPE) {
type= (IType)elem;
if (type.exists()) {
String superName= JavaModelUtil.getFullyQualifiedName(type);
if (type.isInterface()) {
initSuperinterfaces.add(superName);
} else {
initSuperclass= superName;
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// ignore this exception now
}
}
String typeName= ""; //$NON-NLS-1$
ITextSelection selection= getCurrentTextSelection();
if (selection != null) {
String text= selection.getText();
if (JavaConventions.validateJavaTypeName(text).isOK()) {
typeName= text;
}
}
setPackageFragment(pack, true);
setEnclosingType(enclosingType, true);
setEnclosingTypeSelection(false, true);
setTypeName(typeName, true);
setSuperClass(initSuperclass, true);
setSuperInterfaces(initSuperinterfaces, true);
}
// -------- UI Creation ---------
/**
* Creates a separator line. Expects a <code>GridLayout</code> with at least 1 column.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSeparator(Composite composite, int nColumns) {
(new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1));
}
/**
* Creates the controls for the package name field. Expects a <code>GridLayout</code> with at
* least 4 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createPackageControls(Composite composite, int nColumns) {
fPackageDialogField.doFillIntoGrid(composite, nColumns);
Text text= fPackageDialogField.getTextControl(null);
LayoutUtil.setWidthHint(text, getMaxFieldWidth());
LayoutUtil.setHorizontalGrabbing(text);
ControlContentAssistHelper.createTextContentAssistant(text, fCurrPackageCompletionProcessor);
}
/**
* Creates the controls for the enclosing type name field. Expects a <code>GridLayout</code> with at
* least 4 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createEnclosingTypeControls(Composite composite, int nColumns) {
// #6891
Composite tabGroup= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
tabGroup.setLayout(layout);
fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1);
Text text= fEnclosingTypeDialogField.getTextControl(composite);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint= getMaxFieldWidth();
gd.horizontalSpan= 2;
text.setLayoutData(gd);
Button button= fEnclosingTypeDialogField.getChangeControl(composite);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.heightHint = SWTUtil.getButtonHeightHint(button);
gd.widthHint = SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
ControlContentAssistHelper.createTextContentAssistant(text, fEnclosingTypeCompletionProcessor);
}
/**
* Creates the controls for the type name field. Expects a <code>GridLayout</code> with at
* least 2 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createTypeNameControls(Composite composite, int nColumns) {
fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1);
DialogField.createEmptySpace(composite);
LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* Creates the controls for the modifiers radio/ceckbox buttons. Expects a
* <code>GridLayout</code> with at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createModifierControls(Composite composite, int nColumns) {
LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1);
Control control= fAccMdfButtons.getSelectionButtonsGroup(composite);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
DialogField.createEmptySpace(composite);
control= fOtherMdfButtons.getSelectionButtonsGroup(composite);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
}
/**
* Creates the controls for the superclass name field. Expects a <code>GridLayout</code>
* with at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSuperClassControls(Composite composite, int nColumns) {
fSuperClassDialogField.doFillIntoGrid(composite, nColumns);
Text text= fSuperClassDialogField.getTextControl(null);
LayoutUtil.setWidthHint(text, getMaxFieldWidth());
ControlContentAssistHelper.createTextContentAssistant(text, fSuperClassCompletionProcessor);
}
/**
* Creates the controls for the superclass name field. Expects a <code>GridLayout</code> with
* at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSuperInterfacesControls(Composite composite, int nColumns) {
fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns);
GridData gd= (GridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData();
if (fIsClass) {
gd.heightHint= convertHeightInCharsToPixels(3);
} else {
gd.heightHint= convertHeightInCharsToPixels(6);
}
gd.grabExcessVerticalSpace= false;
gd.widthHint= getMaxFieldWidth();
}
/**
* Sets the focus on the type name input field.
*/
protected void setFocus() {
fTypeNameDialogField.setFocus();
}
// -------- TypeFieldsAdapter --------
private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter {
// -------- IStringButtonAdapter
public void changeControlPressed(DialogField field) {
typePageChangeControlPressed(field);
}
// -------- IListAdapter
public void customButtonPressed(ListDialogField field, int index) {
typePageCustomButtonPressed(field, index);
}
public void selectionChanged(ListDialogField field) {}
// -------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
typePageDialogFieldChanged(field);
}
public void doubleClicked(ListDialogField field) {
}
}
private void typePageChangeControlPressed(DialogField field) {
if (field == fPackageDialogField) {
IPackageFragment pack= choosePackage();
if (pack != null) {
fPackageDialogField.setText(pack.getElementName());
}
} else if (field == fEnclosingTypeDialogField) {
IType type= chooseEnclosingType();
if (type != null) {
fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
} else if (field == fSuperClassDialogField) {
IType type= chooseSuperType();
if (type != null) {
fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
}
}
private void typePageCustomButtonPressed(DialogField field, int index) {
if (field == fSuperInterfacesDialogField) {
chooseSuperInterfaces();
}
}
/*
* A field on the type has changed. The fields' status and all dependend
* status are updated.
*/
private void typePageDialogFieldChanged(DialogField field) {
String fieldName= null;
if (field == fPackageDialogField) {
fPackageStatus= packageChanged();
updatePackageStatusLabel();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= PACKAGE;
} else if (field == fEnclosingTypeDialogField) {
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSING;
} else if (field == fEnclosingTypeSelection) {
updateEnableState();
boolean isEnclosedType= isEnclosingTypeSelected();
if (!isEnclosedType) {
if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, false);
fAccMdfButtons.setSelection(PROTECTED_INDEX, false);
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
fOtherMdfButtons.setSelection(fStaticMdfIndex, false);
}
}
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType);
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSINGSELECTION;
} else if (field == fTypeNameDialogField) {
fTypeNameStatus= typeNameChanged();
fieldName= TYPENAME;
} else if (field == fSuperClassDialogField) {
fSuperClassStatus= superClassChanged();
fieldName= SUPER;
} else if (field == fSuperInterfacesDialogField) {
fSuperInterfacesStatus= superInterfacesChanged();
fieldName= INTERFACES;
} else if (field == fOtherMdfButtons || field == fAccMdfButtons) {
fModifierStatus= modifiersChanged();
fieldName= MODIFIERS;
} else {
fieldName= METHODS;
}
// tell all others
handleFieldChanged(fieldName);
}
// -------- update message ----------------
/*
* @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String)
*/
protected void handleFieldChanged(String fieldName) {
super.handleFieldChanged(fieldName);
if (fieldName == CONTAINER) {
fPackageStatus= packageChanged();
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fSuperInterfacesStatus= superInterfacesChanged();
}
}
// ---- set / get ----------------
/**
* Returns the text of the package input field.
*
* @return the text of the package input field
*/
public String getPackageText() {
return fPackageDialogField.getText();
}
/**
* Returns the text of the enclosing type input field.
*
* @return the text of the enclosing type input field
*/
public String getEnclosingTypeText() {
return fEnclosingTypeDialogField.getText();
}
/**
* Returns the package fragment corresponding to the current input.
*
* @return a package fragement or <code>null</code> if the input
* could not be resolved.
*/
public IPackageFragment getPackageFragment() {
if (!isEnclosingTypeSelected()) {
return fCurrPackage;
} else {
if (fCurrEnclosingType != null) {
return fCurrEnclosingType.getPackageFragment();
}
}
return null;
}
/**
* Sets the package fragment to the given value. The method updates the model
* and the text of the control.
*
* @param pack the package fragement to be set
* @param canBeModified if <code>true</code> the package fragment is
* editable; otherwise it is read-only.
*/
public void setPackageFragment(IPackageFragment pack, boolean canBeModified) {
fCurrPackage= pack;
fCanModifyPackage= canBeModified;
String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$
fPackageDialogField.setText(str);
updateEnableState();
}
/**
* Returns the enclosing type corresponding to the current input.
*
* @return the enclosing type or <code>null</code> if the enclosing type is
* not selected or the input could not be resolved
*/
public IType getEnclosingType() {
if (isEnclosingTypeSelected()) {
return fCurrEnclosingType;
}
return null;
}
/**
* Sets the enclosing type. The method updates the underlying model
* and the text of the control.
*
* @param type the enclosing type
* @param canBeModified if <code>true</code> the enclosing type field is
* editable; otherwise it is read-only.
*/
public void setEnclosingType(IType type, boolean canBeModified) {
fCurrEnclosingType= type;
fCanModifyEnclosingType= canBeModified;
String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$
fEnclosingTypeDialogField.setText(str);
updateEnableState();
}
/**
* Returns the selection state of the enclosing type checkbox.
*
* @return the seleciton state of the enclosing type checkbox
*/
public boolean isEnclosingTypeSelected() {
return fEnclosingTypeSelection.isSelected();
}
/**
* Sets the enclosing type checkbox's selection state.
*
* @param isSelected the checkbox's selection state
* @param canBeModified if <code>true</code> the enclosing type checkbox is
* modifiable; otherwise it is read-only.
*/
public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) {
fEnclosingTypeSelection.setSelection(isSelected);
fEnclosingTypeSelection.setEnabled(canBeModified);
updateEnableState();
}
/**
* Returns the type name entered into the type input field.
*
* @return the type name
*/
public String getTypeName() {
return fTypeNameDialogField.getText();
}
/**
* Sets the type name input field's text to the given value. Method doesn't update
* the model.
*
* @param name the new type name
* @param canBeModified if <code>true</code> the enclosing type name field is
* editable; otherwise it is read-only.
*/
public void setTypeName(String name, boolean canBeModified) {
fTypeNameDialogField.setText(name);
fTypeNameDialogField.setEnabled(canBeModified);
}
/**
* Returns the selected modifiers.
*
* @return the selected modifiers
* @see Flags
*/
public int getModifiers() {
int mdf= 0;
if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) {
mdf+= F_PUBLIC;
} else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) {
mdf+= F_PRIVATE;
} else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
mdf+= F_PROTECTED;
}
if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) {
mdf+= F_ABSTRACT;
}
if (fOtherMdfButtons.isSelected(FINAL_INDEX)) {
mdf+= F_FINAL;
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
mdf+= F_STATIC;
}
return mdf;
}
/**
* Sets the modifiers.
*
* @param modifiers <code>F_PUBLIC</code>, <code>F_PRIVATE</code>,
* <code>F_PROTECTED</code>, <code>F_ABSTRACT, F_FINAL</code>
* or <code>F_STATIC</code> or, a valid combination.
* @param canBeModified if <code>true</code> the modifier fields are
* editable; otherwise they are read-only
* @see Flags
*/
public void setModifiers(int modifiers, boolean canBeModified) {
if (Flags.isPublic(modifiers)) {
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
} else if (Flags.isPrivate(modifiers)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, true);
} else if (Flags.isProtected(modifiers)) {
fAccMdfButtons.setSelection(PROTECTED_INDEX, true);
} else {
fAccMdfButtons.setSelection(DEFAULT_INDEX, true);
}
if (Flags.isAbstract(modifiers)) {
fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true);
}
if (Flags.isFinal(modifiers)) {
fOtherMdfButtons.setSelection(FINAL_INDEX, true);
}
if (Flags.isStatic(modifiers)) {
fOtherMdfButtons.setSelection(fStaticMdfIndex, true);
}
fAccMdfButtons.setEnabled(canBeModified);
fOtherMdfButtons.setEnabled(canBeModified);
}
/**
* Returns the content of the superclass input field.
*
* @return the superclass name
*/
public String getSuperClass() {
return fSuperClassDialogField.getText();
}
/**
* Sets the super class name.
*
* @param name the new superclass name
* @param canBeModified if <code>true</code> the superclass name field is
* editable; otherwise it is read-only.
*/
public void setSuperClass(String name, boolean canBeModified) {
fSuperClassDialogField.setText(name);
fSuperClassDialogField.setEnabled(canBeModified);
}
/**
* Returns the chosen super interfaces.
*
* @return a list of chosen super interfaces. The list's elements
* are of type <code>String</code>
*/
public List getSuperInterfaces() {
return fSuperInterfacesDialogField.getElements();
}
/**
* Sets the super interfaces.
*
* @param interfacesNames a list of super interface. The method requires that
* the list's elements are of type <code>String</code>
* @param canBeModified if <code>true</code> the super interface field is
* editable; otherwise it is read-only.
*/
public void setSuperInterfaces(List interfacesNames, boolean canBeModified) {
fSuperInterfacesDialogField.setElements(interfacesNames);
fSuperInterfacesDialogField.setEnabled(canBeModified);
}
/**
* Returns the resource handle that corresponds to the compilation unit to was or
* will be created or modified.
* @return A resource or null if the page contains illegal values.
* @since 3.0
*/
public IResource getModifiedResource() {
IType enclosing= getEnclosingType();
if (enclosing != null) {
return enclosing.getResource();
}
IPackageFragment pack= getPackageFragment();
if (pack != null) {
return pack.getCompilationUnit(getTypeName() + ".java").getResource(); //$NON-NLS-1$
}
return null;
}
// ----------- validation ----------
/*
* @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#containerChanged()
*/
protected IStatus containerChanged() {
IStatus status= super.containerChanged();
fCurrPackageCompletionProcessor.setPackageFragmentRoot(getPackageFragmentRoot());
if (getPackageFragmentRoot() != null)
fEnclosingTypeCompletionProcessor.setPackageFragment(getPackageFragmentRoot().getPackageFragment("")); //$NON-NLS-1$
return status;
}
/**
* A hook method that gets called when the package field has changed. The method
* validates the package name and returns the status of the validation. The validation
* also updates the package fragment model.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus packageChanged() {
StatusInfo status= new StatusInfo();
fPackageDialogField.enableButton(getPackageFragmentRoot() != null);
String packName= getPackageText();
if (packName.length() > 0) {
IStatus val= JavaConventions.validatePackageName(packName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$
// continue
}
} else {
status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.DefaultPackageDiscouraged")); //$NON-NLS-1$
}
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root != null) {
if (root.getJavaProject().exists() && packName.length() > 0) {
try {
IPath rootPath= root.getPath();
IPath outputPath= root.getJavaProject().getOutputLocation();
if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
// if the bin folder is inside of our root, dont allow to name a package
// like the bin folder
IPath packagePath= rootPath.append(packName.replace('.', '/'));
if (outputPath.isPrefixOf(packagePath)) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// let pass
}
}
fCurrPackage= root.getPackageFragment(packName);
fSuperClassCompletionProcessor.setPackageFragment(fCurrPackage);
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
/*
* Updates the 'default' label next to the package field.
*/
private void updatePackageStatusLabel() {
String packName= getPackageText();
if (packName.length() == 0) {
fPackageDialogField.setStatus(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$
} else {
fPackageDialogField.setStatus(""); //$NON-NLS-1$
}
}
/*
* Updates the enable state of buttons related to the enclosing type selection checkbox.
*/
private void updateEnableState() {
boolean enclosing= isEnclosingTypeSelected();
fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing);
fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing);
}
/**
* Hook method that gets called when the enclosing type name has changed. The method
* validates the enclosing type and returns the status of the validation. It also updates the
* enclosing type model.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus enclosingTypeChanged() {
StatusInfo status= new StatusInfo();
fCurrEnclosingType= null;
IPackageFragmentRoot root= getPackageFragmentRoot();
fEnclosingTypeDialogField.enableButton(root != null);
if (root == null) {
status.setError(""); //$NON-NLS-1$
return status;
}
String enclName= getEnclosingTypeText();
if (enclName.length() == 0) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeEnterName")); //$NON-NLS-1$
return status;
}
try {
IType type= findType(root.getJavaProject(), enclName);
if (type == null) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$
return status;
}
if (type.getCompilationUnit() == null) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotInCU")); //$NON-NLS-1$
return status;
}
if (!JavaModelUtil.isEditable(type.getCompilationUnit())) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotEditable")); //$NON-NLS-1$
return status;
}
fCurrEnclosingType= type;
IPackageFragmentRoot enclosingRoot= JavaModelUtil.getPackageFragmentRoot(type);
if (!enclosingRoot.equals(root)) {
status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.EnclosingNotInSourceFolder")); //$NON-NLS-1$
}
return status;
} catch (JavaModelException e) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$
JavaPlugin.log(e);
return status;
}
}
/**
* Hook method that gets called when the type name has changed. The method validates the
* type name and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus typeNameChanged() {
StatusInfo status= new StatusInfo();
String typeName= getTypeName();
// must not be empty
if (typeName.length() == 0) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnterTypeName")); //$NON-NLS-1$
return status;
}
if (typeName.indexOf('.') != -1) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.QualifiedName")); //$NON-NLS-1$
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(typeName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$
// continue checking
}
// must not exist
if (!isEnclosingTypeSelected()) {
IPackageFragment pack= getPackageFragment();
if (pack != null) {
ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$
if (cu.getResource().exists()) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
} else {
IType type= getEnclosingType();
if (type != null) {
IType member= type.getType(typeName);
if (member.exists()) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
}
return status;
}
/**
* Hook method that gets called when the superclass name has changed. The method
* validates the superclass name and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus superClassChanged() {
StatusInfo status= new StatusInfo();
IPackageFragmentRoot root= getPackageFragmentRoot();
fSuperClassDialogField.enableButton(root != null);
fSuperClass= null;
String sclassName= getSuperClass();
if (sclassName.length() == 0) {
// accept the empty field (stands for java.lang.Object)
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(sclassName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$
return status;
}
if (root != null) {
try {
IType type= resolveSuperTypeName(root.getJavaProject(), sclassName);
if (type == null) {
status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.SuperClassNotExists")); //$NON-NLS-1$
return status;
} else {
if (type.isInterface()) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$
return status;
}
int flags= type.getFlags();
if (Flags.isFinal(flags)) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$
return status;
} else if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$
return status;
}
}
fSuperClass= type;
} catch (JavaModelException e) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$
JavaPlugin.log(e);
}
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException {
if (!jproject.exists()) {
return null;
}
IType type= null;
if (isEnclosingTypeSelected()) {
// search in the context of the enclosing type
IType enclosingType= getEnclosingType();
if (enclosingType != null) {
String[][] res= enclosingType.resolveType(sclassName);
if (res != null && res.length > 0) {
type= jproject.findType(res[0][0], res[0][1]);
}
}
} else {
IPackageFragment currPack= getPackageFragment();
if (type == null && currPack != null) {
String packName= currPack.getElementName();
// search in own package
if (!currPack.isDefaultPackage()) {
type= jproject.findType(packName, sclassName);
}
// search in java.lang
if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$
type= jproject.findType("java.lang", sclassName); //$NON-NLS-1$
}
}
// search fully qualified
if (type == null) {
type= jproject.findType(sclassName);
}
}
return type;
}
private IType findType(IJavaProject project, String typeName) throws JavaModelException {
if (project.exists()) {
return project.findType(typeName);
}
return null;
}
/**
* Hook method that gets called when the list of super interface has changed. The method
* validates the superinterfaces and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus superInterfacesChanged() {
StatusInfo status= new StatusInfo();
IPackageFragmentRoot root= getPackageFragmentRoot();
fSuperInterfacesDialogField.enableButton(0, root != null);
if (root != null) {
List elements= fSuperInterfacesDialogField.getElements();
int nElements= elements.size();
for (int i= 0; i < nElements; i++) {
String intfname= (String)elements.get(i);
try {
IType type= findType(root.getJavaProject(), intfname);
if (type == null) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$
return status;
} else {
if (type.isClass()) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$
return status;
}
if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// let pass, checking is an extra
}
}
}
return status;
}
/**
* Hook method that gets called when the modifiers have changed. The method validates
* the modifiers and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus modifiersChanged() {
StatusInfo status= new StatusInfo();
int modifiers= getModifiers();
if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$
}
return status;
}
// selection dialogs
private IPackageFragment choosePackage() {
IPackageFragmentRoot froot= getPackageFragmentRoot();
IJavaElement[] packages= null;
try {
if (froot != null && froot.exists()) {
packages= froot.getChildren();
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
if (packages == null) {
packages= new IJavaElement[0];
}
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT));
dialog.setIgnoreCase(false);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.description")); //$NON-NLS-1$
dialog.setEmptyListMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.empty")); //$NON-NLS-1$
dialog.setElements(packages);
IPackageFragment pack= getPackageFragment();
if (pack != null) {
dialog.setInitialSelections(new Object[] { pack });
}
if (dialog.open() == Window.OK) {
return (IPackageFragment) dialog.getFirstResult();
}
return null;
}
private IType chooseEnclosingType() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return null;
}
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { root });
TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.TYPE, scope);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$
dialog.setFilter(Signature.getSimpleName(getEnclosingTypeText()));
if (dialog.open() == Window.OK) {
return (IType) dialog.getFirstResult();
}
return null;
}
private IType chooseSuperType() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return null;
}
IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() };
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);
TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.CLASS, scope);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.message")); //$NON-NLS-1$
dialog.setFilter(getSuperClass());
if (dialog.open() == Window.OK) {
return (IType) dialog.getFirstResult();
}
return null;
}
private void chooseSuperInterfaces() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return;
}
IJavaProject project= root.getJavaProject();
SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project);
dialog.setTitle(fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.class.title") : NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.interface.title")); //$NON-NLS-1$ //$NON-NLS-2$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.message")); //$NON-NLS-1$
dialog.open();
return;
}
// ---- creation ----------------
/**
* Creates the new type using the entered field values.
*
* @param monitor a progress monitor to report progress.
*/
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$
ICompilationUnit createdWorkingCopy= null;
try {
IPackageFragmentRoot root= getPackageFragmentRoot();
IPackageFragment pack= getPackageFragment();
if (pack == null) {
pack= root.getPackageFragment(""); //$NON-NLS-1$
}
if (!pack.exists()) {
String packName= pack.getElementName();
pack= root.createPackageFragment(packName, true, null);
}
monitor.worked(1);
String clName= getTypeName();
boolean isInnerClass= isEnclosingTypeSelected();
IType createdType;
ImportsManager imports;
int indent= 0;
String lineDelimiter= null;
if (!isInnerClass) {
lineDelimiter= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
ICompilationUnit parentCU= pack.createCompilationUnit(clName + ".java", "", false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$ //$NON-NLS-2$
// create a working copy with a new owner
createdWorkingCopy= parentCU.getWorkingCopy(null);
// use the compiler template a first time to read the imports
String content= CodeGeneration.getCompilationUnitContent(createdWorkingCopy, null, "", lineDelimiter); //$NON-NLS-1$
if (content != null) {
createdWorkingCopy.getBuffer().setContents(content);
}
imports= new ImportsManager(createdWorkingCopy);
// add an import that will be removed again. Having this import solves 14661
imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), getTypeName()));
String typeContent= constructTypeStub(imports, lineDelimiter);
String cuContent= constructCUContent(parentCU, typeContent, lineDelimiter);
createdWorkingCopy.getBuffer().setContents(cuContent);
createdType= createdWorkingCopy.getType(clName);
} else {
IType enclosingType= getEnclosingType();
// if we are working on a enclosed type that is open in an editor,
// then replace the enclosing type with its working copy
IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType);
if (workingCopy != null) {
enclosingType= workingCopy;
}
ICompilationUnit parentCU= enclosingType.getCompilationUnit();
imports= new ImportsManager(parentCU);
// add imports that will be removed again. Having the imports solves 14661
IType[] topLevelTypes= parentCU.getTypes();
for (int i= 0; i < topLevelTypes.length; i++) {
imports.addImport(topLevelTypes[i].getFullyQualifiedName('.'));
}
lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType);
StringBuffer content= new StringBuffer();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS)) {
String comment= getTypeComment(parentCU, lineDelimiter);
if (comment != null) {
content.append(comment);
content.append(lineDelimiter);
}
}
content.append(constructTypeStub(imports, lineDelimiter));
IJavaElement[] elems= enclosingType.getChildren();
IJavaElement sibling= elems.length > 0 ? elems[0] : null;
createdType= enclosingType.createType(content.toString(), sibling, false, new SubProgressMonitor(monitor, 1));
indent= StubUtility.getIndentUsed(enclosingType) + 1;
}
// add imports for superclass/interfaces, so types can be resolved correctly
ICompilationUnit cu= createdType.getCompilationUnit();
boolean needsSave= !cu.isWorkingCopy();
imports.create(needsSave, new SubProgressMonitor(monitor, 1));
JavaModelUtil.reconcile(cu);
createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1));
// add imports
imports.create(needsSave, new SubProgressMonitor(monitor, 1));
if (removeUnused(cu, imports)) {
imports.create(needsSave, null);
}
JavaModelUtil.reconcile(cu);
ISourceRange range= createdType.getSourceRange();
IBuffer buf= cu.getBuffer();
String originalContent= buf.getText(range.getOffset(), range.getLength());
String formattedContent= CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, indent, null, lineDelimiter, pack.getJavaProject());
buf.replace(range.getOffset(), range.getLength(), formattedContent);
if (!isInnerClass) {
String fileComment= getFileComment(cu);
if (fileComment != null && fileComment.length() > 0) {
buf.replace(0, 0, fileComment + lineDelimiter);
}
cu.commitWorkingCopy(false, new SubProgressMonitor(monitor, 1));
} else {
if (needsSave) {
buf.save(null, false);
}
monitor.worked(1);
}
if (createdWorkingCopy != null) {
fCreatedType= (IType) createdType.getPrimaryElement();
} else {
fCreatedType= createdType;
}
} finally {
if (createdWorkingCopy != null) {
createdWorkingCopy.discardWorkingCopy();
}
monitor.done();
}
}
private boolean removeUnused(ICompilationUnit cu, ImportsManager imports) {
ASTParser parser= ASTParser.newParser(AST.LEVEL_2_0);
parser.setSource(cu);
parser.setResolveBindings(true);
CompilationUnit root= (CompilationUnit) parser.createAST(null);
IProblem[] problems= root.getProblems();
boolean importRemoved= false;
for (int i= 0; i < problems.length; i++) {
if (problems[i].getID() == IProblem.UnusedImport) {
String imp= problems[i].getArguments()[0];
imports.removeImport(imp);
importRemoved=true;
}
}
return importRemoved;
}
/**
* Uses the New Java file template from the code template page to generate a
* compilation unit with the given type content.
* @param cu The new created compilation unit
* @param typeContent The content of the type, including signature and type
* body.
* @param lineDelimiter The line delimiter to be used.
* @return String Returns the result of evaluating the new file template
* with the given type content.
* @throws CoreException
* @since 2.1
*/
protected String constructCUContent(ICompilationUnit cu, String typeContent, String lineDelimiter) throws CoreException {
String typeComment= getTypeComment(cu, lineDelimiter);
IPackageFragment pack= (IPackageFragment) cu.getParent();
String content= CodeGeneration.getCompilationUnitContent(cu, typeComment, typeContent, lineDelimiter);
if (content != null) {
ASTParser parser= ASTParser.newParser(AST.LEVEL_2_0);
parser.setSource(content.toCharArray());
CompilationUnit unit= (CompilationUnit) parser.createAST(null);
if ((pack.isDefaultPackage() || unit.getPackage() != null) && !unit.types().isEmpty()) {
return content;
}
}
StringBuffer buf= new StringBuffer();
if (!pack.isDefaultPackage()) {
buf.append("package ").append(pack.getElementName()).append(';'); //$NON-NLS-1$
}
buf.append(lineDelimiter).append(lineDelimiter);
if (typeComment != null) {
buf.append(typeComment).append(lineDelimiter);
}
buf.append(typeContent);
return buf.toString();
}
/**
* Returns the created type. The method only returns a valid type
* after <code>createType</code> has been called.
*
* @return the created type
* @see #createType(IProgressMonitor)
*/
public IType getCreatedType() {
return fCreatedType;
}
// ---- construct cu body----------------
private void writeSuperClass(StringBuffer buf, ImportsManager imports) {
String typename= getSuperClass();
if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$
buf.append(" extends "); //$NON-NLS-1$
String qualifiedName= fSuperClass != null ? JavaModelUtil.getFullyQualifiedName(fSuperClass) : typename;
buf.append(imports.addImport(qualifiedName));
}
}
private void writeSuperInterfaces(StringBuffer buf, ImportsManager imports) {
List interfaces= getSuperInterfaces();
int last= interfaces.size() - 1;
if (last >= 0) {
if (fIsClass) {
buf.append(" implements "); //$NON-NLS-1$
} else {
buf.append(" extends "); //$NON-NLS-1$
}
for (int i= 0; i <= last; i++) {
String typename= (String) interfaces.get(i);
buf.append(imports.addImport(typename));
if (i < last) {
buf.append(',');
}
}
}
}
/*
* Called from createType to construct the source for this type
*/
private String constructTypeStub(ImportsManager imports, String lineDelimiter) {
StringBuffer buf= new StringBuffer();
int modifiers= getModifiers();
buf.append(Flags.toString(modifiers));
if (modifiers != 0) {
buf.append(' ');
}
buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$
buf.append(getTypeName());
writeSuperClass(buf, imports);
writeSuperInterfaces(buf, imports);
buf.append('{');
buf.append(lineDelimiter);
buf.append(lineDelimiter);
buf.append('}');
buf.append(lineDelimiter);
return buf.toString();
}
/**
* Hook method that gets called from <code>createType</code> to support adding of
* unanticipated methods, fields, and inner types to the created type.
* <p>
* Implementers can use any methods defined on <code>IType</code> to manipulate the
* new type.
* </p>
* <p>
* The source code of the new type will be formtted using the platform's formatter. Needed
* imports are added by the wizard at the end of the type creation process using the given
* import manager.
* </p>
*
* @param newType the new type created via <code>createType</code>
* @param imports an import manager which can be used to add new imports
* @param monitor a progress monitor to report progress. Must not be <code>null</code>
*
* @see #createType(IProgressMonitor)
*/
protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
// default implementation does nothing
// example would be
// String mainMathod= "public void foo(Vector vec) {}"
// createdType.createMethod(main, null, false, null);
// imports.addImport("java.lang.Vector");
}
/**
* @deprecated Instead of file templates, the new type code template
* specifies the stub for a compilation unit.
*/
protected String getFileComment(ICompilationUnit parentCU) {
return null;
}
private boolean isValidComment(String template) {
IScanner scanner= ToolFactory.createScanner(true, false, false, false);
scanner.setSource(template.toCharArray());
try {
int next= scanner.getNextToken();
while (TokenScanner.isComment(next)) {
next= scanner.getNextToken();
}
return next == ITerminalSymbols.TokenNameEOF;
} catch (InvalidInputException e) {
}
return false;
}
/**
* Hook method that gets called from <code>createType</code> to retrieve
* a type comment. This default implementation returns the content of the
* 'type comment' template.
*
* @return the type comment or <code>null</code> if a type comment
* is not desired
*/
protected String getTypeComment(ICompilationUnit parentCU, String lineDelimiter) {
try {
StringBuffer typeName= new StringBuffer();
if (isEnclosingTypeSelected()) {
typeName.append(JavaModelUtil.getTypeQualifiedName(getEnclosingType())).append('.');
}
typeName.append(getTypeName());
String comment= CodeGeneration.getTypeComment(parentCU, typeName.toString(), lineDelimiter);
if (comment != null && isValidComment(comment)) {
return comment;
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
return null;
}
/**
* @deprecated Use getTypeComment(ICompilationUnit, String)
*/
protected String getTypeComment(ICompilationUnit parentCU) {
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS)) {
return getTypeComment(parentCU, String.valueOf('\n'));
}
return null;
}
/**
* @deprecated Use getTemplate(String,ICompilationUnit,int)
*/
protected String getTemplate(String name, ICompilationUnit parentCU) {
return getTemplate(name, parentCU, 0);
}
/**
* Returns the string resulting from evaluation the given template in
* the context of the given compilation unit. This accesses the normal
* template page, not the code templates. To use code templates use
* <code>constructCUContent</code> to construct a compilation unit stub or
* getTypeComment for the comment of the type.
*
* @param name the template to be evaluated
* @param parentCU the templates evaluation context
* @param pos a source offset into the parent compilation unit. The
* template is evalutated at the given source offset
*/
protected String getTemplate(String name, ICompilationUnit parentCU, int pos) {
try {
Template[] templates= Templates.getInstance().getTemplates(name);
if (templates.length > 0) {
return JavaContext.evaluateTemplate(templates[0], parentCU, pos);
}
} catch (CoreException e) {
JavaPlugin.log(e);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return null;
}
/**
* Creates the bodies of all unimplemented methods and constructors and adds them to the type.
* Method is typically called by implementers of <code>NewTypeWizardPage</code> to add
* needed method and constructors.
*
* @param type the type for which the new methods and constructor are to be created
* @param doConstructors if <code>true</code> unimplemented constructors are created
* @param doUnimplementedMethods if <code>true</code> unimplemented methods are created
* @param imports an import manager to add all neded import statements
* @param monitor a progress monitor to report progress
*/
protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
ArrayList newMethods= new ArrayList();
ITypeHierarchy hierarchy= null;
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (doConstructors) {
hierarchy= type.newSupertypeHierarchy(monitor);
IType superclass= hierarchy.getSuperclass(type);
if (superclass != null) {
String[] constructors= StubUtility.evalConstructors(type, superclass, settings, imports.getImportsStructure());
if (constructors != null) {
for (int i= 0; i < constructors.length; i++) {
newMethods.add(constructors[i]);
}
}
}
}
if (doUnimplementedMethods) {
if (hierarchy == null) {
hierarchy= type.newSupertypeHierarchy(monitor);
}
String[] unimplemented= StubUtility.evalUnimplementedMethods(type, hierarchy, false, settings, imports.getImportsStructure());
if (unimplemented != null) {
for (int i= 0; i < unimplemented.length; i++) {
newMethods.add(unimplemented[i]);
}
}
}
IMethod[] createdMethods= new IMethod[newMethods.size()];
for (int i= 0; i < newMethods.size(); i++) {
String content= (String) newMethods.get(i) + '\n'; // content will be formatted, ok to use \n
createdMethods[i]= type.createMethod(content, null, false, null);
}
return createdMethods;
}
// ---- creation ----------------
/**
* Returns the runnable that creates the type using the current settings.
* The returned runnable must be executed in the UI thread.
*
* @return the runnable to create the new type
*/
public IRunnableWithProgress getRunnable() {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
createType(monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
}
}
|
49,041 |
Bug 49041 Search context menu not available [search]
|
In 12162000 the search menu entry seems to be gone from everywhere. I can't search for implementors, declarations, ... in my Java code. This is a mainline workflow. The menu bar entry doesn't cut it as it involves too much context shift.
|
resolved fixed
|
74947cf
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-19T14:32:55Z | 2003-12-17T16:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/JavaSearchActionGroup.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.actions;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.part.Page;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.jdt.internal.ui.actions.FindExceptionOccurrences;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.preferences.WorkInProgressPreferencePage;
import org.eclipse.jdt.internal.ui.search.SearchMessages;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.PreferenceConstants;
/**
* Action group that adds the Java search actions to a context menu and
* the global menu bar.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class JavaSearchActionGroup extends ActionGroup {
private JavaEditor fEditor;
private IWorkbenchSite fSite;
private ReferencesSearchGroup fReferencesGroup;
private ReadReferencesSearchGroup fReadAccessGroup;
private WriteReferencesSearchGroup fWriteAccessGroup;
private DeclarationsSearchGroup fDeclarationsGroup;
private ImplementorsSearchGroup fImplementorsGroup;
private FindOccurrencesInFileAction fOccurrencesInFileAction;
private FindExceptionOccurrences fExceptionOriginatorsAction;
/**
* Creates a new <code>JavaSearchActionGroup</code>. The group
* requires that the selection provided by the part's selection provider
* is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param part the view part that owns this action group
*/
public JavaSearchActionGroup(IViewPart part) {
this(part.getViewSite());
fOccurrencesInFileAction= new FindOccurrencesInFileAction(part);
part.getViewSite().getSelectionProvider().addSelectionChangedListener(fOccurrencesInFileAction);
}
/**
* Creates a new <code>JavaSearchActionGroup</code>. The group
* requires that the selection provided by the page's selection provider
* is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param page the page that owns this action group
*/
public JavaSearchActionGroup(Page page) {
this(page.getSite());
fOccurrencesInFileAction= new FindOccurrencesInFileAction(page);
page.getSite().getSelectionProvider().addSelectionChangedListener(fOccurrencesInFileAction);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public JavaSearchActionGroup(JavaEditor editor) {
Assert.isNotNull(editor);
fEditor= editor;
fSite= fEditor.getSite();
fReferencesGroup= new ReferencesSearchGroup(fEditor);
fReadAccessGroup= new ReadReferencesSearchGroup(fEditor);
fWriteAccessGroup= new WriteReferencesSearchGroup(fEditor);
fDeclarationsGroup= new DeclarationsSearchGroup(fEditor);
fImplementorsGroup= new ImplementorsSearchGroup(fEditor);
fOccurrencesInFileAction= new FindOccurrencesInFileAction(fEditor);
fExceptionOriginatorsAction= new FindExceptionOccurrences(fEditor);
}
private JavaSearchActionGroup(IWorkbenchSite site) {
fReferencesGroup= new ReferencesSearchGroup(site);
fReadAccessGroup= new ReadReferencesSearchGroup(site);
fWriteAccessGroup= new WriteReferencesSearchGroup(site);
fDeclarationsGroup= new DeclarationsSearchGroup(site);
fImplementorsGroup= new ImplementorsSearchGroup(site);
fSite= site;
}
/*
* Method declared on ActionGroup.
*/
public void setContext(ActionContext context) {
fReferencesGroup.setContext(context);
fDeclarationsGroup.setContext(context);
fImplementorsGroup.setContext(context);
fReadAccessGroup.setContext(context);
fWriteAccessGroup.setContext(context);
}
/*
* Method declared on ActionGroup.
*/
public void fillActionBars(IActionBars actionBar) {
super.fillActionBars(actionBar);
fReferencesGroup.fillActionBars(actionBar);
fDeclarationsGroup.fillActionBars(actionBar);
fImplementorsGroup.fillActionBars(actionBar);
fReadAccessGroup.fillActionBars(actionBar);
fWriteAccessGroup.fillActionBars(actionBar);
actionBar.setGlobalActionHandler(JdtActionConstants.FIND_OCCURRENCES_IN_FILE, fOccurrencesInFileAction);
actionBar.setGlobalActionHandler(JdtActionConstants.FIND_EXCEPTION_OCCURRENCES, fExceptionOriginatorsAction);
}
/*
* Method declared on ActionGroup.
*/
public void fillContextMenu(IMenuManager menu) {
super.fillContextMenu(menu);
if(PreferenceConstants.getPreferenceStore().getBoolean(WorkInProgressPreferencePage.PREF_SEARCH_MENU)) {
fReferencesGroup.fillContextMenu(menu);
} else {
IMenuManager target= menu;
IMenuManager searchSubMenu= null;
if (fEditor != null) {
String groupName= SearchMessages.getString("group.search"); //$NON-NLS-1$
searchSubMenu= new MenuManager(groupName, ITextEditorActionConstants.GROUP_FIND);
searchSubMenu.add(new GroupMarker(ITextEditorActionConstants.GROUP_FIND));
target= searchSubMenu;
}
fReferencesGroup.fillContextMenu(target);
fDeclarationsGroup.fillContextMenu(target);
fImplementorsGroup.fillContextMenu(target);
fReadAccessGroup.fillContextMenu(target);
fWriteAccessGroup.fillContextMenu(target);
if (searchSubMenu != null) {
searchSubMenu.add(new Separator());
addAction(target, fOccurrencesInFileAction);
} else {
addAction(target, IContextMenuConstants.GROUP_SEARCH, fOccurrencesInFileAction);
}
// no other way to find out if we have added items.
if (searchSubMenu != null && searchSubMenu.getItems().length > 2) {
menu.appendToGroup(ITextEditorActionConstants.GROUP_FIND, searchSubMenu);
}
}
}
/*
* Method declared on ActionGroup.
*/
public void dispose() {
fReferencesGroup.dispose();
fDeclarationsGroup.dispose();
fImplementorsGroup.dispose();
fReadAccessGroup.dispose();
fWriteAccessGroup.dispose();
if (fOccurrencesInFileAction != null)
fSite.getSelectionProvider().removeSelectionChangedListener(fOccurrencesInFileAction);
super.dispose();
}
private void addAction(IMenuManager manager, IAction action) {
if (action != null && action.isEnabled())
manager.add(action);
}
private void addAction(IMenuManager manager, String group, IAction action) {
if (action != null && action.isEnabled())
manager.appendToGroup(group, action);
}
}
|
37,594 |
Bug 37594 Quick fix for 'hidden variable'
|
When you get the compiler warning stating that you have a local variable in a method which is over-riding a field in your class, I would like to have the QuickFix option to rename the local variable and all its occurences in the method.
|
resolved fixed
|
4c8ff5d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-19T15:23:20Z | 2003-05-14T13:46:40Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.tests.core.ProjectTestSetup;
import org.eclipse.jdt.internal.corext.template.java.CodeTemplates;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal;
public class LocalCorrectionsQuickFixTest extends QuickFixTest {
private static final Class THIS= LocalCorrectionsQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public LocalCorrectionsQuickFixTest(String name) {
super(name);
}
public static Test allTests() {
return new ProjectTestSetup(new TestSuite(THIS));
}
public static Test suite() {
if (true) {
return allTests();
} else {
TestSuite suite= new TestSuite();
suite.addTest(new LocalCorrectionsQuickFixTest("testUnnecessaryThrownException3"));
return new ProjectTestSetup(suite);
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4");
options.put(JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER, JavaCore.ERROR);
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false);
CodeTemplates.getCodeTemplate(CodeTemplates.CATCHBLOCK).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.CONSTRUCTORSTUB).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.METHODSTUB).setPattern("");
fJProject1= ProjectTestSetup.getProject();
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.clear(fJProject1, ProjectTestSetup.getDefaultClasspath());
}
public void testFieldAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return (new File(\"x.txt\")).separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return File.separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testInheritedAccessOnStatic() throws Exception {
IPackageFragment pack0= fSourceFolder.createPackageFragment("pack", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class A {\n");
buf.append(" public static void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
pack0.createCompilationUnit("A.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class B extends A {\n");
buf.append("}\n");
pack0.createCompilationUnit("B.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" b.foo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" B.foo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.A;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" A.foo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class A {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testQualifiedAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" t.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" Thread.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testThisAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" E.goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testThisAccessToStaticField() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static int fCount;\n");
buf.append("\n");
buf.append(" public void foo() {\n");
buf.append(" this.fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static int fCount;\n");
buf.append("\n");
buf.append(" public void foo() {\n");
buf.append(" E.fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int fCount;\n");
buf.append("\n");
buf.append(" public void foo() {\n");
buf.append(" this.fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInVarDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= o;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= (Thread) o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Object th= o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInVarDecl2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class Container {\n");
buf.append(" public List[] getLists() {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("Container.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= (ArrayList[]) c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" List[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInVarDecl3() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" Thread th= foo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 0);
}
public void testCastMissingInFieldDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= System.currentTimeMillis();\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= (int) System.currentTimeMillis();\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" long time= System.currentTimeMillis();\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInAssignment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= (String) iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCastMissingInExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return (String[]) list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public Object[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastOnCastExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (ArrayList) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" Cloneable a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo().substring(2);\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtExceptionRemoveMoreSpecific() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" try {\n");
buf.append(" this.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtExceptionToSurroundingTry() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() throws IOException, ParseException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" E.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() throws IOException, ParseException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws ParseException {\n");
buf.append(" try {\n");
buf.append(" E.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() throws IOException, ParseException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" try {\n");
buf.append(" E.goo();\n");
buf.append(" } catch (ParseException e1) {\n");
buf.append(" }\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() throws IOException, ParseException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" E.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testUncaughtExceptionOnSuper1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.FileInputStream;\n");
buf.append("public class E extends FileInputStream {\n");
buf.append(" public E() {\n");
buf.append(" super(\"x\");\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.FileInputStream;\n");
buf.append("import java.io.FileNotFoundException;\n");
buf.append("public class E extends FileInputStream {\n");
buf.append(" public E() throws FileNotFoundException {\n");
buf.append(" super(\"x\");\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUncaughtExceptionOnSuper2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append(" public A() throws Exception {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public E() {\n");
buf.append(" super();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public E() throws Exception {\n");
buf.append(" super();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUncaughtExceptionOnThis() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" this(null);\n");
buf.append(" }\n");
buf.append(" public E(Object x) throws IOException {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public E() throws IOException {\n");
buf.append(" this(null);\n");
buf.append(" }\n");
buf.append(" public E(Object x) throws IOException {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
boolean BUG_25417= true;
public void testUncaughtExceptionDuplicate() throws Exception {
if (BUG_25417) {
return;
}
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class MyException extends Exception {\n");
buf.append("}\n");
pack1.createCompilationUnit("MyException.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot, 2); // 2 uncaught exceptions
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException, ParseException, MyException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" try {\n");
buf.append(" m2();\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" } catch (MyException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testMultipleUncaughtExceptions() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot, 2); // 2 uncaught exceptions
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException, ParseException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnneededCatchBlock() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws ParseException {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnneededCatchBlockSingle() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnneededCatchBlockBug47221() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public Object foo() {\n");
buf.append(" try {\n");
buf.append(" Object o= null;\n");
buf.append(" return o;\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public Object foo() {\n");
buf.append(" Object o= null;\n");
buf.append(" return o;\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public Object foo() throws IOException {\n");
buf.append(" Object o= null;\n");
buf.append(" return o;\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnneededCatchBlockWithFinally() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnimplementedMethods() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public abstract class E implements Inter{\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append("\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnimplementedMethods2() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public abstract class InterImpl implements Inter {\n");
buf.append(" protected abstract int[] getMusic() throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("InterImpl.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot, 2);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public abstract class E extends InterImpl {\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append("\n");
buf.append(" protected int[] getMusic() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnitializedVariable() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int s;\n");
buf.append(" try {\n");
buf.append(" s= 1;\n");
buf.append(" } catch (Exception e) {\n");
buf.append(" System.out.println(s);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int s = 0;\n");
buf.append(" try {\n");
buf.append(" s= 1;\n");
buf.append(" } catch (Exception e) {\n");
buf.append(" System.out.println(s);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUndefinedConstructorInDefaultConstructor1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" public F(Runnable runnable) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(Runnable runnable) {\n");
buf.append(" super(runnable);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUndefinedConstructorInDefaultConstructor2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class F {\n");
buf.append(" public F(Runnable runnable) throws IOException {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public F(int i, Runnable runnable) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(int i, Runnable runnable) {\n");
buf.append(" super(i, runnable);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(Runnable runnable) throws IOException {\n");
buf.append(" super(runnable);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUndefinedConstructorWithEnclosing1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" public class SubF {\n");
buf.append(" public SubF(int i) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public class SubE extends F.SubF {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public class SubE extends F.SubF {\n");
buf.append("\n");
buf.append(" public SubE(F f, int i) {\n");
buf.append(" f.super(i);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUndefinedConstructorWithEnclosing2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" public static class SubF {\n");
buf.append(" public SubF(int i) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public class SubE extends F.SubF {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public class SubE extends F.SubF {\n");
buf.append("\n");
buf.append(" public SubE(int i) {\n");
buf.append(" super(i);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUndefinedConstructorWithEnclosing3() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" public static class SubF {\n");
buf.append(" public SubF(int i) {\n");
buf.append(" }\n");
buf.append(" public class SubF2 extends SubF {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("F.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" public static class SubF {\n");
buf.append(" public SubF(int i) {\n");
buf.append(" }\n");
buf.append(" public class SubF2 extends SubF {\n");
buf.append("\n");
buf.append(" public SubF2(int i) {\n");
buf.append(" super(i);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testNotVisibleConstructorInDefaultConstructor() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" private F() {\n");
buf.append(" }\n");
buf.append(" public F(Runnable runnable) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(Runnable runnable) {\n");
buf.append(" super(runnable);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnhandledExceptionInDefaultConstructor() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class F {\n");
buf.append(" public F() throws IOException{\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E() throws IOException {\n");
buf.append(" super();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateField() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int fCount;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateField1() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int fCount, fColor= fCount;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int fCount;\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateField2() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int fCount= 0;\n");
buf.append(" public void foo() {\n");
buf.append(" fCount= 1 + 2;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedVariable() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" boolean res= process();\n");
buf.append(" res= (super.hashCode() == 1);\n");
buf.append(" }\n");
buf.append(" public boolean process() {\n");
buf.append(" return true;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" res= (super.hashCode() == 1);\n");
buf.append(" }\n");
buf.append(" public boolean process() {\n");
buf.append(" return true;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedVariable1() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private Object[] foo() {\n");
buf.append(" Object[] i, j= new Object[0];\n");
buf.append(" i= j = null;\n");
buf.append(" i= (new Object[] { null, null });\n");
buf.append(" return j;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private Object[] foo() {\n");
buf.append(" Object[] j= new Object[0];\n");
buf.append(" j = null;\n");
buf.append(" return j;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedVariable2() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private void foo() {\n");
buf.append(" for (int j= 0, i= 0; i < 3; i++) {\n");
buf.append(" j= i;\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private void foo() {\n");
buf.append(" for (int i= 0; i < 3; i++) {\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedVariable4() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" /**\n");
buf.append(" * @param i\n");
buf.append(" */\n");
buf.append(" private void foo(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" /**\n");
buf.append(" */\n");
buf.append(" private void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedParam() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private void foo(Object str) {\n");
buf.append(" {\n");
buf.append(" str= toString();\n");
buf.append(" str= new String[] { toString(), toString() };\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private void foo() {\n");
buf.append(" {\n");
buf.append(" str= toString();\n");
buf.append(" str= new String[] { toString(), toString() };\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateMethod() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int fCount;\n");
buf.append(" \n");
buf.append(" private void foo() {\n");
buf.append(" fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int fCount;\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateConstructor() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" private E(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateType() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private class F {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnnecessaryCast1() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s = (int) i;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s = i;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnnecessaryCast2() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" String r = ((String) s);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" String r = s;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnnecessaryCast3() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s = ((int) 1 + 2) * 3;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s = (1 + 2) * 3;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testSuperfluousSemicolon() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_SUPERFLUOUS_SEMICOLON, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s= 1;;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s= 1;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testIndirectStaticAccess1() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_INDIRECT_STATIC_ACCESS, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment other= fSourceFolder.createPackageFragment("other", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package other;\n");
buf.append("public class A {\n");
buf.append(" public static final int CONST=1;\n");
buf.append("}\n");
other.createCompilationUnit("A.java", buf.toString(), false, null);
IPackageFragment pack0= fSourceFolder.createPackageFragment("pack", false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class B extends other.A {\n");
buf.append("}\n");
pack0.createCompilationUnit("B.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public int foo(B b) {\n");
buf.append(" return B.CONST;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import other.A;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public int foo(B b) {\n");
buf.append(" return A.CONST;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testIndirectStaticAccess2() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_INDIRECT_STATIC_ACCESS, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment other= fSourceFolder.createPackageFragment("other", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package other;\n");
buf.append("public class A {\n");
buf.append(" public static int foo() {\n");
buf.append(" return 1;\n");
buf.append(" }\n");
buf.append("}\n");
other.createCompilationUnit("A.java", buf.toString(), false, null);
IPackageFragment pack0= fSourceFolder.createPackageFragment("pack", false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class B extends other.A {\n");
buf.append("}\n");
pack0.createCompilationUnit("B.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int foo() {\n");
buf.append(" return pack.B.foo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import other.A;\n");
buf.append("\n");
buf.append("public class E {\n");
buf.append(" public int foo() {\n");
buf.append(" return A.foo();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testIndirectStaticAccess_bug40880() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_INDIRECT_STATIC_ACCESS, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("class FileType {\n");
buf.append(" public String extension;\n");
buf.append("}\n");
pack1.createCompilationUnit("FileType.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("interface ToolConfigurationSettingsConstants {\n");
buf.append(" FileType FILE_TYPE = null;\n");
buf.append("}\n");
pack1.createCompilationUnit("ToolConfigurationSettingsConstants.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("interface ToolUserSettingsConstants extends ToolConfigurationSettingsConstants {\n");
buf.append("}\n");
pack1.createCompilationUnit("ToolUserSettingsConstants.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" ToolUserSettingsConstants.FILE_TYPE.extension.toLowerCase();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" ToolConfigurationSettingsConstants.FILE_TYPE.extension.toLowerCase();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testIndirectStaticAccess_bug32022() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_INDIRECT_STATIC_ACCESS, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class StaticField {\n");
buf.append(" public boolean flag;\n");
buf.append("}\n");
pack1.createCompilationUnit("StaticField.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class ConstClass {\n");
buf.append(" public static StaticField staticField = new StaticField();\n");
buf.append("}\n");
pack1.createCompilationUnit("ConstClass.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(ConstClass constclass) {\n");
buf.append(" constclass.staticField.flag= true;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(ConstClass constclass) {\n");
buf.append(" ConstClass.staticField.flag= true;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class ConstClass {\n");
buf.append(" public StaticField staticField = new StaticField();\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnnecessaryInstanceof1() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public boolean foo(String b) {\n");
buf.append(" return (b instanceof String);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public boolean foo(String b) {\n");
buf.append(" return (b != null);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnnecessaryInstanceof2() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String b) {\n");
buf.append(" if (b instanceof String && b.getClass() != null) {\n");
buf.append(" System.out.println();\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String b) {\n");
buf.append(" if (b != null && b.getClass() != null) {\n");
buf.append(" System.out.println();\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnnecessaryThrownException1() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String b) throws IOException {\n");
buf.append(" if (b != null) {\n");
buf.append(" System.out.println();\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String b) {\n");
buf.append(" if (b != null) {\n");
buf.append(" System.out.println();\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnnecessaryThrownException2() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) throws IOException, ParseException {\n");
buf.append(" if (i == 0) {\n");
buf.append(" throw new IOException();\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) throws IOException {\n");
buf.append(" if (i == 0) {\n");
buf.append(" throw new IOException();\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnnecessaryThrownException3() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" /**\n");
buf.append(" * @param i\n");
buf.append(" * @throws IOException\n");
buf.append(" * @throws ParseException\n");
buf.append(" */\n");
buf.append(" public void foo(int i) throws IOException, ParseException {\n");
buf.append(" if (i == 0) {\n");
buf.append(" throw new IOException();\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" /**\n");
buf.append(" * @param i\n");
buf.append(" * @throws IOException\n");
buf.append(" */\n");
buf.append(" public void foo(int i) throws IOException {\n");
buf.append(" if (i == 0) {\n");
buf.append(" throw new IOException();\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnqualifiedFieldAccess1() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNQUALIFIED_FIELD_ACCESS, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int count;\n");
buf.append(" public E(int i) {\n");
buf.append(" count= i;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int count;\n");
buf.append(" public E(int i) {\n");
buf.append(" this.count= i;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnqualifiedFieldAccess2() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNQUALIFIED_FIELD_ACCESS, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" public int count;\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private F f= new F();\n");
buf.append(" public E(int i) {\n");
buf.append(" f.count= i;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private F f= new F();\n");
buf.append(" public E(int i) {\n");
buf.append(" this.f.count= i;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnqualifiedFieldAccess3() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNQUALIFIED_FIELD_ACCESS, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" public void setCount(int i) {}\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private F f= new F();\n");
buf.append(" public E(int i) {\n");
buf.append(" f.setCount(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private F f= new F();\n");
buf.append(" public E(int i) {\n");
buf.append(" this.f.setCount(i);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnqualifiedFieldAccess4() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNQUALIFIED_FIELD_ACCESS, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int count;\n");
buf.append(" public E(int i) {\n");
buf.append(" class Inner {\n");
buf.append(" public void foo() {\n");
buf.append(" count= 1;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= getASTRoot(cu);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOfProposals(proposals, 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int count;\n");
buf.append(" public E(int i) {\n");
buf.append(" class Inner {\n");
buf.append(" public void foo() {\n");
buf.append(" E.this.count= 1;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
}
|
37,594 |
Bug 37594 Quick fix for 'hidden variable'
|
When you get the compiler warning stating that you have a local variable in a method which is over-riding a field in your class, I would like to have the QuickFix option to rename the local variable and all its occurences in the method.
|
resolved fixed
|
4c8ff5d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-19T15:23:20Z | 2003-05-14T13:46:40Z |
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 java.util.Arrays;
import java.util.Comparator;
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.jface.text.link.LinkedEnvironment;
import org.eclipse.jface.text.link.LinkedPositionGroup;
import org.eclipse.jface.text.link.LinkedUIControl;
import org.eclipse.ui.texteditor.link.EditorHistoryUpdater;
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.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
/**
* 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, final int offset) {
try {
// create full ast
CompilationUnit root= AST.parseCompilationUnit(fCompilationUnit, true, null, null); // full AST needed
ASTNode nameNode= NodeFinder.perform(root, fNode.getStartPosition(), fNode.getLength());
ASTNode[] sameNodes;
if (nameNode instanceof SimpleName) {
sameNodes= LinkedNodeFinder.findByNode(root, (SimpleName) nameNode);
} else {
sameNodes= new ASTNode[] { nameNode };
}
// sort for iteration order, starting with the node @ offset
Arrays.sort(sameNodes, new Comparator() {
public int compare(Object o1, Object o2) {
return rank((ASTNode) o1) - rank((ASTNode) o2);
}
/**
* Returns the absolute rank of an <code>ASTNode</code>. Nodes
* preceding <code>offset</code> are ranked last.
*
* @param node the node to compute the rank for
* @return the rank of the node with respect to the invocation offset
*/
private int rank(ASTNode node) {
int relativeRank= node.getStartPosition() + node.getLength() - offset;
if (relativeRank < 0)
return Integer.MAX_VALUE + relativeRank;
else
return relativeRank;
}
});
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);
}
LinkedEnvironment enviroment= new LinkedEnvironment();
enviroment.addGroup(group);
enviroment.forceInstall();
LinkedUIControl ui= new LinkedUIControl(enviroment, viewer);
ui.setPositionListener(new EditorHistoryUpdater());
// ui.setInitialOffset(offset);
ui.setExitPosition(viewer, offset, 0, LinkedPositionGroup.NO_STOP);
ui.enter();
fSelectedRegion= ui.getSelectedRegion();
} catch (BadLocationException e) {
JavaPlugin.log(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;
}
}
|
37,594 |
Bug 37594 Quick fix for 'hidden variable'
|
When you get the compiler warning stating that you have a local variable in a method which is over-riding a field in your class, I would like to have the QuickFix option to rename the local variable and all its occurences in the method.
|
resolved fixed
|
4c8ff5d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-19T15:23:20Z | 2003-05-14T13:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Renaud Waldura <[email protected]> - Access to static proposal
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.Collection;
import java.util.List;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.core.dom.PrimitiveType.Code;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.java.IInvocationContext;
import org.eclipse.jdt.ui.text.java.IProblemLocation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportRewrite;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.corext.dom.ListRewriter;
import org.eclipse.jdt.internal.corext.dom.NewASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Selection;
import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSUtil;
import org.eclipse.jdt.internal.corext.refactoring.surround.ExceptionAnalyzer;
import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter;
import org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizard;
/**
*/
public class LocalCorrectionsSubProcessor {
public static void addCastProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
String[] args= problem.getProblemArguments();
if (args.length != 2) {
return;
}
ICompilationUnit cu= context.getCompilationUnit();
String castType= args[1];
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveredNode(astRoot);
if (!(selectedNode instanceof Expression)) {
return;
}
Expression nodeToCast= (Expression) selectedNode;
int parentNodeType= selectedNode.getParent().getNodeType();
if (parentNodeType == ASTNode.ASSIGNMENT) {
Assignment assign= (Assignment) selectedNode.getParent();
if (selectedNode.equals(assign.getLeftHandSide())) {
nodeToCast= assign.getRightHandSide();
}
} else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment frag= (VariableDeclarationFragment) selectedNode.getParent();
if (selectedNode.equals(frag.getName())) {
nodeToCast= frag.getInitializer();
}
}
ITypeBinding binding= nodeToCast.resolveTypeBinding();
if (binding == null || canCast(castType, binding)) {
proposals.add(createCastProposal(context, castType, nodeToCast, 5));
}
ITypeBinding currBinding= nodeToCast.resolveTypeBinding();
if (currBinding == null || "void".equals(currBinding.getName())) { //$NON-NLS-1$
return;
}
// change method return statement to actual type
if (parentNodeType == ASTNode.RETURN_STATEMENT) {
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration= (MethodDeclaration) decl;
currBinding= Bindings.normalizeTypeBinding(currBinding);
if (currBinding == null) {
currBinding= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
ASTRewrite rewrite= new ASTRewrite(methodDeclaration);
ImportRewrite imports= new ImportRewrite(cu);
String returnTypeName= imports.addImport(currBinding);
Type newReturnType= ASTNodeFactory.newType(astRoot.getAST(), returnTypeName);
rewrite.markAsReplaced(methodDeclaration.getReturnType(), newReturnType, null);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changereturntype.description", currBinding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image);
proposal.setImportRewrite(imports);
String returnKey= "return"; //$NON-NLS-1$
proposal.markAsLinked(rewrite, newReturnType, true, returnKey);
ITypeBinding[] typeSuggestions= ASTResolving.getRelaxingTypes(astRoot.getAST(), currBinding);
for (int i= 0; i < typeSuggestions.length; i++) {
proposal.addLinkedModeProposal(returnKey, typeSuggestions[i]);
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment fragment= (VariableDeclarationFragment) selectedNode.getParent();
ASTNode parent= fragment.getParent();
Type typeNode= null;
if (parent instanceof VariableDeclarationStatement) {
VariableDeclarationStatement stmt= (VariableDeclarationStatement) parent;
if (stmt.fragments().size() == 1) {
typeNode= stmt.getType();
}
} else if (parent instanceof FieldDeclaration) {
FieldDeclaration decl= (FieldDeclaration) parent;
if (decl.fragments().size() == 1) {
typeNode= decl.getType();
}
}
if (typeNode != null) {
currBinding= Bindings.normalizeTypeBinding(currBinding);
if (currBinding == null) {
currBinding= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
ImportRewrite importRewrite= new ImportRewrite(cu);
String typeName= importRewrite.addImport(currBinding);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changevartype.description", typeName); //$NON-NLS-1$
ReplaceCorrectionProposal varProposal= new ReplaceCorrectionProposal(label, cu, typeNode.getStartPosition(), typeNode.getLength(), typeName, 5);
varProposal.setImportRewrite(importRewrite);
proposals.add(varProposal);
}
}
}
private static boolean canCast(String castTarget, ITypeBinding bindingToCast) {
bindingToCast= Bindings.normalizeTypeBinding(bindingToCast);
if (bindingToCast == null) {
return false;
}
int arrStart= castTarget.indexOf('[');
if (arrStart != -1) {
if (!bindingToCast.isArray()) {
return "java.lang.Object".equals(bindingToCast.getQualifiedName()); //$NON-NLS-1$
}
castTarget= castTarget.substring(0, arrStart);
bindingToCast= bindingToCast.getElementType();
if (bindingToCast.isPrimitive() && !castTarget.equals(bindingToCast.getName())) {
return false; // can't cast arrays of primitive types into each other
}
}
Code targetCode= PrimitiveType.toCode(castTarget);
if (bindingToCast.isPrimitive()) {
Code castCode= PrimitiveType.toCode(bindingToCast.getName());
if (castCode == targetCode) {
return true;
}
return (targetCode != null && targetCode != PrimitiveType.BOOLEAN && castCode != PrimitiveType.BOOLEAN);
} else {
return targetCode == null; // can not check
}
}
public static ASTRewriteCorrectionProposal createCastProposal(IInvocationContext context, String castType, Expression nodeToCast, int relevance) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTRewrite rewrite= new ASTRewrite(nodeToCast.getParent());
ImportRewrite imports= new ImportRewrite(cu);
String label;
String simpleCastType= imports.addImport(castType);
if (nodeToCast.getNodeType() == ASTNode.CAST_EXPRESSION) {
label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changecast.description", castType); //$NON-NLS-1$
CastExpression expression= (CastExpression) nodeToCast;
rewrite.markAsReplaced(expression.getType(), rewrite.createPlaceholder(simpleCastType, NewASTRewrite.TYPE), null);
} else {
label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast.description", castType); //$NON-NLS-1$
Expression expressionCopy= (Expression) rewrite.createCopy(nodeToCast);
int nodeType= nodeToCast.getNodeType();
if (nodeType == ASTNode.INFIX_EXPRESSION || nodeType == ASTNode.CONDITIONAL_EXPRESSION
|| nodeType == ASTNode.ASSIGNMENT || nodeType == ASTNode.INSTANCEOF_EXPRESSION) {
// nodes have weaker precedence than cast
ParenthesizedExpression parenthesizedExpression= astRoot.getAST().newParenthesizedExpression();
parenthesizedExpression.setExpression(expressionCopy);
expressionCopy= parenthesizedExpression;
}
Type typeCopy= (Type) rewrite.createPlaceholder(simpleCastType, NewASTRewrite.TYPE);
CastExpression castExpression= astRoot.getAST().newCastExpression();
castExpression.setExpression(expressionCopy);
castExpression.setType(typeCopy);
rewrite.markAsReplaced(nodeToCast, castExpression, null);
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, relevance, image); //$NON-NLS-1$
proposal.setImportRewrite(imports);
proposal.ensureNoModifications();
return proposal;
}
public static void addUncaughtExceptionProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(astRoot);
if (selectedNode == null) {
return;
}
while (selectedNode != null && !(selectedNode instanceof Statement)) {
selectedNode= selectedNode.getParent();
}
if (selectedNode == null) {
return;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
SurroundWithTryCatchRefactoring refactoring= SurroundWithTryCatchRefactoring.create(cu, selectedNode.getStartPosition(), selectedNode.getLength(), settings, null);
if (refactoring == null)
return;
refactoring.setLeaveDirty(true);
if (refactoring.checkActivationBasics(astRoot, null).isOK()) {
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.surroundwith.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
CUCorrectionProposal proposal= new CUCorrectionProposal(label, (CompilationUnitChange) refactoring.createChange(null), 4, image);
proposals.add(proposal);
}
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl == null) {
return;
}
ITypeBinding[] uncaughtExceptions= ExceptionAnalyzer.perform(decl, Selection.createFromStartLength(selectedNode.getStartPosition(), selectedNode.getLength()));
if (uncaughtExceptions.length == 0) {
return;
}
TryStatement surroundingTry= ASTResolving.findParentTryStatement(selectedNode);
if (surroundingTry != null && ASTNodes.isParent(selectedNode, surroundingTry.getBody())) {
ASTRewrite rewrite= new ASTRewrite(surroundingTry);
ImportRewrite imports= new ImportRewrite(cu);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addadditionalcatch.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 5, image);
proposal.setImportRewrite(imports);
AST ast= astRoot.getAST();
ListRewriter clausesRewrite= rewrite.getListRewrite(surroundingTry, TryStatement.CATCH_CLAUSES_PROPERTY);
for (int i= 0; i < uncaughtExceptions.length; i++) {
ITypeBinding excBinding= uncaughtExceptions[i];
String varName= PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.CODEGEN_EXCEPTION_VAR_NAME);
String imp= imports.addImport(excBinding);
Name name= ASTNodeFactory.newName(ast, imp);
SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
var.setName(ast.newSimpleName(varName));
var.setType(ast.newSimpleType(name));
CatchClause newClause= ast.newCatchClause();
newClause.setException(var);
String catchBody = StubUtility.getCatchBodyContent(cu, excBinding.getName(), varName, String.valueOf('\n'));
if (catchBody != null) {
ASTNode node= rewrite.createPlaceholder(catchBody, NewASTRewrite.STATEMENT);
newClause.getBody().statements().add(node);
}
clausesRewrite.insertLast(newClause, null);
String typeKey= "type" + i; //$NON-NLS-1$
String nameKey= "name" + i; //$NON-NLS-1$
proposal.markAsLinked(rewrite, var.getType(), false, typeKey); //$NON-NLS-1$
proposal.markAsLinked(rewrite, var.getName(), false, nameKey); //$NON-NLS-1$
addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
if (decl instanceof MethodDeclaration) {
ASTRewrite rewrite= new ASTRewrite(astRoot);
ImportRewrite imports= new ImportRewrite(cu);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addthrows.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image);
proposal.setImportRewrite(imports);
AST ast= astRoot.getAST();
MethodDeclaration methodDecl= (MethodDeclaration) decl;
List exceptions= methodDecl.thrownExceptions();
ListRewriter listRewrite= rewrite.getListRewrite(methodDecl, MethodDeclaration.THROWN_EXCEPTIONS_PROPERTY);
for (int i= 0; i < uncaughtExceptions.length; i++) {
String imp= imports.addImport(uncaughtExceptions[i]);
Name name= ASTNodeFactory.newName(ast, imp);
listRewrite.insertLast(name, null);
String typeKey= "type" + i; //$NON-NLS-1$
proposal.markAsLinked(rewrite, name, false, typeKey); //$NON-NLS-1$
addExceptionTypeLinkProposals(proposal, uncaughtExceptions[i], typeKey);
}
for (int i= 0; i < exceptions.size(); i++) {
Name elem= (Name) exceptions.get(i);
if (canRemoveException(elem.resolveTypeBinding(), uncaughtExceptions)) {
rewrite.markAsRemoved(elem, null);
}
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
private static void addExceptionTypeLinkProposals(LinkedCorrectionProposal proposal, ITypeBinding exc, String key) {
// all superclasses except Object
while (exc != null && !"java.lang.Object".equals(exc.getQualifiedName())) { //$NON-NLS-1$
proposal.addLinkedModeProposal(key, exc);
exc= exc.getSuperclass();
}
}
private static boolean canRemoveException(ITypeBinding curr, ITypeBinding[] addedExceptions) {
while (curr != null) {
for (int i= 0; i < addedExceptions.length; i++) {
if (curr == addedExceptions[i]) {
return true;
}
}
curr= curr.getSuperclass();
}
return false;
}
public static void addUnreachableCatchProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (selectedNode == null) {
return;
}
QuickAssistProcessor.getCatchClauseToThrowsProposals(context, selectedNode, proposals);
}
public static void addNLSProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
if (! NLSRefactoring.isAvailable(cu)){
return;
}
String name= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.description"); //$NON-NLS-1$
ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 5) {
public void apply(IDocument document) {
try {
NLSRefactoring refactoring= NLSRefactoring.create(cu, JavaPreferencesSettings.getCodeGenerationSettings());
if (refactoring == null)
return;
ExternalizeWizard wizard= new ExternalizeWizard(refactoring);
String dialogTitle= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.dialog.title"); //$NON-NLS-1$
new RefactoringStarter().activate(refactoring, wizard, JavaPlugin.getActiveWorkbenchShell(), dialogTitle, true);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
};
proposals.add(proposal);
TextEdit edit= NLSUtil.createNLSEdit(cu, problem.getOffset());
if (edit != null) {
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addnon-nls.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_NEVER_TRANSLATE);
CUCorrectionProposal nlsProposal= new CUCorrectionProposal(label, cu, 6, image);
nlsProposal.getRootTextEdit().addChild(edit);
proposals.add(nlsProposal);
}
}
/**
* Fix instance accesses and indirect (static) accesses to static fields/methods
*/
public static void addCorrectAccessToStaticProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(astRoot);
if (selectedNode == null) {
return;
}
// fix for 32022
String[] args= problem.getProblemArguments();
if (selectedNode instanceof QualifiedName && args.length == 2) {
String field= args[1];
QualifiedName qualified= (QualifiedName) selectedNode;
while (!field.equals(qualified.getName().getIdentifier()) && qualified.getQualifier() instanceof QualifiedName) {
qualified= (QualifiedName) qualified.getQualifier();
}
selectedNode= qualified;
problem= new ProblemLocation(qualified.getStartPosition(), qualified.getLength(), problem.getProblemId(), args, problem.isError());
}
Expression qualifier= null;
IBinding accessBinding= null;
if (selectedNode instanceof QualifiedName) {
QualifiedName name= (QualifiedName) selectedNode;
qualifier= name.getQualifier();
accessBinding= name.resolveBinding();
} else if (selectedNode instanceof SimpleName) {
ASTNode parent= selectedNode.getParent();
if (parent instanceof FieldAccess) {
FieldAccess fieldAccess= (FieldAccess) parent;
qualifier= fieldAccess.getExpression();
accessBinding= fieldAccess.getName().resolveBinding();
}
} else if (selectedNode instanceof MethodInvocation) {
MethodInvocation methodInvocation= (MethodInvocation) selectedNode;
qualifier= methodInvocation.getExpression();
accessBinding= methodInvocation.getName().resolveBinding();
} else if (selectedNode instanceof FieldAccess) {
FieldAccess fieldAccess= (FieldAccess) selectedNode;
qualifier= fieldAccess.getExpression();
accessBinding= fieldAccess.getName().resolveBinding();
}
if (problem.getProblemId() == IProblem.IndirectAccessToStaticField || problem.getProblemId() == IProblem.IndirectAccessToStaticMethod) {
// indirectAccessToStaticProposal
if (accessBinding != null) {
ITypeBinding declaringTypeBinding= getDeclaringTypeBinding(accessBinding);
if (declaringTypeBinding != null) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
ImportRewrite imports= new ImportRewrite(cu);
String typeName= imports.addImport(declaringTypeBinding);
rewrite.markAsReplaced(qualifier, ASTNodeFactory.newName(astRoot.getAST(), typeName), null);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.indirectaccesstostatic.description", declaringTypeBinding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
proposal.setImportRewrite(imports);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
return;
}
ITypeBinding declaringTypeBinding= null;
if (accessBinding != null) {
declaringTypeBinding= getDeclaringTypeBinding(accessBinding);
if (declaringTypeBinding != null) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
ImportRewrite imports= new ImportRewrite(cu);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostaticdefining.description", declaringTypeBinding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
proposal.setImportRewrite(imports);
String typeName= imports.addImport(declaringTypeBinding);
rewrite.markAsReplaced(qualifier, ASTNodeFactory.newName(astRoot.getAST(), typeName), null);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (qualifier != null) {
ITypeBinding instanceTypeBinding= Bindings.normalizeTypeBinding(qualifier.resolveTypeBinding());
if (instanceTypeBinding != null && instanceTypeBinding != declaringTypeBinding) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
ImportRewrite imports= new ImportRewrite(cu);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostatic.description", instanceTypeBinding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image);
proposal.setImportRewrite(imports);
String typeName= imports.addImport(instanceTypeBinding);
rewrite.markAsReplaced(qualifier, ASTNodeFactory.newName(astRoot.getAST(), typeName), null);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_STATIC, 4);
}
private static ITypeBinding getDeclaringTypeBinding(IBinding accessBinding) {
if (accessBinding instanceof IMethodBinding) {
return ((IMethodBinding) accessBinding).getDeclaringClass();
} else if (accessBinding instanceof IVariableBinding) {
return ((IVariableBinding) accessBinding).getDeclaringClass();
}
return null;
}
public static void addUnimplementedMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (selectedNode == null) {
return;
}
ASTNode typeNode= null;
if (selectedNode.getNodeType() == ASTNode.SIMPLE_NAME && selectedNode.getParent().getNodeType() == ASTNode.TYPE_DECLARATION) {
typeNode= selectedNode.getParent();
} else if (selectedNode.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode;
typeNode= creation.getAnonymousClassDeclaration();
}
if (typeNode != null) {
UnimplementedMethodsCompletionProposal proposal= new UnimplementedMethodsCompletionProposal(cu, typeNode, 10);
proposals.add(proposal);
}
if (typeNode instanceof TypeDeclaration) {
TypeDeclaration typeDeclaration= (TypeDeclaration) typeNode;
ASTRewriteCorrectionProposal proposal= ModifierCorrectionSubProcessor.getMakeTypeAbstractProposal(cu, typeDeclaration, 5);
proposals.add(proposal);
}
}
public static void addUninitializedLocalVariableProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (!(selectedNode instanceof Name)) {
return;
}
Name name= (Name) selectedNode;
IBinding binding= name.resolveBinding();
if (!(binding instanceof IVariableBinding)) {
return;
}
IVariableBinding varBinding= (IVariableBinding) binding;
CompilationUnit astRoot= context.getASTRoot();
ASTNode node= astRoot.findDeclaringNode(binding);
if (node instanceof VariableDeclarationFragment) {
ASTRewrite rewrite= new ASTRewrite(node.getParent());
VariableDeclarationFragment fragment= (VariableDeclarationFragment) node;
if (fragment.getInitializer() != null) {
return;
}
Expression expression= ASTNodeFactory.newDefaultExpression(astRoot.getAST(), varBinding.getType());
if (expression == null) {
return;
}
rewrite.set(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, expression, null);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.uninitializedvariable.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image);
proposal.markAsLinked(rewrite, expression, false, "initializer"); //$NON-NLS-1$
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
public static void addConstructorFromSuperclassProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (!(selectedNode instanceof Name && selectedNode.getParent() instanceof TypeDeclaration)) {
return;
}
TypeDeclaration typeDeclaration= (TypeDeclaration) selectedNode.getParent();
ITypeBinding binding= typeDeclaration.resolveBinding();
if (binding == null || binding.getSuperclass() == null) {
return;
}
ICompilationUnit cu= context.getCompilationUnit();
IMethodBinding[] methods= binding.getSuperclass().getDeclaredMethods();
for (int i= 0; i < methods.length; i++) {
IMethodBinding curr= methods[i];
if (curr.isConstructor() && !Modifier.isPrivate(curr.getModifiers())) {
proposals.add(new ConstructorFromSuperclassProposal(cu, typeDeclaration, curr, 5));
}
}
}
public static void addUnusedMemberProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
SimpleName name= null;
if (selectedNode instanceof MethodDeclaration) {
name= ((MethodDeclaration) selectedNode).getName();
} else if (selectedNode instanceof SimpleName) {
name= (SimpleName) selectedNode;
}
if (name != null) {
IBinding binding= name.resolveBinding();
if (binding != null) {
proposals.add(new RemoveDeclarationCorrectionProposal(context.getCompilationUnit(), name, 5));
}
}
}
public static void addSuperfluousSemicolonProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removesemicolon.description"); //$NON-NLS-1$
ReplaceCorrectionProposal proposal= new ReplaceCorrectionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), "", 6); //$NON-NLS-1$
proposals.add(proposal);
}
public static void addUnnecessaryCastProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
ASTNode curr= selectedNode;
while (curr instanceof ParenthesizedExpression) {
curr= ((ParenthesizedExpression) curr).getExpression();
}
if (curr instanceof CastExpression) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
CastExpression cast= (CastExpression) curr;
Expression expression= cast.getExpression();
ASTNode placeholder= rewrite.createCopy(expression);
if (ASTNodes.needsParentheses(expression)) {
rewrite.markAsReplaced(curr, placeholder, null);
} else {
rewrite.markAsReplaced(selectedNode, placeholder, null);
}
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.unnecessarycast.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image);
proposals.add(proposal);
}
}
public static void addUnnecessaryInstanceofProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
ASTNode curr= selectedNode;
while (curr instanceof ParenthesizedExpression) {
curr= ((ParenthesizedExpression) curr).getExpression();
}
if (curr instanceof InstanceofExpression) {
ASTRewrite rewrite= new ASTRewrite(curr.getParent());
InstanceofExpression inst= (InstanceofExpression) curr;
AST ast= inst.getAST();
InfixExpression expression= ast.newInfixExpression();
expression.setLeftOperand((Expression) rewrite.createCopy(inst.getLeftOperand()));
expression.setOperator(InfixExpression.Operator.NOT_EQUALS);
expression.setRightOperand(ast.newNullLiteral());
if (false/*ASTNodes.needsParentheses(expression)*/) {
ParenthesizedExpression parents= ast.newParenthesizedExpression();
parents.setExpression(expression);
rewrite.markAsReplaced(inst, parents, null);
} else {
rewrite.markAsReplaced(inst, expression, null);
}
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.unnecessaryinstanceof.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image);
proposals.add(proposal);
}
}
public static void addUnnecessaryThrownExceptionProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (selectedNode == null) {
return;
}
if (selectedNode.getParent() instanceof MethodDeclaration) {
MethodDeclaration decl= (MethodDeclaration) selectedNode.getParent();
List thrownExceptions= decl.thrownExceptions();
if (!thrownExceptions.contains(selectedNode)) {
return;
}
ASTRewrite rewrite= new ASTRewrite(decl);
rewrite.markAsRemoved(selectedNode, null);
Javadoc javadoc= decl.getJavadoc();
if (javadoc != null) {
IBinding binding= ((Name) selectedNode).resolveBinding();
if (binding != null) {
TagElement tagElement= findThrowsTag(javadoc, binding);
if (tagElement != null) {
rewrite.markAsRemoved(tagElement, null);
}
}
}
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.unnecessarythrow.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image);
proposals.add(proposal);
}
}
private static TagElement findThrowsTag(Javadoc javadoc, IBinding binding) {
List tags= javadoc.tags();
for (int i= tags.size() - 1; i >= 0; i--) {
TagElement curr= (TagElement) tags.get(i);
String currName= curr.getTagName();
if ("@throws".equals(currName) || "@exception".equals(currName)) { //$NON-NLS-1$//$NON-NLS-2$
List fragments= curr.fragments();
if (!fragments.isEmpty() && fragments.get(0) instanceof Name) {
Name name= (Name) fragments.get(0);
if (name.resolveBinding() == binding) {
return curr;
}
}
}
}
return null;
}
public static void addUnqualifiedFieldAccessProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
while (selectedNode instanceof QualifiedName) {
selectedNode= ((QualifiedName) selectedNode).getQualifier();
}
if (!(selectedNode instanceof SimpleName)) {
return;
}
SimpleName name = (SimpleName) selectedNode;
IBinding binding= name.resolveBinding();
if (binding.getKind() != IBinding.VARIABLE) {
return;
}
ASTRewrite rewrite= new ASTRewrite(name.getParent());
ImportRewrite imports= new ImportRewrite(context.getCompilationUnit());
ITypeBinding declaringClass= ((IVariableBinding) binding).getDeclaringClass();
String qualifier;
if (Modifier.isStatic(binding.getModifiers())) {
qualifier= imports.addImport(declaringClass);
} else {
ITypeBinding currType= Bindings.getBindingOfParentType(name);
if (Bindings.isSuperType(currType, declaringClass)) {
qualifier= "this"; //$NON-NLS-1$
} else {
String outer= imports.addImport(declaringClass);
qualifier= outer + ".this"; //$NON-NLS-1$
}
}
String replacement= qualifier + '.' + name.getIdentifier();
rewrite.markAsReplaced(name, rewrite.createPlaceholder(replacement, NewASTRewrite.NAME), null);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.unqualifiedfieldaccess.description", qualifier); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image); //$NON-NLS-1$
proposal.setImportRewrite(imports);
proposals.add(proposal);
}
}
|
37,594 |
Bug 37594 Quick fix for 'hidden variable'
|
When you get the compiler warning stating that you have a local variable in a method which is over-riding a field in your class, I would like to have the QuickFix option to rename the local variable and all its occurences in the method.
|
resolved fixed
|
4c8ff5d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-19T15:23:20Z | 2003-05-14T13:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sebastian Davids <[email protected]> - Bug 37432 getInvertEqualsProposal
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.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.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder;
import org.eclipse.jdt.internal.corext.dom.ListRewriter;
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)
|| getAddBlockProposals(context, coveringNode, null)
|| getInvertEqualsProposal(context, coveringNode, null);
}
return false;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.correction.IAssistProcessor#getAssists(org.eclipse.jdt.internal.ui.text.correction.IAssistContext, org.eclipse.jdt.internal.ui.text.correction.IProblemLocation[])
*/
public IJavaCompletionProposal[] getAssists(IInvocationContext context, IProblemLocation[] locations) throws CoreException {
ASTNode coveringNode= getCoveringNode(context);
if (coveringNode != null) {
ArrayList resultingCollections= new ArrayList();
// quick assists that show up also if there is an error/warning
getRenameLocalProposals(context, coveringNode, resultingCollections);
if (noErrorsAtLocation(locations)) {
getCatchClauseToThrowsProposals(context, coveringNode, resultingCollections);
getAssignToVariableProposals(context, coveringNode, resultingCollections);
getAssignParamToFieldProposals(context, coveringNode, resultingCollections);
getUnWrapProposals(context, coveringNode, resultingCollections);
getSplitVariableProposals(context, coveringNode, resultingCollections);
getJoinVariableProposals(context, coveringNode, resultingCollections);
getAddFinallyProposals(context, coveringNode, resultingCollections);
getAddElseProposals(context, coveringNode, resultingCollections);
getAddBlockProposals(context, coveringNode, resultingCollections);
getInvertEqualsProposal(context, coveringNode, resultingCollections);
}
return (IJavaCompletionProposal[]) resultingCollections.toArray(new IJavaCompletionProposal[resultingCollections.size()]);
}
return null;
}
private boolean noErrorsAtLocation(IProblemLocation[] locations) {
if (locations != null) {
for (int i= 0; i < locations.length; i++) {
if (locations[i].isError()) {
return false;
}
}
}
return true;
}
private boolean getJoinVariableProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) 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.findByBinding(statement.getParent(), binding);
if (names.length <= 1 || names[0] != fragment.getName()) {
return false;
}
SimpleName firstAccess= names[1];
if (!(firstAccess.getParent() instanceof Assignment)) {
return false;
}
Assignment assignment= (Assignment) firstAccess.getParent();
if (assignment.getLeftHandSide() != firstAccess) {
return false;
}
ASTNode assignParent= assignment.getParent();
if (!(assignParent instanceof ExpressionStatement || assignParent instanceof ForStatement && ((ForStatement) assignParent).initializers().contains(assignment))) {
return false;
}
if (resultingCollections == null) {
return true;
}
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.set(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, placeholder, null);
if (assignParent instanceof ExpressionStatement) {
int statementParent= assignParent.getParent().getNodeType();
if (statementParent == ASTNode.IF_STATEMENT || statementParent == ASTNode.WHILE_STATEMENT || statementParent == ASTNode.DO_STATEMENT
|| statementParent == ASTNode.FOR_STATEMENT) {
Block block= ast.newBlock();
rewrite.markAsReplaced(assignParent, block, null);
} else {
rewrite.markAsRemoved(assignParent, null);
}
} else {
rewrite.markAsRemoved(assignment, null);
}
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();
StructuralPropertyDescriptor property= statement.getLocationInParent();
if (!property.isChildListProperty()) {
return false;
}
List list= (List) statementParent.getStructuralProperty(property);
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
int modifiers= ((VariableDeclarationStatement) statement).getModifiers();
if (Modifier.isFinal(modifiers)) {
rewrite.set(statement, VariableDeclarationStatement.MODIFIERS_PROPERTY, new Integer(modifiers & ~Modifier.FINAL), null);
}
} else {
rewrite.markAsReplaced(fragment.getParent(), assignment, null);
VariableDeclarationFragment newFrag= ast.newVariableDeclarationFragment();
newFrag.setName(ast.newSimpleName(fragment.getName().getIdentifier()));
newFrag.setExtraDimensions(fragment.getExtraDimensions());
VariableDeclarationExpression oldVarDecl= (VariableDeclarationExpression) fragParent;
VariableDeclarationStatement newVarDec= ast.newVariableDeclarationStatement(newFrag);
newVarDec.setType((Type) ASTNode.copySubtree(ast, oldVarDecl.getType()));
newVarDec.setModifiers(oldVarDecl.getModifiers() & ~Modifier.FINAL);
newStatement= newVarDec;
}
ListRewriter listRewriter= rewrite.getListRewrite(statementParent, (ChildListPropertyDescriptor) property);
listRewriter.insertAt(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.set(tryStatement, TryStatement.FINALLY_PROPERTY, finallyBody, null);
String label= CorrectionMessages.getString("QuickAssistProcessor.addfinallyblock.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
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.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, body, null);
String label= CorrectionMessages.getString("QuickAssistProcessor.addelseblock.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
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);
ListRewriter listRewriter= rewrite.getListRewrite(methodDeclaration, MethodDeclaration.THROWN_EXCEPTIONS_PROPERTY);
listRewriter.insertLast(newName, null);
}
String label= CorrectionMessages.getString("QuickAssistProcessor.catchclausetothrows.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 4, image);
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, null);
} else {
List statements= tryStatement.getBody().statements();
if (statements.size() > 0) {
ASTNode placeholder= rewrite.collapseNodes(statements, 0, statements.size());
rewrite.markAsReplaced(tryStatement, rewrite.createCopy(placeholder), null);
} else {
rewrite.markAsRemoved(tryStatement, null);
}
}
}
private static boolean isNotYetThrown(ITypeBinding binding, List thrownExcpetions) {
for (int i= 0; i < thrownExcpetions.size(); i++) {
Name name= (Name) thrownExcpetions.get(i);
ITypeBinding elem= (ITypeBinding) name.resolveBinding();
if (elem != null) {
if (Bindings.isSuperType(elem, binding)) { // existing exception is base class of new
return false;
}
}
}
return true;
}
private boolean getRenameLocalProposals(IInvocationContext context, ASTNode node, 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, null);
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;
}
private static boolean isControlStatementWithBlock(ASTNode node) {
switch (node.getNodeType()) {
case ASTNode.IF_STATEMENT:
case ASTNode.WHILE_STATEMENT:
case ASTNode.FOR_STATEMENT:
case ASTNode.DO_STATEMENT:
return true;
default:
return false;
}
}
private boolean getAddBlockProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) throws CoreException {
Statement statement= ASTResolving.findParentStatement(node);
if (statement == null) {
return false;
}
if (!isControlStatementWithBlock(statement)) {
if (!isControlStatementWithBlock(statement.getParent())) {
return false;
}
int statementStart= statement.getStartPosition();
int statementEnd= statementStart + statement.getLength();
int offset= context.getSelectionOffset();
int length= context.getSelectionLength();
if (length == 0) {
if (offset != statementEnd) { // cursor at end
return false;
}
} else {
if (offset > statementStart || offset + length < statementEnd) { // statement selected
return false;
}
}
statement= (Statement) statement.getParent();
}
StructuralPropertyDescriptor childProperty= null;
ASTNode child= null;
switch (statement.getNodeType()) {
case ASTNode.IF_STATEMENT:
int selectionStart= context.getSelectionOffset();
int selectionEnd= context.getSelectionOffset() + context.getSelectionLength();
ASTNode then= ((IfStatement) statement).getThenStatement();
if (selectionEnd <= then.getStartPosition() + then.getLength()) {
if (!(then instanceof Block)) {
childProperty= IfStatement.THEN_STATEMENT_PROPERTY;
child= then;
}
} else if (selectionStart >= then.getStartPosition() + then.getLength()) {
ASTNode elseStatement= ((IfStatement) statement).getElseStatement();
if (!(elseStatement instanceof Block)) {
childProperty= IfStatement.ELSE_STATEMENT_PROPERTY;
child= elseStatement;
}
}
break;
case ASTNode.WHILE_STATEMENT:
ASTNode whileBody= ((WhileStatement) statement).getBody();
if (!(whileBody instanceof Block)) {
childProperty= WhileStatement.BODY_PROPERTY;
child= whileBody;
}
break;
case ASTNode.FOR_STATEMENT:
ASTNode forBody= ((ForStatement) statement).getBody();
if (!(forBody instanceof Block)) {
childProperty= ForStatement.BODY_PROPERTY;
child= forBody;
}
break;
case ASTNode.DO_STATEMENT:
ASTNode doBody= ((DoStatement) statement).getBody();
if (!(doBody instanceof Block)) {
childProperty= DoStatement.BODY_PROPERTY;
child= doBody;
}
break;
default:
}
if (child == null) {
return false;
}
if (resultingCollections == null) {
return true;
}
AST ast= statement.getAST();
ASTRewrite rewrite= new ASTRewrite(statement);
ASTNode childPlaceholder= rewrite.createMove(child);
Block replacingBody= ast.newBlock();
replacingBody.statements().add(childPlaceholder);
rewrite.set(statement, childProperty, replacingBody, null);
String label;
if (childProperty == IfStatement.THEN_STATEMENT_PROPERTY) {
label = CorrectionMessages.getString("QuickAssistProcessor.replacethenwithblock.description");//$NON-NLS-1$
} else if (childProperty == IfStatement.ELSE_STATEMENT_PROPERTY) {
label = CorrectionMessages.getString("QuickAssistProcessor.replaceelsewithblock.description");//$NON-NLS-1$
} else {
label = CorrectionMessages.getString("QuickAssistProcessor.replacebodywithblock.description");//$NON-NLS-1$
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, 10, image);
proposal.markAsSelection(rewrite, child);
proposal.ensureNoModifications();
resultingCollections.add(proposal);
return true;
}
private boolean getInvertEqualsProposal(IInvocationContext context, ASTNode node, Collection resultingCollections) throws CoreException {
ASTNode parent= node.getParent();
if (!(parent instanceof MethodInvocation)) {
return false;
}
MethodInvocation method= (MethodInvocation) parent;
if (!"equals".equals(method.getName().getIdentifier())) { //$NON-NLS-1$
return false;
}
List arguments= method.arguments();
if (arguments.size() != 1) { //overloaded equals w/ more than 1 arg
return false;
}
Expression right= (Expression) arguments.get(0);
ITypeBinding binding = right.resolveTypeBinding();
if (!(binding.isClass() || binding.isInterface())) { //overloaded equals w/ non-class/interface arg or null
return false;
}
Expression left= method.getExpression();
ASTRewrite rewrite;
if (left == null) { // equals(x) -> x.equals(this)
rewrite= new ASTRewrite(method.getParent());
AST ast= rewrite.getAST();
MethodInvocation replacement= ast.newMethodInvocation();
replacement.setName((SimpleName) rewrite.createCopy(method.getName()));
replacement.arguments().add(ast.newThisExpression());
replacement.setExpression((Expression) rewrite.createCopy(right));
rewrite.markAsReplaced(method, replacement, null);
} else if (right instanceof ThisExpression) { // x.equals(this) -> equals(x)
rewrite= new ASTRewrite(method.getParent());
MethodInvocation replacement= rewrite.getAST().newMethodInvocation();
replacement.setName((SimpleName) rewrite.createCopy(method.getName()));
replacement.arguments().add(rewrite.createCopy(left));
rewrite.markAsReplaced(method, replacement, null);
} else {
rewrite= new ASTRewrite(method);
if (left instanceof ParenthesizedExpression) {
Expression ex= ((ParenthesizedExpression) left).getExpression();
rewrite.markAsReplaced(right, rewrite.createCopy(ex), null);
} else {
rewrite.markAsReplaced(right, rewrite.createCopy(left), null);
}
if ((right instanceof CastExpression)
|| (right instanceof Assignment)
|| (right instanceof ConditionalExpression)
|| (right instanceof InfixExpression)) {
ParenthesizedExpression paren= rewrite.getAST().newParenthesizedExpression();
paren.setExpression((Expression) rewrite.createCopy(right));
rewrite.markAsReplaced(left, paren, null);
} else {
rewrite.markAsReplaced(left, rewrite.createCopy(right), null);
}
}
String label= CorrectionMessages.getString("QuickAssistProcessor.invertequals.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
proposal.ensureNoModifications();
resultingCollections.add(proposal);
return true;
}
}
|
37,594 |
Bug 37594 Quick fix for 'hidden variable'
|
When you get the compiler warning stating that you have a local variable in a method which is over-riding a field in your class, I would like to have the QuickFix option to rename the local variable and all its occurences in the method.
|
resolved fixed
|
4c8ff5d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-19T15:23:20Z | 2003-05-14T13:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickFixProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.ui.text.java.*;
import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
/**
*/
public class QuickFixProcessor implements IQuickFixProcessor {
public boolean hasCorrections(ICompilationUnit cu, int problemId) {
switch (problemId) {
case IProblem.UnterminatedString:
case IProblem.UnusedImport:
case IProblem.DuplicateImport:
case IProblem.CannotImportPackage:
case IProblem.ConflictingImport:
case IProblem.ImportNotFound:
case IProblem.UndefinedMethod:
case IProblem.UndefinedConstructor:
case IProblem.ParameterMismatch:
case IProblem.MethodButWithConstructorName:
case IProblem.UndefinedField:
case IProblem.UndefinedName:
case IProblem.PublicClassMustMatchFileName:
case IProblem.PackageIsNotExpectedPackage:
case IProblem.UndefinedType:
case IProblem.FieldTypeNotFound:
case IProblem.ArgumentTypeNotFound:
case IProblem.ReturnTypeNotFound:
case IProblem.SuperclassNotFound:
case IProblem.ExceptionTypeNotFound:
case IProblem.InterfaceNotFound:
case IProblem.TypeMismatch:
case IProblem.UnhandledException:
case IProblem.UnreachableCatch:
case IProblem.VoidMethodReturnsValue:
case IProblem.ShouldReturnValue:
case IProblem.MissingReturnType:
case IProblem.NonExternalizedStringLiteral:
case IProblem.NonStaticAccessToStaticField:
case IProblem.NonStaticAccessToStaticMethod:
case IProblem.StaticMethodRequested:
case IProblem.NonStaticFieldFromStaticInvocation:
case IProblem.InstanceMethodDuringConstructorInvocation:
case IProblem.InstanceFieldDuringConstructorInvocation:
case IProblem.NotVisibleMethod:
case IProblem.NotVisibleConstructor:
case IProblem.NotVisibleType:
case IProblem.SuperclassNotVisible:
case IProblem.InterfaceNotVisible:
case IProblem.FieldTypeNotVisible:
case IProblem.ArgumentTypeNotVisible:
case IProblem.ReturnTypeNotVisible:
case IProblem.ExceptionTypeNotVisible:
case IProblem.NotVisibleField:
case IProblem.ImportNotVisible:
case IProblem.BodyForAbstractMethod:
case IProblem.AbstractMethodInAbstractClass:
case IProblem.AbstractMethodMustBeImplemented:
case IProblem.BodyForNativeMethod:
case IProblem.OuterLocalMustBeFinal:
case IProblem.UninitializedLocalVariable:
case IProblem.UndefinedConstructorInDefaultConstructor:
case IProblem.UnhandledExceptionInDefaultConstructor:
case IProblem.NotVisibleConstructorInDefaultConstructor:
case IProblem.FieldTypeAmbiguous:
case IProblem.ArgumentTypeAmbiguous:
case IProblem.ExceptionTypeAmbiguous:
case IProblem.ReturnTypeAmbiguous:
case IProblem.SuperclassAmbiguous:
case IProblem.InterfaceAmbiguous:
case IProblem.AmbiguousType:
case IProblem.UnusedPrivateMethod:
case IProblem.UnusedPrivateConstructor:
case IProblem.UnusedPrivateField:
case IProblem.UnusedPrivateType:
case IProblem.LocalVariableIsNeverUsed:
case IProblem.ArgumentIsNeverUsed:
case IProblem.MethodRequiresBody:
case IProblem.NeedToEmulateFieldReadAccess:
case IProblem.NeedToEmulateFieldWriteAccess:
case IProblem.NeedToEmulateMethodAccess:
case IProblem.NeedToEmulateConstructorAccess:
case IProblem.SuperfluousSemicolon:
case IProblem.UnnecessaryCast:
case IProblem.UnnecessaryArgumentCast:
case IProblem.UnnecessaryInstanceof:
case IProblem.IndirectAccessToStaticField:
case IProblem.IndirectAccessToStaticMethod:
case IProblem.Task:
case IProblem.UnusedMethodDeclaredThrownException:
case IProblem.UnusedConstructorDeclaredThrownException:
case IProblem.UnqualifiedFieldAccess:
case IProblem.JavadocMissing:
case IProblem.JavadocMissingParamTag:
case IProblem.JavadocMissingReturnTag:
case IProblem.JavadocMissingThrowsTag:
case IProblem.JavadocUndefinedType:
case IProblem.JavadocAmbiguousType:
case IProblem.JavadocNotVisibleType:
case IProblem.NonBlankFinalLocalAssignment:
case IProblem.DuplicateFinalLocalInitialization:
case IProblem.FinalFieldAssignment:
case IProblem.DuplicateBlankFinalFieldInitialization:
case IProblem.FinalMethodCannotBeOverridden:
return true;
default:
return false;
}
}
private static int moveBack(int offset, int start, String ignoreCharacters, ICompilationUnit cu) {
try {
IBuffer buf= cu.getBuffer();
while (offset >= start) {
if (ignoreCharacters.indexOf(buf.getChar(offset - 1)) == -1) { //$NON-NLS-1$
return offset;
}
offset--;
}
} catch(JavaModelException e) {
}
return start;
}
/* (non-Javadoc)
* @see IAssistProcessor#getCorrections(org.eclipse.jdt.internal.ui.text.correction.IAssistContext, org.eclipse.jdt.internal.ui.text.correction.IProblemLocation[])
*/
public IJavaCompletionProposal[] getCorrections(IInvocationContext context, IProblemLocation[] locations) throws CoreException {
if (locations == null || locations.length == 0) {
return null;
}
HashSet handledProblems= new HashSet(locations.length);
ArrayList resultingCollections= new ArrayList();
for (int i= 0; i < locations.length; i++) {
IProblemLocation curr= locations[i];
Integer id= new Integer(curr.getProblemId());
if (handledProblems.add(id)) {
process(context, curr, resultingCollections);
}
}
return (IJavaCompletionProposal[]) resultingCollections.toArray(new IJavaCompletionProposal[resultingCollections.size()]);
}
private void process(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
int id= problem.getProblemId();
if (id == 0) { // no proposals for none-problem locations
return;
}
switch (id) {
case IProblem.UnterminatedString:
String quoteLabel= CorrectionMessages.getString("JavaCorrectionProcessor.addquote.description"); //$NON-NLS-1$
int pos= moveBack(problem.getOffset() + problem.getLength(), problem.getOffset(), "\n\r", context.getCompilationUnit()); //$NON-NLS-1$
proposals.add(new ReplaceCorrectionProposal(quoteLabel, context.getCompilationUnit(), pos, 0, "\"", 0)); //$NON-NLS-1$
break;
case IProblem.UnusedImport:
case IProblem.DuplicateImport:
case IProblem.CannotImportPackage:
case IProblem.ConflictingImport:
ReorgCorrectionsSubProcessor.removeImportStatementProposals(context, problem, proposals);
break;
case IProblem.ImportNotFound:
ReorgCorrectionsSubProcessor.importNotFoundProposals(context, problem, proposals);
ReorgCorrectionsSubProcessor.removeImportStatementProposals(context, problem, proposals);
break;
case IProblem.UndefinedMethod:
UnresolvedElementsSubProcessor.getMethodProposals(context, problem, false, proposals);
break;
case IProblem.UndefinedConstructor:
UnresolvedElementsSubProcessor.getConstructorProposals(context, problem, proposals);
break;
case IProblem.ParameterMismatch:
UnresolvedElementsSubProcessor.getMethodProposals(context, problem, true, proposals);
break;
case IProblem.MethodButWithConstructorName:
ReturnTypeSubProcessor.addMethodWithConstrNameProposals(context, problem, proposals);
break;
case IProblem.UndefinedField:
case IProblem.UndefinedName:
UnresolvedElementsSubProcessor.getVariableProposals(context, problem, proposals);
break;
case IProblem.FieldTypeAmbiguous:
case IProblem.ArgumentTypeAmbiguous:
case IProblem.ExceptionTypeAmbiguous:
case IProblem.ReturnTypeAmbiguous:
case IProblem.SuperclassAmbiguous:
case IProblem.InterfaceAmbiguous:
case IProblem.AmbiguousType:
case IProblem.JavadocAmbiguousType:
UnresolvedElementsSubProcessor.getAmbiguosTypeReferenceProposals(context, problem, proposals);
break;
case IProblem.PublicClassMustMatchFileName:
ReorgCorrectionsSubProcessor.getWrongTypeNameProposals(context, problem, proposals);
break;
case IProblem.PackageIsNotExpectedPackage:
ReorgCorrectionsSubProcessor.getWrongPackageDeclNameProposals(context, problem, proposals);
break;
case IProblem.UndefinedType:
case IProblem.FieldTypeNotFound:
case IProblem.ArgumentTypeNotFound:
case IProblem.ReturnTypeNotFound:
case IProblem.SuperclassNotFound:
case IProblem.ExceptionTypeNotFound:
case IProblem.InterfaceNotFound:
case IProblem.JavadocUndefinedType:
UnresolvedElementsSubProcessor.getTypeProposals(context, problem, proposals);
break;
case IProblem.TypeMismatch:
LocalCorrectionsSubProcessor.addCastProposals(context, problem, proposals);
break;
case IProblem.UnhandledException:
LocalCorrectionsSubProcessor.addUncaughtExceptionProposals(context, problem, proposals);
break;
case IProblem.UnreachableCatch:
LocalCorrectionsSubProcessor.addUnreachableCatchProposals(context, problem, proposals);
break;
case IProblem.VoidMethodReturnsValue:
ReturnTypeSubProcessor.addVoidMethodReturnsProposals(context, problem, proposals);
break;
case IProblem.MissingReturnType:
ReturnTypeSubProcessor.addMissingReturnTypeProposals(context, problem, proposals);
break;
case IProblem.ShouldReturnValue:
ReturnTypeSubProcessor.addMissingReturnStatementProposals(context, problem, proposals);
break;
case IProblem.NonExternalizedStringLiteral:
LocalCorrectionsSubProcessor.addNLSProposals(context, problem, proposals);
break;
case IProblem.NonStaticAccessToStaticField:
case IProblem.NonStaticAccessToStaticMethod:
case IProblem.IndirectAccessToStaticField:
case IProblem.IndirectAccessToStaticMethod:
LocalCorrectionsSubProcessor.addCorrectAccessToStaticProposals(context, problem, proposals);
break;
case IProblem.StaticMethodRequested:
case IProblem.NonStaticFieldFromStaticInvocation:
case IProblem.InstanceMethodDuringConstructorInvocation:
case IProblem.InstanceFieldDuringConstructorInvocation:
ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_STATIC, 5);
break;
case IProblem.NonBlankFinalLocalAssignment:
case IProblem.DuplicateFinalLocalInitialization:
case IProblem.FinalFieldAssignment:
case IProblem.DuplicateBlankFinalFieldInitialization:
ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_FINAL, 9);
break;
case IProblem.FinalMethodCannotBeOverridden:
ModifierCorrectionSubProcessor.addOverridesFinalProposals(context, problem, proposals);
break;
case IProblem.NotVisibleMethod:
case IProblem.NotVisibleConstructor:
case IProblem.NotVisibleType:
case IProblem.SuperclassNotVisible:
case IProblem.InterfaceNotVisible:
case IProblem.FieldTypeNotVisible:
case IProblem.ArgumentTypeNotVisible:
case IProblem.ReturnTypeNotVisible:
case IProblem.ExceptionTypeNotVisible:
case IProblem.NotVisibleField:
case IProblem.ImportNotVisible:
case IProblem.JavadocNotVisibleType:
ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_VISIBLE, 10);
break;
case IProblem.BodyForAbstractMethod:
case IProblem.AbstractMethodInAbstractClass:
ModifierCorrectionSubProcessor.addAbstractMethodProposals(context, problem, proposals);
break;
case IProblem.AbstractMethodMustBeImplemented:
LocalCorrectionsSubProcessor.addUnimplementedMethodsProposals(context, problem, proposals);
break;
case IProblem.BodyForNativeMethod:
ModifierCorrectionSubProcessor.addNativeMethodProposals(context, problem, proposals);
break;
case IProblem.MethodRequiresBody:
ModifierCorrectionSubProcessor.addMethodRequiresBodyProposals(context, problem, proposals);
break;
case IProblem.OuterLocalMustBeFinal:
ModifierCorrectionSubProcessor.addNonFinalLocalProposal(context, problem, proposals);
break;
case IProblem.UninitializedLocalVariable:
LocalCorrectionsSubProcessor.addUninitializedLocalVariableProposal(context, problem, proposals);
break;
case IProblem.UnhandledExceptionInDefaultConstructor:
case IProblem.UndefinedConstructorInDefaultConstructor:
case IProblem.NotVisibleConstructorInDefaultConstructor:
LocalCorrectionsSubProcessor.addConstructorFromSuperclassProposal(context, problem, proposals);
break;
case IProblem.UnusedPrivateMethod:
case IProblem.UnusedPrivateConstructor:
case IProblem.UnusedPrivateField:
case IProblem.UnusedPrivateType:
case IProblem.LocalVariableIsNeverUsed:
case IProblem.ArgumentIsNeverUsed:
LocalCorrectionsSubProcessor.addUnusedMemberProposal(context, problem, proposals);
break;
case IProblem.NeedToEmulateFieldReadAccess:
case IProblem.NeedToEmulateFieldWriteAccess:
case IProblem.NeedToEmulateMethodAccess:
case IProblem.NeedToEmulateConstructorAccess:
ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_PRIVATE, 5);
break;
case IProblem.SuperfluousSemicolon:
LocalCorrectionsSubProcessor.addSuperfluousSemicolonProposal(context, problem, proposals);
break;
case IProblem.UnnecessaryCast:
case IProblem.UnnecessaryArgumentCast:
LocalCorrectionsSubProcessor.addUnnecessaryCastProposal(context, problem, proposals);
break;
case IProblem.UnnecessaryInstanceof:
LocalCorrectionsSubProcessor.addUnnecessaryInstanceofProposal(context, problem, proposals);
break;
case IProblem.UnusedMethodDeclaredThrownException:
case IProblem.UnusedConstructorDeclaredThrownException:
LocalCorrectionsSubProcessor.addUnnecessaryThrownExceptionProposal(context, problem, proposals);
break;
case IProblem.UnqualifiedFieldAccess:
LocalCorrectionsSubProcessor.addUnqualifiedFieldAccessProposal(context, problem, proposals);
break;
case IProblem.Task:
proposals.add(new TaskMarkerProposal(context.getCompilationUnit(), problem, 10));
break;
case IProblem.JavadocMissing:
JavadocTagsSubProcessor.getMissingJavadocCommentProposals(context, problem, proposals);
break;
case IProblem.JavadocMissingParamTag:
case IProblem.JavadocMissingReturnTag:
case IProblem.JavadocMissingThrowsTag:
JavadocTagsSubProcessor.getMissingJavadocTagProposals(context, problem, proposals);
break;
default:
}
}
}
|
38,176 |
Bug 38176 Quickfix for wrong casing on field could be improved
|
2.1 In the source for InternalPlatform, I added a field: boolean noVersionCheck. Elsewhere in the code, I made reference to it but got the casing wrong in an assignment: noversioncheck = false. Clicking on the light bulb gave me some suggestions, but the suggestion for noVersionCheck was far down the list. It would be nice if it checked for simple case mismatches. The list also included some static final fields, which can't be assigned to.
|
resolved fixed
|
96d505c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-03-19T17:15:35Z | 2003-05-28T02:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Renaud Waldura <[email protected]> - New class/interface with wizard
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.ISharedImages;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.ui.text.java.IInvocationContext;
import org.eclipse.jdt.ui.text.java.IProblemLocation;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportRewrite;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer;
import org.eclipse.jdt.internal.corext.dom.TypeRules;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.corext.util.TypeFilter;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.ChangeDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.EditDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.InsertDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.RemoveDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.SwapDescription;
public class UnresolvedElementsSubProcessor {
public static void getVariableProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveredNode(astRoot);
if (selectedNode == null) {
return;
}
// type that defines the variable
ITypeBinding binding= null;
ITypeBinding declaringTypeBinding= Bindings.getBindingOfParentType(selectedNode);
if (declaringTypeBinding == null) {
return;
}
// possible type kind of the node
boolean suggestVariableProposals= true;
int typeKind= 0;
while (selectedNode instanceof ParenthesizedExpression) {
selectedNode= ((ParenthesizedExpression) selectedNode).getExpression();
}
Name node= null;
switch (selectedNode.getNodeType()) {
case ASTNode.SIMPLE_NAME:
node= (SimpleName) selectedNode;
ASTNode parent= node.getParent();
if (parent instanceof MethodInvocation && node.equals(((MethodInvocation)parent).getExpression())) {
typeKind= SimilarElementsRequestor.CLASSES;
} else if (parent instanceof SimpleType) {
suggestVariableProposals= false;
typeKind= SimilarElementsRequestor.REF_TYPES;
} else if (parent instanceof QualifiedName) {
Name qualifier= ((QualifiedName) parent).getQualifier();
if (qualifier != node) {
binding= qualifier.resolveTypeBinding();
} else {
typeKind= SimilarElementsRequestor.REF_TYPES;
}
ASTNode outerParent= parent.getParent();
while (outerParent instanceof QualifiedName) {
outerParent= outerParent.getParent();
}
if (outerParent instanceof SimpleType) {
typeKind= SimilarElementsRequestor.REF_TYPES;
suggestVariableProposals= false;
}
}
break;
case ASTNode.QUALIFIED_NAME:
QualifiedName qualifierName= (QualifiedName) selectedNode;
ITypeBinding qualifierBinding= qualifierName.getQualifier().resolveTypeBinding();
if (qualifierBinding != null) {
node= qualifierName.getName();
binding= qualifierBinding;
} else {
node= qualifierName.getQualifier();
typeKind= SimilarElementsRequestor.REF_TYPES;
suggestVariableProposals= node.isSimpleName();
}
if (selectedNode.getParent() instanceof SimpleType) {
typeKind= SimilarElementsRequestor.REF_TYPES;
suggestVariableProposals= false;
}
break;
case ASTNode.FIELD_ACCESS:
FieldAccess access= (FieldAccess) selectedNode;
Expression expression= access.getExpression();
if (expression != null) {
binding= expression.resolveTypeBinding();
if (binding != null) {
node= access.getName();
}
}
break;
case ASTNode.SUPER_FIELD_ACCESS:
binding= declaringTypeBinding.getSuperclass();
node= ((SuperFieldAccess) selectedNode).getName();
break;
default:
}
if (node == null) {
return;
}
// add type proposals
if (typeKind != 0) {
int relevance= Character.isUpperCase(ASTResolving.getSimpleName(node).charAt(0)) ? 3 : 0;
addSimilarTypeProposals(typeKind, cu, node, relevance + 1, proposals);
addNewTypeProposals(cu, node, SimilarElementsRequestor.REF_TYPES, relevance, proposals);
}
if (!suggestVariableProposals) {
return;
}
SimpleName simpleName= node.isSimpleName() ? (SimpleName) node : ((QualifiedName) node).getName();
boolean isWriteAccess= ASTResolving.isWriteAccess(node);
// similar variables
addSimilarVariableProposals(cu, astRoot, simpleName, isWriteAccess, proposals);
// new fields
addNewFieldProposals(cu, astRoot, binding, declaringTypeBinding, simpleName, isWriteAccess, proposals);
// new parameters and local variables
if (binding == null) {
addNewVariableProposals(cu, node, simpleName, proposals);
}
}
private static void addNewVariableProposals(ICompilationUnit cu, Name node, SimpleName simpleName, Collection proposals) throws CoreException {
String name= simpleName.getIdentifier();
BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(node);
int type= bodyDeclaration.getNodeType();
if (type == ASTNode.METHOD_DECLARATION) {
int relevance= StubUtility.hasParameterName(cu.getJavaProject(), name) ? 8 : 5;
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createparameter.description", simpleName.getIdentifier()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.PARAM, simpleName, null, relevance, image));
}
if (type == ASTNode.METHOD_DECLARATION || type == ASTNode.INITIALIZER) {
int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7;
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createlocal.description", simpleName.getIdentifier()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.LOCAL, simpleName, null, relevance, image));
}
if (node.getParent().getNodeType() == ASTNode.ASSIGNMENT) {
Assignment assignment= (Assignment) node.getParent();
if (assignment.getLeftHandSide() == node && assignment.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
ASTNode statement= assignment.getParent();
ASTRewrite rewrite= new ASTRewrite(statement.getParent());
rewrite.markAsRemoved(statement, null);
String label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.removestatement.description"); //$NON-NLS-1$
Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 4, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
}
private static void addNewFieldProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, ITypeBinding declaringTypeBinding, SimpleName simpleName, boolean isWriteAccess, Collection proposals) throws JavaModelException {
// new variables
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding);
ITypeBinding senderBinding= binding != null ? binding : declaringTypeBinding;
if (!senderBinding.isFromSource() || targetCU == null || !JavaModelUtil.isEditable(targetCU)) {
return;
}
ITypeBinding outsideAnonymous= null;
if (binding == null && senderBinding.isAnonymous()) {
ASTNode anonymDecl= astRoot.findDeclaringNode(senderBinding);
if (anonymDecl != null) {
ITypeBinding bind= Bindings.getBindingOfParentType(anonymDecl.getParent());
if (!bind.isAnonymous()) {
outsideAnonymous= bind;
}
}
}
String name= simpleName.getIdentifier();
int relevance= StubUtility.hasFieldName(cu.getJavaProject(), name) ? 9 : 6;
String label;
Image image;
if (binding == null) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.description", name); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE);
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { name, binding.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
}
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, relevance, image));
// create field in outer class (if inside anonymous)
if (outsideAnonymous != null) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { name, outsideAnonymous.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, outsideAnonymous, relevance + 1, image));
}
// create constant
if (!isWriteAccess) {
relevance= StubUtility.hasConstantName(name) ? 9 : 4;
ITypeBinding target= (outsideAnonymous != null) ? outsideAnonymous : senderBinding;
if (binding == null) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconst.description", name); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE);
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconst.other.description", new Object[] { name, binding.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
}
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.CONST_FIELD, simpleName, target, relevance, image));
}
}
private static void addSimilarVariableProposals(ICompilationUnit cu, CompilationUnit astRoot, SimpleName node, boolean isWriteAccess, Collection proposals) {
IBinding[] varsInScope= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(node, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY);
if (varsInScope.length > 0) {
// avoid corrections like int i= i;
String otherNameInAssign= null;
ASTNode parent= node.getParent();
if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
// node must be initializer
otherNameInAssign= ((VariableDeclarationFragment) parent).getName().getIdentifier();
} else if (parent.getNodeType() == ASTNode.ASSIGNMENT) {
Assignment assignment= (Assignment) parent;
if (isWriteAccess && assignment.getRightHandSide() instanceof SimpleName) {
otherNameInAssign= ((SimpleName) assignment.getRightHandSide()).getIdentifier();
} else if (!isWriteAccess && assignment.getLeftHandSide() instanceof SimpleName) {
otherNameInAssign= ((SimpleName) assignment.getLeftHandSide()).getIdentifier();
}
}
ITypeBinding guessedType= ASTResolving.guessBindingForReference(node);
if (astRoot.getAST().resolveWellKnownType("java.lang.Object") == guessedType) { //$NON-NLS-1$
guessedType= null; // too many suggestions
}
String identifier= node.getIdentifier();
for (int i= 0; i < varsInScope.length; i++) {
IVariableBinding curr= (IVariableBinding) varsInScope[i];
String currName= curr.getName();
boolean isFinal= Modifier.isFinal(curr.getModifiers());
if (!currName.equals(otherNameInAssign) && !(isFinal && curr.isField() && isWriteAccess)) {
int relevance= 0;
if (NameMatcher.isSimilarName(currName, identifier)) {
relevance += 3; // variable with a similar name than the unresolved variable
}
ITypeBinding varType= curr.getType();
if (guessedType != null && varType != null) {
if (!isWriteAccess && TypeRules.canAssign(varType, guessedType)
|| isWriteAccess && TypeRules.canAssign(guessedType, varType)) {
relevance += 2; // unresolved variable can be assign to this variable
}
}
if (relevance > 0) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changevariable.description", currName); //$NON-NLS-1$
proposals.add(new RenameNodeCompletionProposal(label, cu, node.getStartPosition(), node.getLength(), currName, relevance));
}
}
}
}
}
public static void getTypeProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (selectedNode == null) {
return;
}
int kind= SimilarElementsRequestor.ALL_TYPES;
ASTNode parent= selectedNode.getParent();
while (parent.getLength() == selectedNode.getLength()) { // get parent of type or variablefragment
parent= parent.getParent();
}
switch (parent.getNodeType()) {
case ASTNode.TYPE_DECLARATION:
TypeDeclaration typeDeclaration=(TypeDeclaration) parent;
if (typeDeclaration.superInterfaces().contains(selectedNode)) {
kind= SimilarElementsRequestor.INTERFACES;
} else if (selectedNode.equals(typeDeclaration.getSuperclass())) {
kind= SimilarElementsRequestor.CLASSES;
}
break;
case ASTNode.METHOD_DECLARATION:
MethodDeclaration methodDeclaration= (MethodDeclaration) parent;
if (methodDeclaration.thrownExceptions().contains(selectedNode)) {
kind= SimilarElementsRequestor.CLASSES;
} else if (selectedNode.equals(methodDeclaration.getReturnType())) {
kind= SimilarElementsRequestor.ALL_TYPES | SimilarElementsRequestor.VOIDTYPE;
}
break;
case ASTNode.INSTANCEOF_EXPRESSION:
kind= SimilarElementsRequestor.REF_TYPES;
break;
case ASTNode.THROW_STATEMENT:
kind= SimilarElementsRequestor.REF_TYPES;
break;
case ASTNode.CLASS_INSTANCE_CREATION:
if (((ClassInstanceCreation) parent).getAnonymousClassDeclaration() == null) {
kind= SimilarElementsRequestor.CLASSES;
} else {
kind= SimilarElementsRequestor.REF_TYPES;
}
break;
case ASTNode.SINGLE_VARIABLE_DECLARATION:
int superParent= parent.getParent().getNodeType();
if (superParent == ASTNode.CATCH_CLAUSE) {
kind= SimilarElementsRequestor.CLASSES;
}
break;
case ASTNode.TAG_ELEMENT:
kind= SimilarElementsRequestor.REF_TYPES;
break;
default:
}
Name node= null;
if (selectedNode instanceof SimpleType) {
node= ((SimpleType) selectedNode).getName();
} else if (selectedNode instanceof ArrayType) {
Type elementType= ((ArrayType) selectedNode).getElementType();
if (elementType.isSimpleType()) {
node= ((SimpleType) elementType).getName();
}
} else if (selectedNode instanceof Name) {
node= (Name) selectedNode;
} else {
return;
}
// change to simlar type proposals
addSimilarTypeProposals(kind, cu, node, 3, proposals);
// add type
addNewTypeProposals(cu, node, kind, 0, proposals);
}
private static void addSimilarTypeProposals(int kind, ICompilationUnit cu, Name node, int relevance, Collection proposals) throws CoreException {
SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, node, kind);
// try to resolve type in context -> highest severity
String resolvedTypeName= null;
ITypeBinding binding= ASTResolving.guessBindingForTypeReference(node);
if (binding != null) {
if (binding.isArray()) {
binding= binding.getElementType();
}
resolvedTypeName= binding.getQualifiedName();
proposals.add(createTypeRefChangeProposal(cu, resolvedTypeName, node, relevance + 2));
}
// add all similar elements
for (int i= 0; i < elements.length; i++) {
SimilarElement elem= elements[i];
if ((elem.getKind() & SimilarElementsRequestor.ALL_TYPES) != 0) {
String fullName= elem.getName();
if (!fullName.equals(resolvedTypeName)) {
proposals.add(createTypeRefChangeProposal(cu, fullName, node, relevance));
}
}
}
}
private static CUCorrectionProposal createTypeRefChangeProposal(ICompilationUnit cu, String fullName, Name node, int relevance) throws CoreException {
ImportRewrite importRewrite= new ImportRewrite(cu);
importRewrite.setFindAmbiguosImports(true);
String simpleName= importRewrite.addImport(fullName);
String packName= Signature.getQualifier(fullName);
String[] arg= { simpleName, packName };
CUCorrectionProposal proposal;
if (node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) { // import only
// import only
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importtype.description", arg); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL);
proposal= new CUCorrectionProposal(label, cu, relevance + 100, image);
} else {
String label;
if (packName.length() == 0) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.nopack.description", simpleName); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.description", arg); //$NON-NLS-1$
}
proposal= new RenameNodeCompletionProposal(label, cu, node.getStartPosition(), node.getLength(), simpleName, relevance); //$NON-NLS-1$
}
proposal.setImportRewrite(importRewrite);
return proposal;
}
private static void addNewTypeProposals(ICompilationUnit cu, Name refNode, int kind, int relevance, Collection proposals) throws JavaModelException {
Name node= refNode;
do {
String typeName= ASTResolving.getSimpleName(node);
Name qualifier= null;
// only propose to create types for qualifiers when the name starts with upper case
boolean isPossibleName= Character.isUpperCase(typeName.charAt(0)) || (node == refNode);
if (isPossibleName) {
IPackageFragment enclosingPackage= null;
IType enclosingType= null;
if (node.isSimpleName()) {
enclosingPackage= (IPackageFragment) cu.getParent();
// don't sugest member type, user can select it in wizard
} else {
Name qualifierName= ((QualifiedName) node).getQualifier();
// 24347
// IBinding binding= qualifierName.resolveBinding();
// if (binding instanceof ITypeBinding) {
// enclosingType= Binding2JavaModel.find((ITypeBinding) binding, cu.getJavaProject());
IJavaElement[] res= cu.codeSelect(qualifierName.getStartPosition(), qualifierName.getLength());
if (res!= null && res.length > 0 && res[0] instanceof IType) {
enclosingType= (IType) res[0];
} else {
qualifier= qualifierName;
enclosingPackage= JavaModelUtil.getPackageFragmentRoot(cu).getPackageFragment(ASTResolving.getFullName(qualifierName));
}
}
// new top level type
if (enclosingPackage != null && !enclosingPackage.getCompilationUnit(typeName + ".java").exists()) { //$NON-NLS-1$
if ((kind & SimilarElementsRequestor.CLASSES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingPackage, relevance));
}
if ((kind & SimilarElementsRequestor.INTERFACES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingPackage, relevance));
}
}
// new member type
if (enclosingType != null && !enclosingType.isReadOnly() && !enclosingType.getType(typeName).exists()) {
if ((kind & SimilarElementsRequestor.CLASSES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingType, relevance));
}
if ((kind & SimilarElementsRequestor.INTERFACES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingType, relevance));
}
}
}
node= qualifier;
} while (node != null);
}
public static void getMethodProposals(IInvocationContext context, IProblemLocation problem, boolean needsNewName, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(astRoot);
if (!(selectedNode instanceof SimpleName)) {
return;
}
SimpleName nameNode= (SimpleName) selectedNode;
List arguments;
Expression sender;
boolean isSuperInvocation;
ASTNode invocationNode= nameNode.getParent();
if (invocationNode instanceof MethodInvocation) {
MethodInvocation methodImpl= (MethodInvocation) invocationNode;
arguments= methodImpl.arguments();
sender= methodImpl.getExpression();
isSuperInvocation= false;
} else if (invocationNode instanceof SuperMethodInvocation) {
SuperMethodInvocation methodImpl= (SuperMethodInvocation) invocationNode;
arguments= methodImpl.arguments();
sender= methodImpl.getQualifier();
isSuperInvocation= true;
} else {
return;
}
String methodName= nameNode.getIdentifier();
int nArguments= arguments.size();
// corrections
IBinding[] bindings= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(nameNode, ScopeAnalyzer.METHODS);
ArrayList parameterMismatchs= new ArrayList();
for (int i= 0; i < bindings.length; i++) {
IMethodBinding binding= (IMethodBinding) bindings[i];
String curr= binding.getName();
if (curr.equals(methodName) && needsNewName) {
parameterMismatchs.add(binding);
} else if (binding.getParameterTypes().length == nArguments && NameMatcher.isSimilarName(methodName, curr)) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changemethod.description", curr); //$NON-NLS-1$
proposals.add(new RenameNodeCompletionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), curr, 6));
}
}
addParameterMissmatchProposals(context, problem, parameterMismatchs, invocationNode, arguments, proposals);
// new method
ITypeBinding binding= null;
if (sender != null) {
binding= sender.resolveTypeBinding();
} else {
binding= Bindings.getBindingOfParentType(invocationNode);
if (isSuperInvocation && binding != null) {
binding= binding.getSuperclass();
}
}
if (binding != null && binding.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding);
if (targetCU != null) {
String label;
Image image;
String sig= getMethodSignature(methodName, arguments);
if (cu.equals(targetCU)) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.description", sig); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE);
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", new Object[] { sig, targetCU.getElementName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
}
proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 5, image));
if (binding.isAnonymous() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(binding, methodName, null) == null) { // no covering method
ASTNode anonymDecl= astRoot.findDeclaringNode(binding);
if (anonymDecl != null) {
binding= Bindings.getBindingOfParentType(anonymDecl.getParent());
if (!binding.isAnonymous()) {
String[] args= new String[] { sig, binding.getName() };
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", args); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED);
proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 5, image));
}
}
}
}
}
if (!isSuperInvocation) {
ASTNode parent= invocationNode.getParent();
while (parent instanceof Expression && parent.getNodeType() != ASTNode.CAST_EXPRESSION) {
parent= parent.getParent();
}
if (!isSuperInvocation && parent instanceof CastExpression) {
addMissingCastParentsProposal(cu, (CastExpression) parent, sender, nameNode, getArgumentTypes(arguments), proposals);
}
}
}
private static void addMissingCastParentsProposal(ICompilationUnit cu, CastExpression expression, Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes, Collection proposals) throws CoreException {
ITypeBinding castType= expression.getType().resolveBinding();
if (castType == null) {
return;
}
if (paramTypes != null) {
if (Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes) == null) {
return;
}
} else if (Bindings.findFieldInHierarchy(castType, accessSelector.getIdentifier()) == null) {
return;
}
ITypeBinding bindingToCast= accessExpression.resolveTypeBinding();
if (bindingToCast != null && !TypeRules.canCast(castType, bindingToCast)) {
return;
}
IMethodBinding res= Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes);
if (res != null) {
AST ast= expression.getAST();
ASTRewrite rewrite= new ASTRewrite(expression.getParent());
CastExpression newCast= ast.newCastExpression();
newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType()));
newCast.setExpression((Expression) rewrite.createCopy(accessExpression));
ParenthesizedExpression parents= ast.newParenthesizedExpression();
parents.setExpression(newCast);
ASTNode node= rewrite.createCopy(expression.getExpression());
rewrite.markAsReplaced(expression, node, null);
rewrite.markAsReplaced(accessExpression, parents, null);
String label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.missingcastbrackets.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 8, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
private static void addParameterMissmatchProposals(IInvocationContext context, IProblemLocation problem, List similarElements, ASTNode invocationNode, List arguments, Collection proposals) throws CoreException {
int nSimilarElements= similarElements.size();
ITypeBinding[] argTypes= getArgumentTypes(arguments);
if (argTypes == null || nSimilarElements == 0) {
return;
}
for (int i= 0; i < nSimilarElements; i++) {
IMethodBinding elem = (IMethodBinding) similarElements.get(i);
int diff= elem.getParameterTypes().length - argTypes.length;
if (diff == 0) {
int nProposals= proposals.size();
doEqualNumberOfParameters(context, invocationNode, problem, arguments, argTypes, elem, proposals);
if (nProposals != proposals.size()) {
return; // only suggest for one method (avoid duplicated proposals)
}
} else if (diff > 0) {
doMoreParameters(context, problem, invocationNode, arguments, argTypes, elem, proposals);
} else {
doMoreArguments(context, problem, invocationNode, arguments, argTypes, elem, proposals);
}
}
}
private static void doMoreParameters(IInvocationContext context, IProblemLocation problem, ASTNode invocationNode, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException {
ITypeBinding[] paramTypes= methodBinding.getParameterTypes();
int k= 0, nSkipped= 0;
int diff= paramTypes.length - argTypes.length;
int[] indexSkipped= new int[diff];
for (int i= 0; i < paramTypes.length; i++) {
if (k < argTypes.length && TypeRules.canAssign(argTypes[k], paramTypes[i])) {
k++; // match
} else {
if (nSkipped >= diff) {
return; // too different
}
indexSkipped[nSkipped++]= i;
}
}
ITypeBinding declaringType= methodBinding.getDeclaringClass();
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
// add arguments
{
String[] arg= new String[] { getMethodSignature(methodBinding, false) };
String label;
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargument.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addarguments.description", arg); //$NON-NLS-1$
}
AddArgumentCorrectionProposal proposal= new AddArgumentCorrectionProposal(label, context.getCompilationUnit(), invocationNode, indexSkipped, paramTypes, 8);
proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD));
proposal.ensureNoModifications();
proposals.add(proposal);
}
// remove parameters
if (!declaringType.isFromSource()) {
return;
}
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
if (targetCU != null) {
ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length];
ITypeBinding[] changedTypes= new ITypeBinding[diff];
for (int i= diff - 1; i >= 0; i--) {
int idx= indexSkipped[i];
changeDesc[idx]= new RemoveDescription();
changedTypes[i]= paramTypes[idx];
}
String[] arg= new String[] { getMethodSignature(methodBinding, !cu.equals(targetCU)), getTypeNames(changedTypes) };
String label;
if (methodBinding.isConstructor()) {
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparam.constr.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparams.constr.description", arg); //$NON-NLS-1$
}
} else {
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparam.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparams.description", arg); //$NON-NLS-1$
}
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE);
ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, 5, image);
proposals.add(proposal);
}
}
private static String getTypeNames(ITypeBinding[] types) {
StringBuffer buf= new StringBuffer();
for (int i= 0; i < types.length; i++) {
if (i > 0) {
buf.append(", "); //$NON-NLS-1$
}
buf.append(types[i].getName());
}
return buf.toString();
}
private static String getArgumentName(ICompilationUnit cu, List arguments, int index) {
String def= String.valueOf(index + 1);
ASTNode expr= (ASTNode) arguments.get(index);
if (expr.getLength() > 18) {
return def;
}
try {
String str= cu.getBuffer().getText(expr.getStartPosition(), expr.getLength());
for (int i= 0; i < str.length(); i++) {
if (Strings.isLineDelimiterChar(str.charAt(i))) {
return def;
}
}
ASTMatcher matcher= new ASTMatcher();
for (int i= 0; i < arguments.size(); i++) {
if (i != index && matcher.safeSubtreeMatch(expr, arguments.get(i))) {
return def;
}
}
return '\'' + str + '\'';
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return def;
}
private static void doMoreArguments(IInvocationContext context, IProblemLocation problem, ASTNode invocationNode, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException {
ITypeBinding[] paramTypes= methodBinding.getParameterTypes();
int k= 0, nSkipped= 0;
int diff= argTypes.length - paramTypes.length;
int[] indexSkipped= new int[diff];
for (int i= 0; i < argTypes.length; i++) {
if (k < paramTypes.length && TypeRules.canAssign(argTypes[i], paramTypes[k])) {
k++; // match
} else {
if (nSkipped >= diff) {
return; // too different
}
indexSkipped[nSkipped++]= i;
}
}
ITypeBinding declaringType= methodBinding.getDeclaringClass();
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
// remove arguments
{
ASTNode selectedNode= problem.getCoveringNode(astRoot);
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
for (int i= diff - 1; i >= 0; i--) {
rewrite.markAsRemoved((Expression) arguments.get(indexSkipped[i]), null);
}
String[] arg= new String[] { getMethodSignature(methodBinding, false) };
String label;
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeargument.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removearguments.description", arg); //$NON-NLS-1$
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
// add parameters
if (!declaringType.isFromSource()) {
return;
}
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
if (targetCU != null) {
boolean isDifferentCU= !cu.equals(targetCU);
if (isImplicitConstructor(methodBinding, targetCU)) {
return;
}
ChangeDescription[] changeDesc= new ChangeDescription[argTypes.length];
ITypeBinding[] changeTypes= new ITypeBinding[diff];
for (int i= diff - 1; i >= 0; i--) {
int idx= indexSkipped[i];
Expression arg= (Expression) arguments.get(idx);
String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null;
ITypeBinding newType= Bindings.normalizeTypeBinding(argTypes[idx]);
if (newType == null) {
newType= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
changeDesc[idx]= new InsertDescription(newType, name);
changeTypes[i]= newType;
}
String[] arg= new String[] { getMethodSignature(methodBinding, isDifferentCU), getTypeNames(changeTypes) };
String label;
if (methodBinding.isConstructor()) {
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparam.constr.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparams.constr.description", arg); //$NON-NLS-1$
}
} else {
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparam.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparams.description", arg); //$NON-NLS-1$
}
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, 5, image);
proposals.add(proposal);
}
}
private static boolean isImplicitConstructor(IMethodBinding meth, ICompilationUnit targetCU) {
if (meth.isConstructor() && meth.getParameterTypes().length == 0) {
IMethodBinding[] bindings= meth.getDeclaringClass().getDeclaredMethods();
// implicit constructors must be the only constructor
for (int i= 0; i < bindings.length; i++) {
IMethodBinding curr= bindings[i];
if (curr.isConstructor() && curr != meth) {
return false;
}
}
ASTParser parser= ASTParser.newParser(AST.LEVEL_2_0);
parser.setSource(targetCU);
parser.setFocalPosition(0);
parser.setResolveBindings(true);
CompilationUnit unit= (CompilationUnit) parser.createAST(null);
return unit.findDeclaringNode(meth.getKey()) == null;
}
return false;
}
private static String getMethodSignature(IMethodBinding binding, boolean inOtherCU) {
StringBuffer buf= new StringBuffer();
if (inOtherCU && !binding.isConstructor()) {
buf.append(binding.getDeclaringClass().getName()).append('.');
}
buf.append(binding.getName());
return getMethodSignature(buf.toString(), binding.getParameterTypes());
}
private static String getMethodSignature(String name, List args) {
ITypeBinding[] params= new ITypeBinding[args.size()];
for (int i= 0; i < args.size(); i++) {
Expression expr= (Expression) args.get(i);
ITypeBinding curr= Bindings.normalizeTypeBinding(expr.resolveTypeBinding());
if (curr == null) {
curr= expr.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
params[i]= curr;
}
return getMethodSignature(name, params);
}
private static String getMethodSignature(String name, ITypeBinding[] params) {
StringBuffer buf= new StringBuffer();
buf.append(name).append('(');
for (int i= 0; i < params.length; i++) {
if (i > 0) {
buf.append(", "); //$NON-NLS-1$
}
buf.append(params[i].getName());
}
buf.append(')');
return buf.toString();
}
private static void doEqualNumberOfParameters(IInvocationContext context, ASTNode invocationNode, IProblemLocation problem, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException {
ITypeBinding[] paramTypes= methodBinding.getParameterTypes();
int[] indexOfDiff= new int[paramTypes.length];
int nDiffs= 0;
for (int n= 0; n < argTypes.length; n++) {
if (!TypeRules.canAssign(argTypes[n], paramTypes[n])) {
indexOfDiff[nDiffs++]= n;
}
}
ITypeBinding declaringType= methodBinding.getDeclaringClass();
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode nameNode= problem.getCoveringNode(astRoot);
if (nameNode == null) {
return;
}
if (nDiffs == 0) {
if (nameNode.getParent() instanceof MethodInvocation) {
MethodInvocation inv= (MethodInvocation) nameNode.getParent();
if (inv.getExpression() == null) {
addQualifierToOuterProposal(context, inv, methodBinding, proposals);
}
}
return;
}
if (nDiffs == 1) { // one argument missmatching: try to fix
int idx= indexOfDiff[0];
Expression nodeToCast= (Expression) arguments.get(idx);
ITypeBinding castType= paramTypes[idx];
ITypeBinding binding= nodeToCast.resolveTypeBinding();
if (binding == null || TypeRules.canCast(castType, binding)) {
String castTypeName= castType.getQualifiedName();
ASTRewriteCorrectionProposal proposal= LocalCorrectionsSubProcessor.createCastProposal(context, castTypeName, nodeToCast, 6);
String[] arg= new String[] { getArgumentName(cu, arguments, idx), castTypeName};
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargumentcast.description", arg)); //$NON-NLS-1$
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (nDiffs == 2) { // try to swap
int idx1= indexOfDiff[0];
int idx2= indexOfDiff[1];
boolean canSwap= TypeRules.canAssign(argTypes[idx1], paramTypes[idx2]) && TypeRules.canAssign(argTypes[idx2], paramTypes[idx1]);
if (canSwap) {
Expression arg1= (Expression) arguments.get(idx1);
Expression arg2= (Expression) arguments.get(idx2);
ASTRewrite rewrite= new ASTRewrite(arg1.getParent());
rewrite.markAsReplaced(arg1, rewrite.createCopy(arg2), null);
rewrite.markAsReplaced(arg2, rewrite.createCopy(arg1), null);
{
String[] arg= new String[] { getArgumentName(cu, arguments, idx1), getArgumentName(cu, arguments, idx2) };
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swaparguments.description", arg); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
if (declaringType.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
if (targetCU != null) {
ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length];
for (int i= 0; i < nDiffs; i++) {
changeDesc[idx1]= new SwapDescription(idx2);
}
ITypeBinding[] swappedTypes= new ITypeBinding[] { paramTypes[idx1], paramTypes[idx2] };
String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getTypeNames(swappedTypes) };
String label;
if (methodBinding.isConstructor()) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swapparams.constr.description", args); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swapparams.description", args); //$NON-NLS-1$
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, 5, image);
proposals.add(proposal);
}
}
return;
}
}
if (declaringType.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
if (targetCU != null) {
ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length];
for (int i= 0; i < nDiffs; i++) {
int diffIndex= indexOfDiff[i];
Expression arg= (Expression) arguments.get(diffIndex);
String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null;
changeDesc[diffIndex]= new EditDescription(argTypes[diffIndex], name);
}
String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getMethodSignature(methodBinding.getName(), arguments) };
String label;
if (methodBinding.isConstructor()) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changeparamsignature.constr.description", args); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changeparamsignature.description", args); //$NON-NLS-1$
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, 7, image);
proposals.add(proposal);
}
}
}
private static ITypeBinding[] getArgumentTypes(List arguments) {
ITypeBinding[] res= new ITypeBinding[arguments.size()];
for (int i= 0; i < res.length; i++) {
Expression expression= (Expression) arguments.get(i);
ITypeBinding curr= expression.resolveTypeBinding();
if (curr == null) {
return null;
}
curr= Bindings.normalizeTypeBinding(curr);
if (curr == null) {
curr= expression.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
res[i]= curr;
}
return res;
}
private static void addQualifierToOuterProposal(IInvocationContext context, MethodInvocation invocationNode, IMethodBinding binding, Collection proposals) throws CoreException {
ITypeBinding declaringType= binding.getDeclaringClass();
ITypeBinding parentType= Bindings.getBindingOfParentType(invocationNode);
ITypeBinding currType= parentType;
boolean isInstanceMethod= !Modifier.isStatic(binding.getModifiers());
while (currType != null && !Bindings.isSuperType(declaringType, currType)) {
if (isInstanceMethod && Modifier.isStatic(currType.getModifiers())) {
return;
}
currType= currType.getDeclaringClass();
}
if (currType == null || currType == parentType) {
return;
}
ASTRewrite rewrite= new ASTRewrite(invocationNode.getParent());
ImportRewrite imports= new ImportRewrite(context.getCompilationUnit());
AST ast= invocationNode.getAST();
String qualifier= imports.addImport(currType);
Name name= ASTNodeFactory.newName(ast, qualifier);
Expression newExpression;
if (isInstanceMethod) {
ThisExpression expr= ast.newThisExpression();
expr.setQualifier(name);
newExpression= expr;
} else {
newExpression= name;
}
rewrite.set(invocationNode, MethodInvocation.EXPRESSION_PROPERTY, newExpression, null);
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetoouter.description", currType.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image);
proposal.setImportRewrite(imports);
proposal.ensureNoModifications();
proposals.add(proposal);
}
public static void getConstructorProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(astRoot);
if (selectedNode == null) {
return;
}
ITypeBinding targetBinding= null;
List arguments= null;
IMethodBinding recursiveConstructor= null;
int type= selectedNode.getNodeType();
if (type == ASTNode.CLASS_INSTANCE_CREATION) {
ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode;
IBinding binding= creation.getName().resolveBinding();
if (binding instanceof ITypeBinding) {
targetBinding= (ITypeBinding) binding;
arguments= creation.arguments();
}
} else if (type == ASTNode.SUPER_CONSTRUCTOR_INVOCATION) {
ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode);
if (typeBinding != null && !typeBinding.isAnonymous()) {
targetBinding= typeBinding.getSuperclass();
arguments= ((SuperConstructorInvocation) selectedNode).arguments();
}
} else if (type == ASTNode.CONSTRUCTOR_INVOCATION) {
ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode);
if (typeBinding != null && !typeBinding.isAnonymous()) {
targetBinding= typeBinding;
arguments= ((ConstructorInvocation) selectedNode).arguments();
recursiveConstructor= ASTResolving.findParentMethodDeclaration(selectedNode).resolveBinding();
}
}
if (targetBinding == null) {
return;
}
IMethodBinding[] methods= targetBinding.getDeclaredMethods();
ArrayList similarElements= new ArrayList();
for (int i= 0; i < methods.length; i++) {
IMethodBinding curr= methods[i];
if (curr.isConstructor() && recursiveConstructor != curr) {
similarElements.add(curr); // similar elements can contain a implicit default constructor
}
}
addParameterMissmatchProposals(context, problem, similarElements, selectedNode, arguments, proposals);
if (targetBinding.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, targetBinding);
if (targetCU != null) {
String[] args= new String[] { getMethodSignature( targetBinding.getName(), arguments) };
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconstructor.description", args); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
proposals.add(new NewMethodCompletionProposal(label, targetCU, selectedNode, arguments, targetBinding, 5, image));
}
}
}
public static void getAmbiguosTypeReferenceProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
int offset= problem.getOffset();
int len= problem.getLength();
IJavaElement[] elements= cu.codeSelect(offset, len);
for (int i= 0; i < elements.length; i++) {
IJavaElement curr= elements[i];
if (curr instanceof IType && !TypeFilter.isFiltered((IType) curr)) {
String qualifiedTypeName= JavaModelUtil.getFullyQualifiedName((IType) curr);
ImportRewrite imports= new ImportRewrite(cu);
imports.setFindAmbiguosImports(true);
imports.addImport(qualifiedTypeName);
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importexplicit.description", qualifiedTypeName); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL);
CUCorrectionProposal proposal= new CUCorrectionProposal(label, cu, 5, image);
proposal.setImportRewrite(imports);
proposals.add(proposal);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.